Dataclasses

Data Classes:

This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes.

Dataclasses module provides a subset of attrs functionality.

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

Attrs:

attrs is the Python package that will bring back the joy of writing classes by relieving you from the drudgery of implementing object protocols (aka dunder methods).

Pydantic:

Data validation and settings management using python type annotations. pydantic enforces type hints at runtime, and provides user friendly errors when data is invalid.

Tools

  1. JSON to Pydantic

Tutorials

  1. Python dataclasses will save you HOURS, also featuring attrs

  2. This Is Why Python Data Classes Are Awesome

  3. Do we still need dataclasses? // PYDANTIC tutorial

References

  1. dataclasses — Data Classes

  2. attrs: Classes Without Boilerplate

  3. pydantic-docs