-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
dataclass with Generic parameter does not honor default value #12962
Comments
#11923 seems to be a related issue |
I would not expect this to work. A dataclass decorator effectively adds a synthesized def __init__(self, field: T = 1) -> None: ... If you were to explicitly create a generic class with this |
I see. So the real issue is that concrete default arguments are not allowed for generic parameters. However, after looking around on this site I found that this feature seems to meet some interest and has been requested several times so far (#4236, #3737, #10854, #10504, #5802, #5273, #5464, and perhaps more) The issue is that the proposed workaround or solution with @overload (as in #4236 (comment)) does not work for dataclasses (or at least I cannot see how this would work in my case). With dataclasses the The things is that when writing code with generics one arrives quickly at the point where the built-in default ( |
This isn't supported by the current type system, so I'm closing for now; but it sounds like you may be interested in python/peps#2717 |
Bug Report
A dataclass with generic field does not infer the generics type when a default is provided.
To Reproduce
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
So when
field
is not provided during construction ofData
instance the field is passed as anint
, so the generic typeT
should be inferred asint
(if field is omitted in constructor). In the exactly same way as T is inferred asfloat
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.ini
(and other config files):The text was updated successfully, but these errors were encountered: