python / python/mypy

type narrowing leads to "unreachable" code being actually reachable

Open
#12,598 2 comments 1 reaction 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

To Reproduce

class Foo:
    def foo(self) -> None:
        print("Foo!!!")

class Bar:
    def __init__(self) -> None:
        self.foo: Foo | None = Foo()

    def get_rid_of_foo(self) -> None:
        self.foo = None


bar = Bar()
if bar.foo is not None:
    bar.get_rid_of_foo()
    assert bar.foo is None
    print(1 + "lol")

Expected Behavior

An error for the obviously wrong print(1 + "lol"). It fails there at runtime.

Actual Behavior

no errors!

Your Environment

mypy 0.942 with --python-version 3.10

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

Start by running the reproducer with mypy 0.942 and --python-version 3.10, then trace how narrowing around bar.foo behaves after get_rid_of_foo(). Done means mypy reports the invalid 1 + "lol" expression while preserving valid narrowing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.