Brainbotox · Lessons · Exams

Python Intermediate for Confirmed Developers: OOP and Decorators

by lazizanie · Programming · Python · English

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)
MethodCalled by
__str__print(x), str(x); falls back to __repr__
__len__len(x)
__getitem__x[key]
__contains__item in x
__call__x()
Defining __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 ** 2

A 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

An attribute defined in the class body is shared by all instances. A mutable one (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

  1. Which method does print(obj) use first?
  2. What happens if a class defines __eq__ but not __hash__?
  3. What does @property do?
  4. What is the first parameter of a classmethod?
  5. What does @dataclass generate automatically?
  6. What is the problem with a list defined in the class body, such as items = []?

Take the quiz on Brainbotox

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

TermHasExamples
Iterable__iter__(), which returns an iteratorlist, str, dict, file, range
Iterator__next__(), which returns the next value or raises StopIterationThe 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 time
Calling a generator function runs no code. It returns a generator object, and the body runs step by step as values are requested, keeping its local state between steps.

Generator 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))
A generator can be consumed only once. A second loop over it yields nothing. It has no 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 comprehension

Lazy built-ins and itertools

range, zip, map, filter and enumerate are lazy. The itertools module adds building blocks:

FunctionDoes
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

  1. What does a function containing yield return when called?
  2. Which exception signals that an iterator is exhausted?
  3. What is the advantage of (n * n for n in data) over [n * n for n in data]?
  4. What happens when you loop over the same generator a second time?
  5. What must an iterable provide?
  6. Which itertools function takes the first N items of an iterator?

Take the quiz on Brainbotox

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 argument

Closures

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()   # 2

The inner function keeps access to the variables of the function that created it, even after that function has returned.

Late binding: a closure looks up the variable when it is called, not when it is created. [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

DecoratorEffect
@functools.lru_cache(maxsize=128), @functools.cacheMemoises results by arguments, which must be hashable
@property, @classmethod, @staticmethodChange how a method is accessed
@dataclassA class decorator

Stacked decorators apply from the bottom up: the one closest to def wraps first.

Check yourself

  1. What is @timed above def load equivalent to?
  2. Why use functools.wraps in a decorator?
  3. What does nonlocal do?
  4. funcs = [lambda: i for i in range(3)]. What does funcs[0]() return?
  5. What does @functools.lru_cache do?
  6. How many nested function levels does a decorator with arguments need?

Take the quiz on Brainbotox

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 e chains exceptions so the traceback shows both.
  • A bare raise inside except re-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] = {}
Type hints are not enforced at run time: 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.
HintMeaning
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
AnySwitches checking off for that value

Check yourself

  1. Which two methods make an object usable in a with statement?
  2. When does __exit__ run?
  3. What does raise NewError('x') from e do?
  4. Why avoid a bare except:?
  5. Python raises an error at run time when an argument does not match its type hint.
  6. What does the hint User | None mean?

Take the quiz on Brainbotox

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
ImmutableMutable
int, float, bool, str, tuple, frozenset, Nonelist, 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 only
Python passes arguments by assignment (also called by object reference): the parameter is a new name for the same object. Mutating it is visible to the caller; rebinding it is not.

Shallow 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

TypeUse
defaultdict(list)A dict that creates a default value for missing keys: grouping
CounterCounts items; most_common(3)
dequeQueue with O(1) appends and pops at both ends
namedtupleA 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) and json.dumps(obj).
  • datetime: dates, times and timedelta. Prefer timezone-aware values.

Check yourself

  1. a = [1, 2]; b = a; b.append(3). What is a?
  2. What is the difference between == and is?
  3. After shallow = grid.copy() on a list of lists, what is shared?
  4. What is wrong with grid = [[0] * 3] * 3?
  5. Which collections type is ideal for counting occurrences?
  6. A function does items = ['new'] on its list parameter. What does the caller see?

Take the quiz on Brainbotox

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.py
from 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() == expected
pytest discovers files named test_*.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

  1. What does pip freeze output?
  2. How does pytest find tests?
  3. What is a pytest fixture?
  4. How do you check that code raises ValueError in pytest?
  5. How many times is a module's top-level code executed when it is imported from several places?
  6. What is pyproject.toml?

Take the quiz on Brainbotox