Deny free type variables in instance attributes coming from constructor args
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Feature
Detect free type variables as instance attribute annotations, when they appear from constructor with TypeVar in signature without Generic.
Pitch
It would be especially useful for beginners. People often do not understand Generic necessity under some circumstances, though more experienced user may also accidentally forget about this.
This does not deny type variables in constructor arguments, if they do not become part of attributes annotations (say, __init__(self, x: _T, y: _T): do_something(x, y); super().__init__()).
Simple example (playground link):
from typing import TypeVar
_T = TypeVar('_T')
class Foo:
def __init__(self, foo: _T, bar: _T):
self.foo = foo
self.bar = bar
f = Foo(1, 1)
reveal_type(f.foo) # N: Revealed type is "_T`-1"
mypy already denies another scenario, which is essentially the same:
...
class Bar:
x: _T # E: Type variable "__main__._T" is unbound [valid-type]
results in
main.py:15: error: Type variable "__main__._T" is unbound [valid-type]
main.py:15: note: (Hint: Use "Generic[_T]" or "Protocol[_T]" base class to bind "_T" inside a class)
main.py:15: note: (Hint: Use "_T" in function signature to bind "_T" inside a function)
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 with the linked mypy-play reproducer and compare it with the existing unbound TypeVar diagnostic for class attributes. Trace how constructor assignments become instance attribute annotations; done means reporting unbound type variables there while allowing TypeVars used only in constructor arguments.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100