Content · Programming · Python

Python dataclasses.field() Function: Usage and Examples

Configure field defaults, factories, and metadata with dataclasses.field().

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Configure field defaults, factories, and metadata with dataclasses.field().

What You Will Learn


field(default_factory=...) creates a fresh mutable value per instance. Other options include repr=False, compare=False, kw_only=True, and metadata. Metadata itself is read-only at the mapping level.

A default_factory should be a zero-argument callable.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from dataclasses import dataclass, field

@dataclass
class ShoppingCart:
    products: list[str] = field(default_factory=list)

first_cart = ShoppingCart()
second_cart = ShoppingCart()
first_cart.products.append("Notebook")
print(first_cart.products)
print(second_cart.products)

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: dataclasses.
  • The class ShoppingCart groups data and behavior; its methods run when called on an instance.
  • The variable first_cart holds the result of ShoppingCart(). Later lines use that value or inspect how it changes.
  • The variable second_cart holds the result of ShoppingCart(). Later lines use that value or inspect how it changes.

Expected output from the example:

['Notebook']
[]

When You Would Use This


These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.

Practice: Modify the Code


Add a per-instance set field with default_factory=set.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Using one shared mutable default list for every instance instead of default_factory.
  • Calling default_factory immediately and passing its result, rather than passing the callable.

Key Takeaways


  • Configure field defaults, factories, and metadata with dataclasses.field().
  • field(default_factory=...) creates a fresh mutable value per instance.
  • A default_factory should be a zero-argument callable.
Share this resourceSend this page to someone who may find it useful.