Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

dataclasses.fields

Returns descriptors for the real data fields in declaration order.

Version: Python 3.14; repository image, production runtime not attested

Syntax

dataclasses.fields(class_or_instance)

Returns descriptors for the real data fields in declaration order.

Class variables are excluded, so class-level configuration does not become a serialized instance field.

Use fields to inspect stored field metadata rather than reading an instance dictionary. It returns a tuple of Field descriptors in field order and accepts the class or an instance. ClassVar and InitVar pseudo-fields are absent; an unrelated argument raises TypeError. Only id appears in the example because version is a ClassVar.

from dataclasses import dataclass, fields, InitVar
from typing import ClassVar
@dataclass
class Row:
    x: int
    cache: ClassVar[int] = 3
    seed: InitVar[int] = 4
assert tuple(f.name for f in fields(Row)) == ("x",)
assert fields(Row) == fields(Row(1))

Examples

import dataclasses
from typing import ClassVar

@dataclasses.dataclass
class Row:
    id: int
    version: ClassVar[int] = 1

print([field.name for field in dataclasses.fields(Row)])

Result

['id']

Use fields to inspect stored field metadata rather than reading an instance dictionary. It returns a tuple of Field descriptors in field order and accepts the class or an instance. ClassVar and InitVar pseudo-fields are absent; an unrelated argument raises TypeError. Only id appears in the example because version is a ClassVar.

Sources