Uh oh!
There was an error while loading. Please reload this page.
Add error for asdict, astuple, fields, and replace in dataclasses - Fixes #14215 - #14263
Add error for asdict, astuple, fields, and replace in dataclasses - Fixes #14215#14263tdscheper wants to merge 1 commit into
Conversation
Diff from mypy_primer, showing the effect of this PR on open source code: core (https://github.com/home-assistant/core)
+ homeassistant/components/zwave_js/discovery.py:78: error: asdict() should be called on dataclass instances [misc]
porcupine (https://github.com/Akuli/porcupine)
+ porcupine/utils.py:408: error: asdict() should be called on dataclass instances [misc] |
tmke8
commented
Dec 8, 2022
Will something like fromdataclassesimportasdict, is_dataclassdeff(x: object) ->dict:
ifis_dataclass(x):
returnasdict(x)
return {}work? |
@thomkeh Just checked, no it does not. I'm thinking the solution to that would involve adding 'dataclass' to the object's metadata if is_dataclass returns True, but being that this is my first time contributing to Mypy, I'm not sure if that is something that should be done. I'll keep looking into it and can submit another PR some time soon, if that works |
JelleZijlstra
commented
Dec 8, 2022
The principled solution would be to make is_dataclass work similar to a TypeGuard and narrow down the type. We probably should do that first before restricting the types that can be passed to asdict() and friends. |
This could potentially be fixed in typeshed rather than mypy, which might be preferable: fromtypingimportAny, ClassVar, Protocolfromtyping_extensionsimportTypeGuardclass_Dataclassy(Protocol):
__dataclass_fields__: ClassVar[dict[str, Any]]
defasdict(obj: _Dataclassy) ->dict[str, Any]: ...
defis_dataclass(obj: object) ->TypeGuard[_Dataclassy]: ...I believe both pyright and mypy already infer that dataclasses automatically have a |
I can confirm that this works in mypy at least. Though the error messages leak the name of the dummy protocol: which might confuse people. EDIT: works in pyright too, but doesn't work in pyre |
AlexWaygood
commented
Dec 8, 2022
We can probably name it something more boring and less punny like |
AlexWaygood
commented
Jan 28, 2023
Thanks for the PR! Unfortunately I just merged python/typeshed#9362, which makes this redundant. |
Fixes#14215
This change ensures Mypy detects an error when any of the asdict, astuple, fields, or replace methods from the dataclasses library is called on an object that is not a dataclass.