0Pricing
Python Academy · Lesson

Default Values and field()

Set defaults and use field() options.

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'))

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