0
0
PythonHow-ToBeginner · 3 min read

How to Use field() Function in Python Dataclasses

In Python, the field() function is used inside a @dataclass to customize how individual attributes behave, such as setting default values, excluding them from the constructor, or adding metadata. You use it by importing field from dataclasses and passing parameters like default, default_factory, or init inside the attribute definition.
📐

Syntax

The field() function is used to customize dataclass attributes. You import it from the dataclasses module and use it inside the class attribute definition.

  • default: sets a fixed default value.
  • default_factory: sets a callable to produce a default value (useful for mutable types).
  • init: if False, excludes the field from the generated __init__ method.
  • repr: if False, excludes the field from the generated __repr__.
  • compare: if False, excludes the field from comparison methods.
  • metadata: a dictionary to store extra info about the field.
python
from dataclasses import dataclass, field

@dataclass
class Example:
    x: int = field(default=10)
    y: list = field(default_factory=list)
    z: str = field(init=False, default='hidden')
💻

Example

This example shows how to use field() to set default values, use a factory for mutable defaults, and exclude a field from the constructor.

python
from dataclasses import dataclass, field

@dataclass
class Person:
    name: str
    age: int = field(default=30)
    hobbies: list = field(default_factory=list)
    secret: str = field(init=False, default='classified')

p = Person(name='Alice')
print(p)
print('Hobbies:', p.hobbies)
print('Secret:', p.secret)
Output
Person(name='Alice', age=30, hobbies=[], secret='classified') Hobbies: [] Secret: classified
⚠️

Common Pitfalls

One common mistake is using a mutable default value directly instead of using default_factory. This causes all instances to share the same object, leading to unexpected behavior.

Also, forgetting to set init=False when you want to exclude a field from the constructor can cause errors.

python
from dataclasses import dataclass, field

# Wrong: mutable default shared across instances
@dataclass
class Wrong:
    items: list = []  # BAD

# Right: use default_factory for mutable defaults
@dataclass
class Right:
    items: list = field(default_factory=list)

w1 = Wrong()
w2 = Wrong()
w1.items.append('apple')
print('Wrong:', w2.items)  # shows ['apple'] because list is shared

r1 = Right()
r2 = Right()
r1.items.append('apple')
print('Right:', r2.items)  # shows [] because each has own list
Output
Wrong: ['apple'] Right: []
📊

Quick Reference

ParameterDescriptionExample
defaultSet a fixed default valuefield(default=10)
default_factorySet a callable for default (for mutable types)field(default_factory=list)
initInclude field in __init__ if True (default)field(init=False)
reprInclude field in __repr__ if True (default)field(repr=False)
compareInclude field in comparison methods if True (default)field(compare=False)
metadataAttach extra info as a dictfield(metadata={'unit': 'cm'})

Key Takeaways

Use field() to customize dataclass attributes beyond simple defaults.
Always use default_factory for mutable default values like lists or dicts.
Set init=False to exclude fields from the constructor parameters.
field() parameters control initialization, representation, comparison, and metadata.
Avoid mutable default arguments directly to prevent shared state bugs.