These are the notes for Python episode 27. Raju's app takes orders from a form, and form input is always text, so a price of "15" times 2 gives a bill of 1515 rupees, with no error at all. In this episode you learn type hints (labels that say what type each value should be), find out why they don't stop wrong types when the code runs, and use a type checker (mypy) that reads them before running. Then we fix a second pain: small classes whose __init__ repeats every name three times, print as <__main__.Order object at 0x...>, and say two identical orders are not equal. You invent dataclasses, which write __init__, __repr__ and __eq__ from the hints. We cover hints for containers and None, defaults, field(default_factory=list), frozen=True, order=True, __post_init__ validation, and a fully typed menu and bill. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13; mypy output is from mypy run on the same code.
The problem: a 1515 rupee samosa
def line_total(price, qty):
return price * qty
print("Chai:", line_total(10, 3))
print("Samosa:", line_total("15", 2))
Output:
Chai: 30
Samosa: 1515
Why it fails: Python only checks a type when an operation runs, and text × number is allowed: it repeats the text ("15" * 2 → "1515", episode 5). Nothing in the function says price must be a number: not to Python, and not to the next programmer reading it. (A type is the kind of a value: int, float, str, list, ...; episode 2.)
Type hints
A label on a kitchen jar says SUGAR. A type hint is that label for a parameter, a variable or a return value:
def line_total(price: int, qty: int) -> int:
return price * qty
print("Chai:", line_total(10, 3))
print("Samosa:", line_total("15", 2))
print(line_total.__annotations__)
Output:
Chai: 30
Samosa: 1515
{'price': <class 'int'>, 'qty': <class 'int'>, 'return': <class 'int'>}
price: intmeans "price should be anint".-> intafter the brackets means "this function returns anint".- Python stores the hints in the function's
__annotations__dictionary (hints are also called annotations).
Surprise: the samosa is still 1515. A label can't stop anyone putting salt in the sugar jar. Hints are labels, not guards: Python does not check them when the code runs. They are for people, editors and checking tools.
Variables can have hints too: total: int = 0, names: list[str] = [].
A type checker: mypy
A type checker reads your code and its hints without running it, and reports mismatches. The most common one is mypy. Install it with pip (episode 30) and run it on a file:
# file: bill.py
def line_total(price: int, qty: int) -> int:
return price * qty
print("Samosa:", line_total("15", 2))
$ pip install mypy
$ mypy bill.py
bill.py:5: error: Argument 1 to "line_total" has incompatible type "str"; expected "int" [arg-type]
Found 1 error in 1 file (checked 1 source file)
Caught before a single customer saw the bill. Editors such as VS Code (with the Python extension, which uses a checker called Pylance/Pyright) use the same hints to underline mistakes as you type and to suggest methods.
Hints for containers and None
| Hint | Means | Example value |
|---|---|---|
int, float, str, bool |
a single value of that type | 10, 2.5, "chai", True |
list[str] |
a list of strings | ["chai", "samosa"] |
dict[str, int] |
a dict from strings to ints | {"chai": 10} |
tuple[str, int] |
a 2-item tuple: a string, then an int | ("chai", 10) |
set[int] |
a set of ints | {1, 2} |
int \| None |
an int or None (Python 3.10+) |
10 or None |
-> None |
the function returns nothing | def show(self) -> None: |
(Older code writes List[str], Dict[str, int] and Optional[int] from the typing module; the lowercase forms work since Python 3.9, and X | None since 3.10.)
def find_price(menu: dict[str, int], item: str) -> int | None:
return menu.get(item)
menu = {"chai": 10, "samosa": 15}
price = find_price(menu, "coffee")
print(price + 5)
Output:
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(price + 5)
~~~~~~^~~
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
dict.get() returns None for a missing key (episode 12). mypy catches this one before running, because the hint says the result might be None:
$ mypy main.py
main.py:6: error: Unsupported operand types for + ("None" and "int") [operator]
main.py:6: note: Left operand is of type "int | None"
Found 1 error in 1 file (checked 1 source file)
The fix: handle the None case first.
def find_price(menu: dict[str, int], item: str) -> int | None:
return menu.get(item)
menu = {"chai": 10, "samosa": 15}
price = find_price(menu, "coffee")
if price is None:
print("coffee is not on the menu")
else:
print(price + 5)
Output:
coffee is not on the menu
Inside the else, mypy knows price is an int (this is called narrowing).
The second problem: boilerplate classes
Boilerplate is code you have to write again and again that carries no new idea.
class Order:
def __init__(self, item, price, qty):
self.item = item
self.price = price
self.qty = qty
a = Order("chai", 10, 2)
b = Order("chai", 10, 2)
print(a)
print(a == b)
Output (the address will differ):
<__main__.Order object at 0x7fe23c5370e0>
False
- Every field name is typed three times (
item,self.item = item). - Printing shows only an address: there's no
__repr__. a == bisFalse: by default==checks whether they are the same object, not the same data; there's no__eq__.
Fixing it by hand means writing __repr__ and __eq__ (episode 23) for every class. But all the information is just three names and three types: a tool could write the rest.
@dataclass
from dataclasses import dataclass
@dataclass
class Order:
item: str
price: int
qty: int = 1
a = Order("chai", 10, 2)
b = Order("chai", 10, 2)
print(a)
print(a == b)
print(Order("samosa", 15))
Output:
Order(item='chai', price=10, qty=2)
True
Order(item='samosa', price=15, qty=1)
The @dataclass decorator (episode 25) reads the class's type-hinted fields and writes:
__init__(self, item, price, qty=1): every field, in order, with defaults;__repr__: a readable print,Order(item='chai', price=10, qty=2);__eq__: compares the fields one by one, soa == bisTrue.
It's a real __init__:
print(Order("chai"))
TypeError: Order.__init__() missing 1 required positional argument: 'price'
Rule: fields with a default must come after fields without one (same as function defaults). Otherwise:
TypeError: non-default argument 'y' follows default argument 'x'
A dataclass is still a normal class: you can add methods, properties and inheritance.
Defaults: the mutable default trap
from dataclasses import dataclass
@dataclass
class Table:
number: int
orders: list = []
Output:
Traceback (most recent call last):
...
ValueError: mutable default <class 'list'> for field orders is not allowed: use default_factory
One shared empty list would be used by every table (the same bug as a list default in a function, episode 13). A mutable value is one that can be changed in place (lists, dicts, sets). Dataclasses refuse it.
The fix: field(default_factory=list): call list() to make a fresh empty list for each new object. (A factory is something that makes new objects.)
from dataclasses import dataclass, field
@dataclass
class Table:
number: int
orders: list[str] = field(default_factory=list)
t1 = Table(1)
t2 = Table(2)
t1.orders.append("chai")
print(t1)
print(t2)
Output:
Table(number=1, orders=['chai'])
Table(number=2, orders=[])
frozen=True: read-only objects
from dataclasses import dataclass
@dataclass(frozen=True)
class MenuItem:
name: str
price: int
chai = MenuItem("chai", 10)
print(chai)
chai.price = 5
Output:
MenuItem(name='chai', price=10)
Traceback (most recent call last):
File "main.py", line 10, in <module>
chai.price = 5
^^^^^^^^^^
File "<string>", line 16, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'price'
Nobody can change it by accident. To get a changed copy, use dataclasses.replace(chai, price=5). Frozen dataclasses are also hashable, so they can go in sets and be dict keys.
__post_init__: checking values
Hints don't stop bad values, but the generated __init__ calls a method named __post_init__ (if you write one) right after setting the fields:
from dataclasses import dataclass
@dataclass
class Order:
item: str
price: int
qty: int = 1
def __post_init__(self):
if self.price <= 0:
raise ValueError(f"price must be positive, got {self.price}")
print(Order("chai", 10))
print(Order("vada pav", -20))
Output:
Order(item='chai', price=10, qty=1)
Traceback (most recent call last):
File "main.py", line 14, in <module>
print(Order("vada pav", -20))
~~~~~^^^^^^^^^^^^^^^^^
File "<string>", line 6, in __init__
File "main.py", line 11, in __post_init__
raise ValueError(f"price must be positive, got {self.price}")
ValueError: price must be positive, got -20
(File "<string>" is the __init__ that @dataclass generated.)
Common mistakes
| Mistake | What you see | Why | Fix |
|---|---|---|---|
line_total("15", 2) with price: int |
no error: prints 1515 |
hints aren't checked at runtime | run mypy; convert input with int() |
price + 5 where price: int \| None |
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' |
the value was None |
if price is None: ... |
Order("chai") |
TypeError: Order.__init__() missing 1 required positional argument: 'price' |
no default for price |
pass it, or give it a default |
orders: list = [] |
ValueError: mutable default <class 'list'> for field orders is not allowed: use default_factory |
one list would be shared by all | field(default_factory=list) |
| a default field before a non-default one | TypeError: non-default argument 'y' follows default argument 'x' |
__init__ needs required parameters first |
put defaults last |
chai.price = 5 on a frozen dataclass |
dataclasses.FrozenInstanceError: cannot assign to field 'price' |
frozen means read-only | dataclasses.replace(chai, price=5) |
a field without a hint: price = 10 |
not a field: missing from __init__ and repr |
dataclass only uses annotated names | price: int = 10 |
Mini project: a typed menu and bill
MenuItemis frozen andorder=True: dataclass also writes<,>,<=,>=, comparing fields in order. Price is the first field, so items sort by price.Billhas a table number and a list of lines, each a(MenuItem, int)tuple, withdefault_factory.- Typed methods add a line and work out the total.
from dataclasses import dataclass, field
@dataclass(frozen=True, order=True)
class MenuItem:
price: int
name: str
@dataclass
class Bill:
table: int
lines: list[tuple[MenuItem, int]] = field(default_factory=list)
def add(self, item: MenuItem, qty: int = 1) -> None:
self.lines.append((item, qty))
def total(self) -> int:
return sum(item.price * qty for item, qty in self.lines)
menu = [MenuItem(20, "vada pav"), MenuItem(10, "chai"), MenuItem(15, "samosa")]
print(sorted(menu))
print(max(menu).name)
bill = Bill(table=4)
bill.add(menu[1], 3)
bill.add(menu[2], 2)
print("Lines:", len(bill.lines))
print("Total: Rs", bill.total())
Output:
[MenuItem(price=10, name='chai'), MenuItem(price=15, name='samosa'), MenuItem(price=20, name='vada pav')]
vada pav
Lines: 2
Total: Rs 60
And mypy on the file:
$ mypy bill.py
Success: no issues found in 1 source file
Practice
1. Add type hints to three functions, and check them with mypy.
Solution
def average(marks: list[int]) -> float:
return sum(marks) / len(marks)
def greet(name: str, times: int = 1) -> str:
return ("Hi " + name + "! ") * times
def find_student(names: list[str], target: str) -> int | None:
for i, name in enumerate(names):
if name == target:
return i
return None
print(average([80, 90, 70]))
print(greet("Asha", 2))
print(find_student(["Asha", "Ravi"], "Ravi"))
print(find_student(["Asha", "Ravi"], "Meena"))
Output:
80.0
Hi Asha! Hi Asha!
1
None
mypy: Success: no issues found in 1 source file.
2. A Student dataclass with marks: list[int] and an average() method.
Solution
from dataclasses import dataclass, field
@dataclass
class Student:
name: str
marks: list[int] = field(default_factory=list)
def average(self) -> float:
return sum(self.marks) / len(self.marks) if self.marks else 0.0
asha = Student("Asha", [80, 90, 70])
ravi = Student("Ravi")
ravi.marks.append(65)
print(asha, asha.average())
print(ravi, ravi.average())
Output:
Student(name='Asha', marks=[80, 90, 70]) 80.0
Student(name='Ravi', marks=[65]) 65.0
3. A frozen Point(x, y); make a moved copy with replace, then try to change x.
Solution
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(2, 3)
moved = replace(p, x=5)
print(p, moved)
p.x = 10
Output:
Point(x=2, y=3) Point(x=5, y=3)
Traceback (most recent call last):
File "main.py", line 11, in <module>
p.x = 10
^^^
File "<string>", line 16, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'x'
4. Add a show() method to the Bill that prints each line.
Solution
from dataclasses import dataclass, field
@dataclass(frozen=True, order=True)
class MenuItem:
price: int
name: str
@dataclass
class Bill:
table: int
lines: list[tuple[MenuItem, int]] = field(default_factory=list)
def add(self, item: MenuItem, qty: int = 1) -> None:
self.lines.append((item, qty))
def total(self) -> int:
return sum(item.price * qty for item, qty in self.lines)
def show(self) -> None:
print(f"Table {self.table}")
for item, qty in self.lines:
print(f" {item.name:<10}{qty} x {item.price:>3} = {item.price * qty:>4}")
print(f" {'Total':<18}= {self.total():>4}")
bill = Bill(4)
bill.add(MenuItem(10, "chai"), 3)
bill.add(MenuItem(15, "samosa"), 2)
bill.show()
Output:
Table 4
chai 3 x 10 = 30
samosa 2 x 15 = 30
Total = 60
(:<10 pads to 10 characters, left-aligned; :>3 right-aligns in 3: f-string format specs from episode 5.)
Quick quiz
1. The video's quiz: what does this print?
from dataclasses import dataclass
@dataclass
class Cup:
size: int = 1
print(Cup() == Cup(1), Cup(2))
Answer
True Cup(size=2)
The generated __eq__ compares fields (1 == 1), and the generated __repr__ shows the field name.
2. Does def f(x: int): return x * 2 followed by f("ab") raise an error?
Answer
No. It returns 'abab'. Hints are not checked at runtime; mypy would report it.
3. Why does orders: list = [] fail in a dataclass, and what's the fix?
Answer
A single list would be shared by every object, so dataclasses raise ValueError: mutable default ... use default_factory. Use orders: list[str] = field(default_factory=list).
Interview questions
- Does Python enforce type hints? No. They're stored in
__annotations__and ignored at runtime; static checkers (mypy, Pyright) and IDEs use them. - Why use type hints in a dynamic language? Catching bugs before running, better editor autocomplete and refactoring, and self-documenting code, especially in large teams and codebases.
- What is
Optional[int]? The same asint | None: the value may be anintorNone. - What does
@dataclassgenerate?__init__,__repr__and__eq__by default; with options also ordering methods (order=True), immutability and__hash__(frozen=True),__slots__(slots=True), keyword-only fields (kw_only=True). - Why
field(default_factory=list)instead of= []? To give each instance its own new list instead of one shared mutable default. - What is
__post_init__for? Validation or computing derived fields after the generated__init__sets the fields. - Dataclass vs namedtuple vs dict? A dict has no fixed fields or types; a namedtuple is immutable and tuple-like; a dataclass is a full class (mutable by default, methods, defaults, validation).
- How do you "change" a frozen dataclass? You don't; create a modified copy with
dataclasses.replace(obj, field=value). - What is type narrowing? When a checker learns a more specific type from a check, e.g. after
if price is None: return,priceis treated asint.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Type | The kind of a value | int, str, list |
| Type hint (annotation) | A label saying what type a value should be | price: int |
| Return hint | The type a function returns, after -> |
-> int |
__annotations__ |
Where Python stores a function's or class's hints | line_total.__annotations__ |
| Runtime | While the program is running | hints are not checked at runtime |
| Static type checker | A tool that checks types by reading code, without running it | mypy, Pyright |
| mypy | The most common Python type checker | mypy bill.py |
list[str], dict[str, int] |
Hints for containers and what they hold | menu: dict[str, int] |
int \| None / Optional[int] |
An int or None |
-> int \| None |
-> None |
The function returns nothing | def add(...) -> None: |
| Narrowing | A checker learning a more specific type after a check | if price is None: |
| Boilerplate | Repetitive code that carries no new idea | self.item = item |
| Dataclass | A class whose __init__, __repr__, __eq__ are generated from its fields |
@dataclass class Order: |
| Field | One annotated attribute of a dataclass | item: str |
__repr__ |
Gives the text shown when you print an object | Order(item='chai', ...) |
__eq__ |
Defines what == means |
compares the fields |
| Mutable | Can be changed in place | lists, dicts, sets |
| Mutable default | A shared list/dict used as a default (a bug) | orders: list = [] |
field(default_factory=...) |
Makes a fresh default value for each object | field(default_factory=list) |
frozen=True |
Makes dataclass objects read-only (and hashable) | @dataclass(frozen=True) |
FrozenInstanceError |
The error for changing a frozen dataclass | cannot assign to field 'price' |
dataclasses.replace |
Makes a copy with some fields changed | replace(p, x=5) |
order=True |
Generates <, >, <=, >= comparing fields in order |
sort menu items by price |
__post_init__ |
Runs right after the generated __init__; used for checks |
if self.price <= 0: raise ... |
| Hashable | Can be a dict key or set member (has a fixed hash) | frozen dataclasses, tuples |
Summary
- Python lets a wrong type slip through:
"15" * 2→"1515", a silent wrong bill. - Type hints label parameters, variables and returns:
price: int,-> int. - Hints are not checked at runtime; a type checker like mypy reads them before running.
- Use
list[str],dict[str, int],tuple[...]andint | None; handle theNonecase. @dataclassturns typed fields into__init__,__repr__and__eq__.- Defaults go last; lists need
field(default_factory=list). frozen=Truefor read-only data (replace()makes a changed copy),order=Truefor sorting,__post_init__for checks.
Next episode: Raju has five hundred messy customer messages and wants every phone number from them. We invent regular expressions.