Skip to content

if MYPY guarding an always-return block v. unreachable #11380

Open
@gsnedders

Description

@gsnedders

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-reachabilityDetecting unreachable code

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions