Python Glossary Русский

Python 3.7+dataclassesfunction

dataclasses.is_dataclass

introspection

True if the object (class or instance) is a dataclass.

Syntax

dataclasses.is_dataclass(obj)

The main trap: it returns True both for a dataclass and for its instances, so to test "this is an actual object" you must additionally check that it is not a type (isinstance(obj, type)). Use it as a guard before asdict/astuple/fields, which raise TypeError on non-dataclasses instead of returning something empty. Subclasses of a dataclass also count as dataclasses even when they carry no decorator of their own.

Examples

import dataclasses
@dataclasses.dataclass
class P:
    x: int
print(dataclasses.is_dataclass(P))   # → True
print(dataclasses.is_dataclass(42))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy