Python 3.7+dataclassesfunction
dataclasses.fields()
field
Returns a tuple of Field objects holding the metadata of every field of the dataclass.
Syntax
dataclasses.fields(class_or_instance)
This is the supported way to iterate over a dataclass's fields, and it is what custom validation, serialization and field-wise comparison are usually built on. Only real fields are returned: InitVar pseudo-fields and ClassVar annotations are left out. Two catches: f.type is the annotation exactly as written, so it is a string when the module uses from __future__ import annotations, and a missing default is reported by the dataclasses.MISSING sentinel rather than None.
Examples
from dataclasses import dataclass, fields
@dataclass
class Pt:
x: int; y: int = 0
for f in fields(Pt):
print(f.name, f.type) # → ? две строки: «x <class 'int'>» и «y <class 'int'>»
print(fields(Pt)[0].name) # → x
print(fields(Pt)[1].default) # → 0
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy