Setting Default Values for Attributes in Python Dataclasses


Default values for Dataclass attributes in Python

In this tutorial, you will learn how to specify default values for attributes in a dataclass in Python.

To specify default values for dataclass attributes, assign the default values to the attributes in the dataclass definition

For example, in the following code snippet, we define a dataclass Person, with attributes: name and age, and default values of "Dummy" and 0 set to these attributes respectively.

@dataclass
class Person:
    name: str = "Dummy"
    age: int = 0

Examples

1. Set default values for Person dataclass

In this example, we'll create a dataclass to represent a Person with name and age attributes, and default values set to these attributes.

We shall create an instance of this Person dataclass person_1 with no arguments passed, and print the instance to standard output to verify the default values.

Python Program

from dataclasses import dataclass

@dataclass
class Person:
    name: str = 'Dummy'
    age: int = 0

# Create an instance of dataclass Person
person_1 = Person()
print(person_1)

Output

Person(name='Sample Name', age=0)

2. Specify default value only for some attributes of the dataclass

We can specify default value only for some of the attributes, and let others be passed while creating the instance.

In the following program, we define the Person dataclass with default value set only for the age attribute. Therefore, passing a value for the name attribute becomes mandatory.

Python Program

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int = 20

# Create an instance of dataclass Person
person_1 = Person('Swamy')
print(person_1)

Output

Person(name='Swamy', age=20)

Summary

In this Python dataclasses tutorial, we learned how to set default values for the dataclass attributes, with the help of example programs.