-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Description
Bug Report
A dataclass with generic field does not infer the generics type when a default is provided.
To Reproduce
@dataclass
class Data(Generic[T]):
field: T = 1
# -> "Incompatible types in assignment (expression has type "int", variable has type "T")" (INCORRECT, should be accepted w/o error)
reveal_type( Data(17.5).field )
# -> Revealed type is "builtins.float*" (CORRECT)
reveal_type( Data().field )
# -> Revealed type is "<nothing>" (FAILED, should be int)
Expected Behavior
The default value supplied in the dataclass should be honored. Semantically the construct is not an assignment, but a default value
in the __init__ function:
Under the hood the (autogenerated) dataclass constructor looks like this
def __init__(self, field = 1):
self.field = field
So when field is not provided during construction of Data instance the field is passed as an int, so the generic type T should be inferred as int (if field is omitted in constructor). In the exactly same way as T is inferred as float when the field is given explicitly in the constructor (e.g. Data(17.5).field)
Concluding, what should happen:
Data()-> infer T as int (from the default in dataclass) (does not work)Data(val)-> infer T as same type asval(this works)
Actual Behavior
Default argument is ignored
Your Environment
- Mypy version used: 0.960
- Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used: 3.9.7
- Operating system and version: Windows 10