1

Following the recommendations in type hint for an instance of a non specific dataclass, I was able to define a Protocol to identify classes decorated with @dataclass, i.e.

class DataclassProtocol(Protocol):
    __dataclass_fields__: Dict

This works well, but I now need to distinguish between a (non-specific) dataclass class and a (non-specific) dataclass instance. The protocol above matches both so it can't be used to discriminate.

Based on the source code in https://github.com/python/cpython/blob/3.8/Lib/dataclasses.py, it seems that one possible discriminator is that dataclasses classes inherit from type, while dataclasses instances do not.

Can this be used to derive type hints to discriminate correctly dataclass classes from dataclass instances? Or is there another way?

hiryu
  • 1,308
  • 1
  • 14
  • 21
  • Are you sure that the protocol you define matches both? [Playground where it doesn't hold true](https://mypy-play.net/?mypy=latest&python=3.10&gist=a034c938c6d0f8191d4c6bb99b3f3624) – STerliakov May 10 '22 at 07:34
  • *all* classes inherit from `type`, so the facts need to be set straight here – rv.kvetch May 10 '22 at 15:00
  • @SUTerliakov you are 100% right, I was testing the protocol by decorating it with `@runtime_checkable` and then using `isinstance`, both were matching. But in `mypy` instead, the dataclass class doesn't match. This means that there is a way! I ended up renaming the protocol to `DataclassInstanceProtocol` and using it for instances, while for dataclass classes I simply use `Type[DataclassInstanceProtocol]`. Works perfectly, here the gist: https://mypy-play.net/?mypy=latest&python=3.10&gist=d73e1af7992248a237e93d0e1c640368 – hiryu May 12 '22 at 09:06

0 Answers0