Open
Description
Bug Report
When a dataclass field uses a descriptor, Mypy makes two incorrect inferences:
- If the descriptor has no default value (it raises AttributeError when accessed on the class), mypy incorrectly assumes it has a default and raises an error on the next field with no default value. The no-default mechanism was documented in Python 3.10 but has been there since 3.7. The specific code is in
dataclasses._get_field
, asdefault = getattr(cls, a_name, MISSING)
. - If the descriptor-based field is typed with
InitVar
, mypy incorrectly assumes the attribute does not exist on the class.
To Reproduce
https://mypy-play.net/?mypy=latest&python=3.11&gist=8a47d8538f2fc798a8564d30dae6434e
Expected Behavior
No error, matching runtime behaviour and the internal validations of the @dataclass
decorator.
Actual Behavior
Two incorrect errors:
- Attributes without a default cannot follow attributes with one [misc]
- "Example2" has no attribute "this_exists" [attr-defined]
Your Environment
- Mypy version used: 1.7.0 and 1.6.1
- Python version used: 3.9 and 3.11
Related: #13856 describes another dataclass descriptor bug, fixed in mypy 1.2.