Python Advanced: Decorators, Generators and Typing
Type Hints and Dataclasses
In this lesson you will
- Add type hints to variables, functions and collections
- Use @dataclass for simple data-holding classes
- Use Enum and Optional for clear, safe code
Introduction
Python decides types as the program runs, which is flexible but can hide mistakes until it is too late. Type hints let you write down what types you expect. Python itself does not enforce them at runtime. Their value is that your editor and tools such as mypy can check them for you, and that they document your code for the next reader.
Type hints
Write a colon and the type after a variable or parameter, and -> before a function's return type.
Because the hints are ignored by Python, this still runs (and a checker like mypy would complain about it):
Quick quiz
What does Python do with type hints when it runs your program?
Optional values and unions
A value that may be missing is X | None. A value that can be one of several types uses |.
Checking is None first is exactly the habit that a type checker wants to see.
Dataclasses: less boilerplate
Many classes only hold data. Writing __init__, __repr__ and __eq__ by hand is repetitive. The @dataclass decorator writes them for you, based on type-hinted fields.
You get a readable repr and equality for free. Fields with defaults must come after fields without.
More dataclass options
frozen=True makes instances read-only, which also makes them usable as dictionary keys. For a mutable default such as a list, use field(default_factory=list). A plain = [] would be shared by every object.
Quick quiz
Why use field(default_factory=list) instead of members: list = []?
Enums: a fixed set of choices
An enum is a named set of constants. It is clearer and safer than loose strings or numbers.
A misspelled Status.PUBLISHD is an immediate error, whereas the string "publishd" would silently be wrong.
Putting it together
Try it yourself
Create a dataclass Product with name: str, price: float and quantity: int = 0, and add a method total_value() that returns price * quantity. Create two products and print the total value of both.
Summary
- Type hints (
x: int,-> str) document code and help tools, but Python does not enforce them. X | Nonemarks optional values, so checkis Nonebefore using them.@dataclasswrites__init__,__repr__and__eq__for you. Usefield(default_factory=...)for mutable defaults.- An
Enumnames a fixed set of choices and prevents typos.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading