Python: How to Set Default Values in Dataclass

Updated: March 1, 2023 By: Khue Post a comment

This succinct, straightforward article shows you how to set default values in a dataclass in Python.

Setting Default Values in Dataclass

To set default values in a dataclass, we can use simple syntax like a variable declaration or use the default parameter in the field() function. The example below define a class called Person with 3 fields: name, age (default is 18), and city (default is Sling Academy):

from dataclasses import dataclass, field

@dataclass
class Person:
    name: str
    age: int = 18
    city: str = field(default='Sling Academy')

# Create an instance of the class without providing age and city
person = Person('Foo Bar')
print(person)

Output:

Person(name='Foo Bar', age=18, city='Sling Academy')

Using the default_factory Parameter for Dynamic Default Values

There might be cases where we may need to set dynamic default values for a field in a dataclass. In such cases, we can use the default_factory parameter instead of default. default_factory must be a zero-argument callable that will be called when a default value is needed.

In the example below, we will define a class named Product with 3 fields: name, price (the default value is a random number between 900 and 1100), and production_year (the default value is the current year):

from datetime import datetime
from dataclasses import dataclass, field
from random import randint

# Get the current year
# Used to to set default value for production_year
def get_current_year():
    return datetime.now().year


@dataclass
class Product:
    name: str
    price: float = 1000 + randint(-100, 100)
    production_year: int = field(default_factory=get_current_year)

# Test code
product = Product('Blue Robot')
print(product)

Output:

Product(name='Blue Robot', price=1091, production_year=2023)

Afterword

Through the tutorial, we have learned how to set default values for fields in a dataclass. We have also seen how to use the default_factory parameter for dynamic default values. The examples, although simple, can give you a deep understanding of the topic. If you have any questions, leave comments. We will respond as soon as possible.