Type alias over generic parameter in generic class produces an error
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Given a class context (eg. class class Foo[T]), mypy fails to infer the generic parameter when used as part of a type alias that is declared in the class context.
Using type aliases within a class can help avoid repetition when complex generics are used throughout the class.
To Reproduce
class X[Y]:
type Z = list[Y] # produces: error: All type parameters should be declared ("Y" not declared) [valid-type]
def __init__(self, val: Y) -> None:
self.val = val
def make_list(self) -> Z:
return [self.val]
reveal_type(X(123).make_list()) # Revealed type *expected* to be "builtins.list[builtins.int]"
# is instead "builtins.list[Any]"
https://mypy-play.net/?mypy=latest&python=3.12&gist=845d9b12620d3febc625406e2a093ca2
Expected Behavior
The generic parameter Y should be inferred from the context of the class where it was specified.
It should be noted that pyright is able to deduce Y and therefore Z. See https://pyright-play.net/?code=MYGwhgzhAEAaDaBNAugLgFDS9ALgTwAcBTaALWgF5oQBLCHJZTbZrAEyIDNoB9HmgHY0cfABQQiITgBpoANzAhU0RAEpoAWgB80AHIB7AUQzZT0CVIB0CkJXmL0raB24BbMAGsiPWvXGTOdW0yEzMsACciHABXcIFoeAtOa0UmdEi5IkUefGJRWFEARgAmAGZVS3cvHzocUVVVIA
Actual Behavior
mytypes.py:2: error: All type parameters should be declared ("Y" not declared) [valid-type]
mytypes.py:10: note: Revealed type is "builtins.list[Any]"
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.12
- Mypy command-line flags:
--strict - Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.12
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the class type-alias example with mypy 1.12, Python 3.12, and --strict. Trace the type-alias handling for generic parameters in the relevant checker code. Done means the valid-type error is gone and reveal_type reports builtins.list[builtins.int].
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100