0Pricing
Python Academy · Lesson

Default Values and field()

Set defaults and use field() options.

Default Values and field() is a free Python Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Giving Fields Defaults

Just like function parameters, dataclass fields can have default values. A field with a default may be omitted when creating an instance.

from dataclasses import dataclass

@dataclass
class Server:
    host: str
    port: int = 8080

print(Server('localhost'))
print(Server('example.com', 443))

Order Matters

Fields with defaults must come after fields without defaults, exactly like function arguments. Otherwise Python raises a TypeError when the class is defined.

from dataclasses import dataclass

@dataclass
class User:
    name: str       # required
    active: bool = True   # optional

print(User('Alice'))

The Mutable Default Trap

You cannot use a mutable object like a list or dict as a direct default. All instances would share the same object. Python detects this and raises a ValueError to protect you.

from dataclasses import dataclass
from typing import List

# This raises ValueError at class definition time:
try:
    @dataclass
    class Bad:
        items: List[int] = []
except ValueError as e:
    print('Error:', e)

field(default_factory=...)

To give a mutable default, use field(default_factory=...). The factory is called for each new instance, so every instance gets its own fresh object.

from dataclasses import dataclass, field
from typing import List

@dataclass
class Cart:
    items: List[str] = field(default_factory=list)

a = Cart()
a.items.append('apple')
b = Cart()
print(a.items, b.items)

default vs default_factory

Use field(default=...) for immutable values when you also need other field() options. Use default_factory for anything mutable. You cannot pass both at once.

from dataclasses import dataclass, field

@dataclass
class Config:
    retries: int = field(default=3)
    tags: list = field(default_factory=list)

print(Config())

Excluding a Field from repr

The repr=False option hides a field from the generated __repr__. This is useful for secrets or large internal buffers.

from dataclasses import dataclass, field

@dataclass
class Account:
    user: str
    token: str = field(repr=False, default='secret')

print(Account('alice'))

Excluding a Field from Comparison

With compare=False, a field is ignored by the generated __eq__ (and ordering). Two instances can be equal even if that field differs.

from dataclasses import dataclass, field

@dataclass
class Event:
    name: str
    timestamp: float = field(compare=False, default=0.0)

print(Event('login', 1.0) == Event('login', 99.0))

init=False Fields

Setting init=False keeps a field out of __init__. You usually combine it with a default or set it in __post_init__.

from dataclasses import dataclass, field

@dataclass
class Circle:
    radius: float
    area: float = field(init=False, default=0.0)

c = Circle(2.0)
print(c)

__post_init__ for Derived Values

Define __post_init__ to run code right after the generated __init__. It is the natural place to compute fields derived from others.

from dataclasses import dataclass, field

@dataclass
class Circle:
    radius: float
    area: float = field(init=False, default=0.0)

    def __post_init__(self):
        self.area = 3.14159 * self.radius ** 2

print(Circle(2.0))

Storing Metadata

The metadata argument attaches an arbitrary mapping to a field. Python ignores it, but tools and your own code can read it for documentation or validation hints.

from dataclasses import dataclass, field, fields

@dataclass
class Product:
    price: float = field(metadata={'unit': 'USD'})

for f in fields(Product):
    print(f.name, f.metadata)

Combining field() Options

The options stack. A single field can hide itself from repr, stay out of comparison, and carry a default at the same time.

from dataclasses import dataclass, field

@dataclass
class Session:
    user: str
    token: str = field(default='x', repr=False, compare=False)

print(Session('alice'))
print(Session('alice') == Session('alice', token='different'))

Quick Check

How should you give a dataclass field a default empty list?

Recap

You learned to set defaults and use field() options.

  • Defaulted fields come after required ones.
  • Use default_factory for mutable defaults.
  • repr, compare, init, and metadata tune each field.
  • __post_init__ computes derived values.

Frequently asked questions

Is the “Default Values and field()” lesson free?

Yes — the full text of “Default Values and field()” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Default Values and field()”?

Set defaults and use field() options. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Default Values and field()” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Defining a Dataclass
  2. Default Values and field()
  3. Frozen and Comparison Options
  4. The attrs Library
← Back to Python Academy