Python: Defining Fields in Dataclass

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

This quick article explains the different types of fields that can be defined in a dataclass in Python, as well as covers the different parameters that can be used to define fields.

Types of Fields

When defining a dataclass in Python, we can use various types of fields to represent the data that we want to store. Here are some of the most common types of fields that can be defined:

  • Init-only Fields: These are fields that can only be set during the initialization of the object. This is useful when we want to make sure that certain attributes of the object are immutable.
  • Mutable Default Fields: These are fields that have a default value that is mutable. This can be useful when we want to create a default value that can be modified later.
  • Class-level Fields: These are fields that are shared across all instances of the class. These fields can be useful when we want to store information that is common to all instances of the class.

Parameters to Define Fields in Dataclass

When defining fields in a dataclass, we can use various parameters to customize their behavior. Below are some of the most common parameters that can be used:

  • Type Hinting: We can use type hinting to specify the type of the field. This can be useful for type-checking and documentation purposes.
  • Default Value: We can provide a default value for the field using the default parameter. This value will be used if no value is provided during initialization.
  • Mutable Default: We can set the default value to a mutable object using the default_factory parameter. This factory function will be called each time a new instance is created.
  • Init-Only: We can make a field init-only using the init parameter. This will make the field immutable after initialization.
  • Comparison: We can specify whether a field should be included in the comparison of two instances using the eq, ne, lt, le, gt, and ge parameters. By default, all fields are included in the comparison.

Now, it’s time for examples and code.

Examples

Car (basic)

In this example, we will define a class that presents a car with 5 fields:

FieldTypeDefault Value
makestr
modelstr
yearint
engine_sizeOptional[float]None
optionsList[str]None

The code:

from dataclasses import dataclass
from typing import List, Optional


@dataclass
class Car:
    make: str
    model: str
    year: int
    engine_size: Optional[float] = None
    options: List[str] = None


car = Car("Toyota", "Prius", 2019, 1.8, [
           "Air Conditioning", "Cruise Control"])

print(car.options)

Output:

['Air Conditioning', 'Cruise Control']

Contact Class (advanced)

The class that we are going to create is called Contact and has 5 fields:

FieldTypeDefault Value
namestr
emailstr
phone_numbersList[str]None
addressOptional[str]None
contact_typeContactTypeContactType.PERSONAL

The ContactType type is an ENUM that we will create ourselves with 3 possible values: PERSONAL, WORK, and OTHER.

The code:

from dataclasses import dataclass
from enum import Enum
from typing import List, Optional
import pprint

# Define the ContactType enum
class ContactType(Enum):
    PERSONAL = "Personal"
    WORK = "Work"
    OTHER = "Other"


@dataclass
class Contact:
    name: str
    email: str
    phone_numbers: List[str] = None
    address: Optional[str] = None
    contact_type: ContactType = ContactType.PERSONAL

# Initiate an instance of the Contact class
contact = Contact(
    name="John Doe",
    email="[email protected]",
    phone_numbers=["123", "456", "789"],
    address="999 Street X, Washington, DC",
    contact_type=ContactType.WORK,
)

# Print the contact
pprint.pprint(contact)

Output:

Contact(name='John Doe',
        email='[email protected]',
        phone_numbers=['123', '456', '789'],
        address='999 Street X, Washington, DC',
        contact_type=<ContactType.WORK: 'Work'>)

Afterword

We’ve explored how to define fields in a dataclass in Python and walked through a couple of examples that demonstrate some real-world use cases. From here, you’re pretty good to go, and you should feel more confident to make more complex things.