Dataclasses

1

dataclasses introduced in python 3.7 onwards. How to use them in my python code

Dataclasses, introduced in Python 3.7 as part of the standard library via PEP 557, are designed to make it easier to write classes that are primarily containers for data ("data classes"). They automatically generate special methods like __init__(), __repr__(), and __eq__().

Here’s a brief guide on how to use dataclasses in your Python code:

1. Import the dataclass Decorator

To use dataclasses, you first need to import the dataclass decorator from the dataclasses module:

from dataclasses import dataclass

2. Define Your Data Class

Apply the @dataclass decorator to your class. This will automatically generate the __init__, __repr__, and __eq__ methods, along with others like __lt__, __le__, __gt__, and __ge__ if you specify the order=True parameter.

Here’s a simple example:

from dataclasses import dataclass

@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

3. Create Instances of Your Data Class

You can now create instances of your data class. The __init__ method is automatically created, so you don't need to define it:

This will output something like:

4. Use the Automatically Generated Methods

With dataclasses, you get implementations of __repr__, __eq__, and if you choose, ordering methods (__lt__, __le__, etc.):

Additional Features

Default Values

You can provide default values as shown above for quantity_on_hand, and use field() for more complex defaults:

Immutable Data Classes

If you want to make the instances of your class immutable (i.e., hashable and suitable for use as dictionary keys), you can use the frozen=True parameter:

This prevents modifications to the fields, making the instance "frozen".

Post-Initialization Processing

Sometimes you need to further initialize your data class after the auto-generated __init__ method has run. Use the __post_init__ method for this:

Dataclasses are powerful for reducing boilerplate in your classes and making your code cleaner and more maintainable. They are especially useful when you are dealing with classes that are primarily meant to be data containers.


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17


18


19


20


21


22


23


24


25


Last updated