Python Intermediate for Confirmed Developers: OOP and Decorators
Intermediate Python for confirmed developers: the data model and OOP, iterators and generators, closures and decorators, context managers, type hints, mutability, pytest and packaging.
Study this lesson with its quizzes on Brainbotox →
Python OOP in depth: dunder methods, properties and dataclasses
Python's data model lets your classes plug into the language: special "dunder" methods such as __eq__ and __len__ define how objects behave with operators and built-in functions.
Special methods
class Money:
def __init__(self, amount):
self.amount = amount
def __repr__(self): # for developers: repr(), debugger, lists
return f'Money({self.amount})'
def __eq__(self, other): # ==
return isinstance(other, Money) and self.amount == other.amount
def __lt__(self, other): # <, enables sorting
return self.amount < other.amount
def __add__(self, other): # +
return Money(self.amount + other.amount)
def __hash__(self):
return hash(self.amount)| Method | Called by |
|---|---|
__str__ | print(x), str(x); falls back to __repr__ |
__len__ | len(x) |
__getitem__ | x[key] |
__contains__ | item in x |
__call__ | x() |
__eq__ without __hash__ makes instances unhashable: they can no longer be dict keys or set members. Equal objects must have equal hashes.Properties
class Circle:
def __init__(self, radius):
self.radius = radius # goes through the setter
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError('radius must be positive')
self._radius = value
@property
def area(self): # computed, read-only
return 3.14159 * self._radius ** 2A property looks like an attribute but runs code. A leading underscore (_radius) marks an attribute as internal, by convention only.
classmethod and staticmethod
class Date:
@classmethod
def from_string(cls, text): # alternative constructor
return cls(*map(int, text.split('-')))
@staticmethod
def is_leap(year): # no self, no cls
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)Dataclasses
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Point:
x: int
y: int = 0
tags: list = field(default_factory=list)@dataclass generates __init__, __repr__ and __eq__ from the annotated fields. frozen=True makes instances immutable and hashable.
Class attributes and duck typing
items = []) is shared state: create it in __init__.Duck typing: Python cares about what an object can do, not its class. For a formal contract, inherit from abc.ABC and mark methods with @abstractmethod.
Check yourself
- Which method does print(obj) use first?
- What happens if a class defines __eq__ but not __hash__?
- What does @property do?
- What is the first parameter of a classmethod?
- What does @dataclass generate automatically?
- What is the problem with a list defined in the class body, such as items = []?
Python iterators, generators and comprehensions
An iterator produces values one at a time on demand, and a generator is the easy way to write one: a function that uses yield. Both make it possible to process data that does not fit in memory.
The iteration protocol
| Term | Has | Examples |
|---|---|---|
| Iterable | __iter__(), which returns an iterator | list, str, dict, file, range |
| Iterator | __next__(), which returns the next value or raises StopIteration | The result of iter(x), generators |
it = iter([1, 2]) next(it) # 1 next(it) # 2 next(it) # StopIteration
A for loop calls iter() once and then next() until StopIteration.
Generator functions
def countdown(n):
while n > 0:
yield n # hands a value out and pauses here
n -= 1
for x in countdown(3): # 3, 2, 1
print(x)
def read_lines(path):
with open(path) as f:
for line in f:
yield line.rstrip() # one line in memory at a timeGenerator expressions
squares_list = [n * n for n in range(1_000_000)] # builds the whole list squares_gen = (n * n for n in range(1_000_000)) # lazy, almost no memory total = sum(n * n for n in range(1_000_000))
len() and cannot be indexed.Other comprehensions
lengths = {word: len(word) for word in words} # dict comprehension
initials = {word[0] for word in words} # set comprehensionLazy built-ins and itertools
range, zip, map, filter and enumerate are lazy. The itertools module adds building blocks:
| Function | Does |
|---|---|
chain(a, b) | Iterates a then b |
islice(it, 10) | Takes the first 10 items of any iterator |
groupby(it, key) | Groups consecutive items with the same key |
count(), cycle() | Infinite iterators |
Check yourself
- What does a function containing yield return when called?
- Which exception signals that an iterator is exhausted?
- What is the advantage of (n * n for n in data) over [n * n for n in data]?
- What happens when you loop over the same generator a second time?
- What must an iterable provide?
- Which itertools function takes the first N items of an iterator?
Python closures and decorators
A decorator is a function that takes a function and returns a replacement, used to add behaviour such as logging, timing, caching or access checks without changing the original code. It relies on closures.
Functions are objects
def shout(text):
return text.upper()
f = shout # assign to a variable
f('hi') # 'HI'
sorted(words, key=len) # pass as an argumentClosures
def make_counter():
count = 0
def increment():
nonlocal count # needed to assign to the enclosing variable
count += 1
return count
return increment
counter = make_counter()
counter() # 1
counter() # 2The inner function keeps access to the variables of the function that created it, even after that function has returned.
[lambda: i for i in range(3)] gives three functions that all return 2. Fix it with a default argument: lambda i=i: i.Writing a decorator
import functools, time
def timed(func):
@functools.wraps(func) # keeps func's name and docstring
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f'{func.__name__} took {time.perf_counter() - start:.3f}s')
return result
return wrapper
@timed
def load(path): ...@timed above def load means exactly load = timed(load). It runs once, when the function is defined.Decorators with arguments
def retry(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(times):
try:
return func(*args, **kwargs)
except ConnectionError:
if attempt == times - 1:
raise
return wrapper
return decorator
@retry(times=3)
def download(url): ...Three levels: retry(3) returns the real decorator, which returns the wrapper.
Useful built-in decorators
| Decorator | Effect |
|---|---|
@functools.lru_cache(maxsize=128), @functools.cache | Memoises results by arguments, which must be hashable |
@property, @classmethod, @staticmethod | Change how a method is accessed |
@dataclass | A class decorator |
Stacked decorators apply from the bottom up: the one closest to def wraps first.
Check yourself
- What is @timed above def load equivalent to?
- Why use functools.wraps in a decorator?
- What does nonlocal do?
- funcs = [lambda: i for i in range(3)]. What does funcs[0]() return?
- What does @functools.lru_cache do?
- How many nested function levels does a decorator with arguments need?
Python context managers, exception design and type hints
Context managers guarantee clean-up with the with statement, a well-designed exception hierarchy makes errors easy to handle, and type hints let tools find bugs before the code runs.
Context managers
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self # bound to the name after 'as'
def __exit__(self, exc_type, exc, tb):
print(time.perf_counter() - self.start)
return False # do not swallow exceptions
with Timer() as t:
work()__exit__ always runs when the block ends, whether normally or through an exception. That is what makes with the right tool for files, locks, database transactions and temporary changes.from contextlib import contextmanager
@contextmanager
def cd(path):
old = os.getcwd()
os.chdir(path)
try:
yield # the with block runs here
finally:
os.chdir(old)Exception design
class AppError(Exception): ...
class NotFoundError(AppError): ...
try:
data = json.loads(text)
except json.JSONDecodeError as e:
raise ConfigError('invalid config file') from e # keeps the cause- Derive your exceptions from
Exception, with one base class per application or library. raise ... from echains exceptions so the traceback shows both.- A bare
raiseinsideexceptre-raises the current exception.
except: and except BaseException: also catch KeyboardInterrupt and SystemExit. Catch Exception at most, and preferably something specific.Type hints
def find_user(user_id: int) -> User | None: ...
def total(prices: list[float], tax: float = 0.2) -> float:
return sum(prices) * (1 + tax)
names: dict[str, int] = {}total('abc') still runs until it fails. Static checkers such as mypy or pyright read the hints and report mismatches before execution, and editors use them for autocompletion.| Hint | Meaning |
|---|---|
int | None or Optional[int] | An int or None |
list[str], dict[str, int] | Typed containers |
Callable[[int], str] | A function from int to str |
Any | Switches checking off for that value |
Check yourself
- Which two methods make an object usable in a with statement?
- When does __exit__ run?
- What does raise NewError('x') from e do?
- Why avoid a bare except:?
- Python raises an error at run time when an argument does not match its type hint.
- What does the hint User | None mean?
Python mutability, copies and the collections module
In Python, assignment never copies an object: it binds another name to the same object. Most surprising bugs at the intermediate level come from two names sharing one mutable object.
Names and objects
a = [1, 2] b = a # same list, two names b.append(3) print(a) # [1, 2, 3] a == b # True: equal values a is b # True: the same object
| Immutable | Mutable |
|---|---|
| int, float, bool, str, tuple, frozenset, None | list, dict, set, most class instances |
Arguments
def add_item(items):
items.append('x') # mutates the caller's list
def rebind(items):
items = ['new'] # rebinds the local name onlyShallow and deep copies
import copy grid = [[0, 0], [0, 0]] shallow = grid.copy() # or list(grid), grid[:] deep = copy.deepcopy(grid) shallow[0][0] = 9 print(grid[0][0]) # 9: inner lists are shared print(deep[0][0]) # 0
[[0] * 3] * 3 creates three references to the same inner list. Use [[0] * 3 for _ in range(3)].A tuple is immutable, but it can contain a mutable object: t = ([1], 2) allows t[0].append(5).
The collections module
| Type | Use |
|---|---|
defaultdict(list) | A dict that creates a default value for missing keys: grouping |
Counter | Counts items; most_common(3) |
deque | Queue with O(1) appends and pops at both ends |
namedtuple | A tuple with named fields |
from collections import Counter, defaultdict
Counter('mississippi').most_common(2) # [('i', 4), ('s', 4)]
by_city = defaultdict(list)
for person in people:
by_city[person.city].append(person)Other everyday modules
pathlib.Path: file paths as objects,Path('data') / 'file.txt'.json:json.loads(text)andjson.dumps(obj).datetime: dates, times andtimedelta. Prefer timezone-aware values.
Check yourself
- a = [1, 2]; b = a; b.append(3). What is a?
- What is the difference between == and is?
- After shallow = grid.copy() on a list of lists, what is shared?
- What is wrong with grid = [[0] * 3] * 3?
- Which collections type is ideal for counting occurrences?
- A function does items = ['new'] on its list parameter. What does the caller see?
Python packaging, virtual environments and testing with pytest
A maintainable Python project has a clear package layout, pinned dependencies in an isolated environment, automated tests, and logging in place of print.
Project layout
myproject/
pyproject.toml
src/
shop/
__init__.py # makes shop a package
cart.py
pricing.py
tests/
test_cart.pyfrom shop.pricing import apply_tax # absolute import from .pricing import apply_tax # relative import, inside the package
A module is executed once, on first import, then cached in sys.modules. Two modules that import each other at top level create a circular import error; move the shared code to a third module.
Environments and dependencies
python -m venv .venv source .venv/bin/activate pip install -r requirements.txt pip freeze > requirements.txt # exact versions installed
pyproject.toml is the standard file describing a project, its dependencies and its tool settings. Pin versions (or use a lock file) so that every machine installs the same thing.
pytest
# tests/test_cart.py
import pytest
from shop.cart import Cart
@pytest.fixture
def cart():
return Cart() # fresh object for each test
def test_add_item(cart):
cart.add('book', 10)
assert cart.total() == 10 # plain assert
def test_negative_price_rejected(cart):
with pytest.raises(ValueError):
cart.add('book', -1)
@pytest.mark.parametrize('qty, expected', [(1, 10), (3, 30)])
def test_quantity(cart, qty, expected):
cart.add('book', 10, qty)
assert cart.total() == expectedtest_*.py and functions named test_*. A fixture provides set-up, injected by naming it as a parameter.Mocking
from unittest.mock import patch
def test_report():
with patch('shop.report.send_email') as fake:
make_report()
fake.assert_called_once()Patch the name where it is used, not where it is defined.
Logging and code quality
import logging
log = logging.getLogger(__name__)
log.info('order %s created', order_id)Logging has levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) and configurable destinations. Run a formatter and linter such as ruff or black, plus a type checker, in continuous integration.
Check yourself
- What does pip freeze output?
- How does pytest find tests?
- What is a pytest fixture?
- How do you check that code raises ValueError in pytest?
- How many times is a module's top-level code executed when it is imported from several places?
- What is pyproject.toml?