Check if a class is a dataclass in Python

Docs

import dataclasses
dataclasses.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)

Leave a Comment