Skip to content

Cannot deduce type of generic attributes within match statements #13612

Description

@ariebovenberg

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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-match-statementPython 3.10's match statementtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions