Bug Report
It seems like mypy is having trouble deducing the type of generic attributes in match statements. If __match_args__ contains a generic attribute, this attribute becomes Any after case matching.
To Reproduce
Run mypy on the code below
from typing import Generic, TypeVar
T = TypeVar("T")
class A(Generic[T]):
x: T
__match_args__ = ("x",)
def __init__(self, x: T):
self.x = x
a = A("foo")
reveal_type(a) # A[str] (correct)
reveal_type(a.x) # builtins.str (correct)
match a:
case A(b):
reveal_type(b) # Any (incorrect! Should be builtins.str)
Expected Behavior
The total output should be:
Revealed type is "mycode.A[builtins.str]"
Revealed type is "builtins.str"
Revealed type is "builtins.str"
Actual Behavior
the last line doesn't reveal builtins.str
Revealed type is "mycode.A[builtins.str]"
Revealed type is "builtins.str"
Revealed type is "Any"
Your Environment
- Mypy version used: 0.971 (also occurs on
master branch)
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini (and other config files): none
- Python version used: 3.10.5
- Operating system and version: MacOS 12.5.1
What I've found so far
Bug Report
It seems like
mypyis having trouble deducing the type of generic attributes inmatchstatements. If__match_args__contains a generic attribute, this attribute becomesAnyaftercasematching.To Reproduce
Run
mypyon the code belowExpected Behavior
The total output should be:
Actual Behavior
the last line doesn't reveal
builtins.strYour Environment
masterbranch)mypy.ini(and other config files): noneWhat I've found so far
If we declare
Aas a minimal dataclass the attribute is correctly inferred!If the
caseexplicitly matches on the attribute name, it also correctly infers the type:Issue
mypyunable to narrow type of tuple elements incaseclause in pattern matching #12364 may be relatedPEP626 mentions generics are special, but the examples don't appear relevant to this case.