» Quick Introduction to Python » 4. Common Modules » 4.1 dataclasses

dataclasses

dataclasses modules provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. It was originally described in PEP (Python Enhancement Proposal) 557.

Create a dataclass

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

The @dataclass decorator will add, among other things, a __init__() that looks like:

def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand

Note that this method is automatically added to the class. Developers don't need to add it manually.

Convert Dataclass to Dictionary

from dataclasses import dataclass, asdict

item = InventoryItem("shoe", 25)
print(asdict(item)) # {'name': 'shoe', 'unit_price': 25, 'quantity_on_hand': 0}

Convert Dictionary to Dataclass

from dataclasses import make_dataclass

shoe_data = {
    "name": "Shoe",
    "unit_price": 25,
    "quantity_on_hand": 1
}
InventoryItem = make_dataclass("InventoryItem", shoe_data.keys())
item = InventoryItem(**shoe_data)
print(item) # InventoryItem(name='Shoe', unit_price=25, quantity_on_hand=1)

Code Challenge

Try to modify the dataclass in the editor to make it print height: 5 width: 10 area: 50.

Loading...
> code result goes here
Prev
Next