Check if a class is a dataclass in Python Check if a class is a dataclass in Python python-3.x python-3.x

Check if a class is a dataclass in Python


Docs

import dataclassesdataclasses.is_dataclass(something)

As mentioned by @Arne internally it simply checks hasattr(something, '__dataclass_fields__'), but I'd recommend to not rely on this attribute and directly use is_dataclass.

Why you should not rely on __dataclass_fields__:

  • This attribute is not a public API: it's not mentioned anywhere in the docs.
  • It's an implementation detail, and so it's not guaranteed to work in other python implementations. But besides cPython nothing seems to support Python3.7 yet (as of May 2019). At least Jython, IronPython and PyPy do not support it, so it's hard to tell if they will be using the same attribute or not

Everything else including differences between checking for dataclass type and dataclass instance is in the docs of is_dataclass method:

# (from the docs)def is_dataclass_instance(obj):    return is_dataclass(obj) and not isinstance(obj, type)


Extending upon the answer above, the following illustrates the usage of is_dataclass():

Remember: The parameter passed to is_dataclass() can be a dataclass or an instance of the dataclass, to return True from the method call.

In [1]: from dataclasses import dataclassIn [2]: @dataclass   ...: class Bio:   ...:     name: str   ...:     age: int   ...:     height: float   ...:In [3]: from dataclasses import is_dataclassIn [4]: is_dataclass(Bio)Out[4]: TrueIn [5]: b = Bio('John', 25, 6.5)In [6]: is_dataclass(b)Out[6]: True

To check whether, b is an instance of the dataclass and not a dataclass itself:

In [7]: is_dataclass(b) and not isinstance(b, type)Out[7]: True

Bio is a dataclass, so the following expression evaluates to False:

In [8]: is_dataclass(Bio) and not isinstance(Bio, type)Out[8]: False

Lets check for a regular class:

In [9]: class Car:   ...:     def __init__(self, name, color):   ...:         self.name = name   ...:         self.color = color   ...:

We know Car is not a dataclass:

In [10]: is_dataclass(Car)Out[10]: FalseIn [11]: c = Car('Mustang', 'Blue')

Neither an instance of Car is a dataclass instance:

In [12]: is_dataclass(c)Out[12]: False