Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

dataclasses.field

Customizes how one annotated data-class field is initialized and included in generated operations.

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

Syntax

dataclasses.field(default_factory=list)

Customizes how one annotated data-class field is initialized and included in generated operations.

If the caller omits the field, the zero-argument factory supplies its default, preventing accidental sharing of a mutable list.

Use field to configure an annotated attribute. A zero-argument default_factory is invoked when a default is needed; pass list itself, not list(). default and default_factory are mutually exclusive. In the example each Bag receives its own list, so appending 8 to a leaves b empty. Python 3.14 adds doc for field documentation. MISSING marks an omitted setting, whereas None is a possible default. Field metadata is a read-only mapping. The factory runs once per field per instance that needs its default.

from dataclasses import dataclass, field
@dataclass
class Queue:
    values: list = field(default_factory=list, repr=False)
a, b = Queue(), Queue()
assert a.values is not b.values and repr(a) == "Queue()"
try:
    field(default=[], default_factory=list)
except ValueError:
    pass
else:
    raise AssertionError
from dataclasses import MISSING, fields
assert fields(Queue)[0].default is MISSING
explicit = []
assert Queue(explicit).values is explicit

Examples

import dataclasses
@dataclasses.dataclass
class Bag:
    items: list = dataclasses.field(default_factory=list)

a, b = Bag(), Bag()
a.items.append(8)
print(a.items, b.items)

Result

[8] []

Use field to configure an annotated attribute. A zero-argument default_factory is invoked when a default is needed; pass list itself, not list(). default and default_factory are mutually exclusive. In the example each Bag receives its own list, so appending 8 to a leaves b empty. Python 3.14 adds doc for field documentation. MISSING marks an omitted setting, whereas None is a possible default. Field metadata is a read-only mapping. The factory runs once per field per instance that needs its default.

Sources