What Are Dataclasses in Python and How to Use Them?

Introduced in Python 3.7, dataclasses provide a decorator and functions for automatically adding special methods to user-defined classes. They simplify the process of creating classes that primarily store data.

Why Use Dataclasses?

  • Less Boilerplate: Automatically generate methods like __init__ and __repr__.
  • Type Annotations: Enforce data types for class attributes.
  • Immutability: Option to make instances immutable.

Basic Usage

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

person = Person(name='Alice', age=30)
print(person)
# Output: Person(name='Alice', age=30)

Default Values

You can assign default values to fields:

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

Immutable Dataclasses

Set frozen=True to make instances immutable:

@dataclass(frozen=True)
class Point:
    x: int
    y: int

Field Metadata

Use field() to add metadata or manage how fields are handled:

from dataclasses import dataclass, field

@dataclass
class InventoryItem:
    name: str
    price: float = field(default=0.0, metadata={'unit': 'USD'})

Conclusion

Dataclasses simplify the creation of classes that are primarily used to store data. They reduce boilerplate code and enhance readability.

Leave a Reply

Your email address will not be published. Required fields are marked *