python / python/mypy

if MYPY guarding an always-return block v. unreachable

Open
#11,380 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-reachability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Given a block dependent on if MYPY, if it always returns, mypy will conclude that everything following is unreachable. This shouldn't be obviously different to using an else block.

To Reproduce

from typing import Any, cast

MYPY = False

def foo(p):
    # type: (Any) -> int
    doc = p
    if MYPY:
        return cast(int, doc)
    else:
        # needs to be in else for MYPY to believe this is reachable
        return doc

def bar(p):
    # type: (Any) -> int
    doc = p
    if MYPY:
        return cast(int, doc)
    return doc

Expected Behavior

Either both output [unreachable] or both type check successfully.

Actual Behavior

foo.py:19: error: Statement is unreachable  [unreachable]

i.e.: only bar fails to typecheck

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: --warn-unreachable
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10.0
  • Operating system and version: Arch Linux

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No source file or test is named. First reproduce the example with mypy 0.910 and --warn-unreachable, then trace the reachability handling for an if MYPY block versus an else block. Done means both equivalent examples either type-check successfully or report unreachable consistently.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.