Lesson 52 of 60
โฎPrev Nextโฏ

PY-101 ยท Object-oriented Python

Dataclasses

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

52of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    A dataclass is a class mainly for holding data, created with the @dataclass decorator. You list the fields with type hints, and Python writes __init__, __repr__ and __eq__ for you. Options like frozen=True (cannot change) and order=True (can sort) add more with one word.

    • Define a @dataclass with typed fields
    • Use defaults and field(default_factory=list)
    • Use frozen and order

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Dataclasses, running
    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class Product:
    4. name: str
    5. price: float
    6. qty: int = 1
    7. tags: list[str] = field(default_factory=list)
    8. def total(self):
    9. return self.price * self.qty
    10. pen = Product("Pen", 20.0, 3)
    11. print(pen)
    12. print(pen.total(), pen == Product("Pen", 20.0, 3))
    13. @dataclass(frozen=True, order=True)
    14. class Version:
    15. major: int
    16. minor: int
    17. print(sorted([Version(2, 1), Version(1, 9), Version(2, 0)]))
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemA Product class with name, price and qty needs a 6-line __init__, a __repr__ and an __eq__. A dataclass needs four lines and gets all of it, correct, for free.
    2. The Python ideafrom dataclasses import dataclass, fieldA dataclass is a class mainly for holding data, created with the @dataclass decorator.
    3. In real lifeFastAPI and Pydantic models look just like dataclasses: typed fields that validate incoming JSON automatically.

    Start with a question

    A Product class with name, price and qty needs a 6-line __init__, a __repr__ and an __eq__. A dataclass needs four lines and gets all of it, correct, for free.

    Modern Python uses dataclasses (and their cousins in Pydantic) for config, API models and records everywhere.

    Explain it like I'm 10

    A dataclass is a ready-made form: you just write the field names, and Python builds the boxes, labels and checks for you.

    The technical explanation

    @dataclass class Point: x: int; y: int gives you Point(1, 2), a readable repr and == that compares fields.

    Defaults work like functions: qty: int = 1. Mutable defaults need field(default_factory=list).

    @dataclass(frozen=True) makes objects read-only; order=True adds <, > so they sort by their fields.

    Syntax

    from dataclasses import dataclass, field
    
    @dataclass
    class Name:
        a: int
        b: str = "x"

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    FastAPI and Pydantic models look just like dataclasses: typed fields that validate incoming JSON automatically.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. Which methods does @dataclass write for you?
    2. 2. How do you declare fields?
    3. 3. Safe default for a list field?
    4. 4. What does frozen=True do?
    5. 5. What does order=True add?

    Questions people ask

    When should I use a dataclass instead of a normal class?

    When the class mainly holds data. You still can add methods. For classes that are mostly behaviour with little data, a normal class is fine.

    What is the difference between dataclasses and Pydantic?

    Dataclasses (standard library) generate methods but do not validate types at run time. Pydantic models validate and convert data, which suits API input.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner When should I use a dataclass instead of a normal class?

    When the class mainly holds data. You still can add methods. For classes that are mostly behaviour with little data, a normal class is fine.

    beginner What is the difference between dataclasses and Pydantic?

    Dataclasses (standard library) generate methods but do not validate types at run time. Pydantic models validate and convert data, which suits API input.

    intermediate Which methods does @dataclass write for you?

    __init__, __repr__, __eq__. Those three by default.

    intermediate How do you declare fields?

    With type-hinted class attributes. name: str, price: floatโ€ฆ

    Quick revision

    Remember

    • Define a @dataclass with typed fields
    • Use defaults and field(default_factory=list)
    • Use frozen and order
    • Never write items: list = [] in a dataclass. Use items: list = field(default_factory=list) so each object gets its own list.

    Syntax

    from dataclasses import dataclass, field
    
    @dataclass
    class Name:
        a: int
        b: str = "x"

    Official documentation