You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Cannot deduce type of generic attributes within match statements #13612
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
fromtypingimportGeneric, TypeVarT=TypeVar("T")
classA(Generic[T]):
x: T__match_args__= ("x",)
def__init__(self, x: T):
self.x=xa=A("foo")
reveal_type(a) # A[str] (correct)reveal_type(a.x) # builtins.str (correct)matcha:
caseA(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
If we declare A as a minimal dataclass the attribute is correctly inferred!
@dataclassclassA(Generic[T]):
x: T
If the case explicitly matches on the attribute name, it also correctly infers the type:
Activity
sobolevn commentedon Sep 5, 2022
Hi, @ariebovenberg 👋
Confession: I've never used a match statement in Python.
But, I will try to take a look (with no promises)
sobolevn commentedon Sep 7, 2022
@ariebovenberg reviews are welcome (at least of tests!) :)
Fix type inference in pattern matching by positional argument (#13618)