Skip to content

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

Description

@tmke8

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

fromtypingimportAny, ClassVar, Protocolfromtyping_extensionsimportTypeGuardclass_DataclassInstance(Protocol):
__dataclass_fields__: ClassVar[dict[str, Any]]
defasdict(obj: _DataclassInstance) ->dict[str, Any]: ...
defis_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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions