-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Closed
Labels
bugmypy got something wrongmypy got something wrongtopic-match-statementPython 3.10's match statementPython 3.10's match statementtopic-type-narrowingConditional type narrowing / binderConditional type narrowing / binder
Description
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
masterbranch) - 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
Aas a minimal dataclass the attribute is correctly inferred!@dataclass class A(Generic[T]): x: T
-
If the
caseexplicitly matches on the attribute name, it also correctly infers the type:match a: case A(x=b): reveal_type(b) # builtins.str (correct)
-
Issue
mypyunable to narrow type of tuple elements incaseclause in pattern matching #12364 may be related -
PEP626 mentions generics are special, but the examples don't appear relevant to this case.
Metadata
Metadata
Assignees
Labels
bugmypy got something wrongmypy got something wrongtopic-match-statementPython 3.10's match statementPython 3.10's match statementtopic-type-narrowingConditional type narrowing / binderConditional type narrowing / binder