Skip to content

Structural Pattern Matching False Positive With Nested Data Structures #12770

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
Kurt-von-Laven opened this issue May 11, 2022 · 0 comments · Fixed by #18448
Closed

Structural Pattern Matching False Positive With Nested Data Structures #12770

Kurt-von-Laven opened this issue May 11, 2022 · 0 comments · Fixed by #18448
Labels
bug mypy got something wrong topic-match-statement Python 3.10's match statement topic-reachability Detecting unreachable code

Comments

@Kurt-von-Laven
Copy link

Kurt-von-Laven commented May 11, 2022

Bug Report

mypy underestimates the reachability of case blocks matching Any (or data structures containing Any) against nested data structures. This particularly impacts the use of structural pattern matching to parse JSON and other data formats that frequently include recursive data structures. It's difficult to avoid using Any for some portion of the type in these cases, so for now I believe the best workaround in these cases is to set warn_unreachable to false or suppress the mypy errors on the pertinent lines.

To Reproduce

  1. Create a test.py file with the following contents:

    from typing import Any
    
    def test_structural_pattern_matching(x: Any) -> Any:
        match x:
            case {"y": [z]}:
                print("mypy believes this line is unreachable")
            case _:
                return None
  2. Run mypy test.py with warn_unreachable set to true.

Expected Behavior

I expected all lines to be considered reachable since x may be {"y": [0]}, for instance.

Actual Behavior

$ mypy test.py
test.py:6: error: Statement is unreachable
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 0.960+dev.8faf44ad44f19c2dcf3f31f12eed5e58494fc3a3

  • Mypy command-line flags: None

  • Mypy configuration options from mypy.ini (and other config files):

    In pyproject.toml:

      [tool.mypy]
      warn_unreachable = true
  • Python version used: 3.10.4

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
bug mypy got something wrong topic-match-statement Python 3.10's match statement topic-reachability Detecting unreachable code
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants