Skip to content

Two possibly-undefined bugs with match statements #15958

Closed
@AlexWaygood

Description

@AlexWaygood

Bug Report

We're seeing two bugs relating to the possibly-undefined error code over at python/cpython#108454

To Reproduce

  1. Save the following code to a file repro.py
  2. Run mypy --enable-error-code=possibly-undefined repro.py
  3. Run mypy --enable-error-code=possibly-undefined repro.py --warn-unreachable
from typing_extensions import assert_never

x: int | str
match x:
    case str():
        f = 'foo'
    case int():
        f = 'bar'
    case _:
        assert_never(x)

print(f)

Expected Behavior

Neither invocation of mypy should result in any errors being emitted. The match statement is an exhaustive match, so there's no possibility that f could be undefined by the end of the match x statement.

Actual Behavior

mypy --enable-error-code=possibly-undefined repro.py produces this output, which seems like a false positive:

> mypy --enable-error-code=possibly-undefined repro.py
repro.py:12: error: Name "f" may be undefined  [possibly-undefined]
Found 1 error in 1 file (checked 1 source file)

What's particularly strange, however, is that adding --warn-unreachable makes the error go away:

> mypy --enable-error-code=possibly-undefined --warn-unreachable repro.py
Success: no issues found in 1 source file

It seems like there's two bugs here:

  1. The possibly-undefined error is a false positive
  2. Adding --warn-unreachable to the config reduces the number of possibly-undefined errors emitted by mypy, and it seems like it definitely shouldn't be doing that.

Cc. @ilinum for possibly-undefined expertise :)

Your Environment

  • Mypy version used: 1.5.1
  • Python version used: 3.11

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions