Skip to content
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

is_dataclass should be a type guard and asdict should only work on objects with __dataclass_fields__ #9345

Closed
tmke8 opened this issue Dec 9, 2022 · 0 comments · Fixed by #9362

Comments

@tmke8
Copy link
Contributor

tmke8 commented Dec 9, 2022

@AlexWaygood proposed the following stubs in this comment: python/mypy#14263 (comment)

from typing import Any, ClassVar, Protocol
from typing_extensions import TypeGuard

class _DataclassInstance(Protocol):
     __dataclass_fields__: ClassVar[dict[str, Any]]

def asdict(obj: _DataclassInstance) -> dict[str, Any]: ...
def is_dataclass(obj: object) -> TypeGuard[_DataclassInstance]: ...

and this works as expected with dataclasses on mypy and pyright, but it doesn't currently work on pyre because pyre doesn't know yet that dataclasses have the __dataclass_fields__ classvar. (I haven't checked other type checkers.)

At runtime, is_dataclass really only checks for the __dataclass_fields__ attribute:

https://github.com/python/cpython/blob/7a0f3c1d92ef0768e082ace19d970b0ef12e7346/Lib/dataclasses.py#L1263-L1267

However, it also works with types in addition to instances, so an overload would be needed.

See also this issue for context: python/mypy#14215

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant