Python 3.7+dataclassesfunction
dataclasses.make_dataclass
factory
Create a new dataclass dynamically from a name and a list of fields.
Syntax
dataclasses.make_dataclass(cls_name, fields, *, bases=(), namespace=None, ...)
Rarely the right tool: when the fields are known up front, a plain @dataclass decorator reads better and is visible to type checkers, while make_dataclass builds the class at runtime so your IDE knows nothing about its fields. A field entry can be a bare name, a (name, type) pair, or a triple with field(); a bare name gets typing.Any. For instances to be picklable, bind the result to a module-level variable whose name matches the first argument.
Examples
import dataclasses
Pt = dataclasses.make_dataclass('Pt', ['x', 'y'])
print(dataclasses.asdict(Pt(1, 2))) # → {'x': 1, 'y': 2}
print(Pt(1, 2)) # → Pt(x=1, y=2)
print(Pt(1, 2) == Pt(1, 2)) # → True
P2 = dataclasses.make_dataclass('P2', [('x', int), ('y', int, dataclasses.field(default=0))])
print(P2(5)) # → P2(x=5, y=0)
print([f.name for f in dataclasses.fields(P2)]) # → ['x', 'y']
Fz = dataclasses.make_dataclass('Fz', ['v'], frozen=True)
Fz(1).v = 2 # → FrozenInstanceError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy