Skip to content

    Type Hints & Dataclasses

    Python · Intermediate

    Definition

    Type hints describe expected types; @dataclass auto-generates __init__, __repr__ and __eq__.

    Clearer, safer code that tools can check.

    Diagram

    @dataclassclass Pointx: int, y: int

    Flowchart

    Annotate variables and functionsDecorate class with @dataclassDeclare fields with typesUse mypy to check

    Example: Dataclass

    from dataclasses import dataclass
    @dataclass
    class Point:
        x: int
        y: int = 0
    print(Point(3), Point(1, 2) == Point(1, 2))

    Output: Point(x=3, y=0) True

    Key points

    • Hints are not enforced at runtime
    • frozen=True makes instances immutable

    Interview questions

    Are type hints checked when running?

    No; external tools like mypy check them.

    More Python topics