Distinguish dataclass classes from dataclass instances in python type hints

326 Views Asked by At

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?

0

There are 0 best solutions below