Foundations to Frontier
Tests
C. Programming, Tools and HPC › C1 Python for Science

Functions, Classes, Decorators, Generators and Context Managers

The five tools that turn Python scripts into reusable, robust research code. Functions are first-class objects (closures, *args/**kwargs, keyword-only arguments). Classes bundle state and behaviour, and dunder methods make objects work with len(), iteration and operators. Decorators wrap functions to add timing, retries or caching. Generators stream data lazily with constant memory. Context managers guarantee cleanup even when things fail. In the exercises you build a timing decorator, a retry decorator factory, a lazy sensor-processing pipeline, a ring buffer class and a state-restoring context manager, then measure memory (generators vs lists) and the effect of memoization.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Five ways to package behaviour

  • A function is a recipe you can reuse.
  • A class is a blueprint for objects that keep their own data and know how to act on it, like a “sensor” that remembers its last readings.
  • A decorator is a wrapper you put around a recipe, like a stopwatch that times every call without changing the recipe.
  • A generator hands out results one at a time, like a tap rather than a bucket, so it can handle endless streams.
  • A context manager (with …:) is a guaranteed clean-up crew: whatever happens inside, the file gets closed and the settings get restored.
Lazy generators vs eager lists: who holds what, when?
for i in events(moving_avg(samples(sensor), k=3), threshold=4):
    alert(i)          # each next() pulls ONE sample through all stages
samples   0106761008971000
moving_avg 0.00.50.32.34.36.34.72.30.32.75.78.05.72.70.30.0
events     ····⚡·····⚡·····
processed 0 of 16 samples · items held in memory ≈ 0 (the 3-sample window plus one value per stage) · alerts so far: none
A generator function (one with yield) returns a lazy iterator. Nothing runs until someone asks for the next value, and then just enough work happens to produce it. Chained generators stream data with constant memory and give results immediately (here the first alert arrives after 5 samples), which is what you want for an endless telemetry stream. Lists compute everything stage by stage, so memory grows with the data and nothing is available until the end.
Why engineers care

Flight-software tooling and robotics pipelines lean on these heavily: decorators for timing and retrying flaky hardware I/O, generators for streaming telemetry, context managers for safely opening serial ports, locking resources and entering and leaving safe modes, and classes to model sensors, vehicles and controllers.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A generator is most like…
  2. 2. A `with` block guarantees…
  3. 3. A decorator…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

Functions

def integrate(f, a, b, *, n=1000):     # '*' makes n keyword-only
    h = (b - a) / n
    return h * sum(f(a + (i + 0.5) * h) for i in range(n))

integrate(lambda x: x**2, 0, 1, n=100)  # functions are values

*args collects extra positional arguments into a tuple, and **kwargs collects keyword arguments into a dict. A function defined inside another can read (and with nonlocal, rebind) the outer variables: a closure.

Classes

class Sensor:
    def __init__(self, name, scale=1.0):
        self.name, self.scale, self.readings = name, scale, []
    def read(self, raw):
        self.readings.append(raw * self.scale)
        return self.readings[-1]
    def __len__(self):
        return len(self.readings)

Dunder methods (__len__, __iter__, __getitem__, __add__, __eq__, __repr__, …) let your objects plug into Python’s syntax. Use @property for computed attributes, @classmethod for alternative constructors, and inheritance sparingly; composition is usually clearer.

📝 Quick check (Level 1)
0/3 answered
  1. 1. In def f(a, *, b), b must be passed…
  2. 2. len(obj) calls…
  3. 3. def f(*args): return args; f(1, 2) returns…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

Decorators

@timed above def work means work = timed(work). A decorator takes a function and returns a wrapper. Use functools.wraps(fn) so the wrapper keeps the original name and docstring. A decorator factory takes arguments and returns a decorator: @retry(3) means work = retry(3)(work). Standard-library examples: functools.lru_cache (memoization), functools.cached_property, dataclasses.dataclass and contextlib.contextmanager.

Generators

A function containing yield returns a generator. Each next() runs it until the next yield. Generator expressions (f(x) for x in xs) are the lazy cousins of list comprehensions. Pipelines of generators process unbounded streams in constant memory, and itertools (islice, chain, groupby, accumulate, pairwise) supplies the building blocks.

Context managers

with open(p) as f: calls __enter__ and, no matter what, __exit__(exc_type, exc, tb). Write one as a class, or as a generator decorated with @contextmanager: the code before yield is setup, the code after it (in a finally block) is teardown. If __exit__ returns True, the exception is suppressed.

🐍 Exercise 1: decorators, generators, a class and a context manager
Build a timing decorator (with functools.wraps), a retry decorator factory, a lazy pipeline samples → moving_avg → events that reports rising edges above a threshold, a RingBuffer class supporting len/iteration/indexing, and a context manager that temporarily changes a setting and always restores it.
📝 Quick check (Level 2)
0/3 answered
  1. 1. @retry(3) above def f means…
  2. 2. Why use functools.wraps?
  3. 3. In a @contextmanager generator, teardown code belongs…

Level 3: Advanced

★★★★☆ Advanced⏱ 35 minGraduate level, with full derivations and proofs.

How the protocols fit together

  • Iteration protocol: iter(x) calls __iter__, returning an iterator whose __next__ raises StopIteration when done. A for loop is sugar for this, and generators implement it automatically.
  • Context-manager protocol: __enter__ / __exit__. The interpreter guarantees __exit__ runs, which is why resources should be acquired in with blocks, not with manual close() calls.
  • Descriptors: @property, methods and @classmethod are descriptors (objects with __get__). That’s how obj.method becomes a bound method.

Closures and late binding

Closures capture variables, not values: [lambda: i for i in range(3)] gives three functions that all return 2. Bind early with a default argument (lambda i=i: i) or with functools.partial.

Memoization

lru_cache stores results keyed by the arguments, so the arguments must be hashable. Naive recursive Fibonacci makes 2F(n+1)−12F(n+1) - 1 calls (exponential); memoized, it makes n + 1.

📝 Quick check (Level 3)
0/3 answered
  1. 1. [lambda: i for i in range(3)][0]() returns…
  2. 2. A for loop ends when the iterator…
  3. 3. lru_cache requires the arguments to be…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Laziness and caching, measured

Exercise 2 (CPython). Peak memory, measured with tracemalloc, for the mean square of n numbers:

n lists generators
10⁴ 0.65 MB 824 B
10⁵ 6.40 MB 824 B
2 × 10⁵ 12.85 MB 824 B

Lists cost about 64 bytes per element (a 24-byte float object plus an 8-byte pointer, for two lists), while the generator version is constant. In Pyodide’s 32-bit build (the browser) the numbers are smaller, 0.40, 4.00 and 8.02 MB against 420 B, about 40 bytes per element, but the contrast is the same. Memoization: naive fib(25) makes 242 785 calls, lru_cache makes 26.

🐍 Exercise 2 (research): memory of laziness, power of memoization
Measure peak memory (tracemalloc) of a list-based vs a generator-based computation for growing n, estimate bytes per element, and count function calls for Fibonacci with and without functools.lru_cache.

In AI, robotics and aerospace

  • Retry and timeout decorators around flaky hardware and network calls.
  • Generators for streaming logs, lazy data loaders and real-time sensor processing.
  • Context managers for opening devices, temporarily switching modes, timing sections and managing GPU memory (e.g. torch.no_grad()).
  • Classes for sensor models, vehicle state and controller interfaces.

References

  1. Python Software Foundation. Python Tutorial, sections 4 (functions), 9 (classes) and Data model reference.
  2. L. Ramalho (2022). Fluent Python, 2nd ed. O’Reilly (chapters 9, 17, 18).
  3. PEP 255 (generators), PEP 318 (decorators), PEP 343 (the with statement).
  4. D. Beazley (2008). “Generator tricks for systems programmers.” PyCon tutorial.
  5. B. Slatkin (2019). Effective Python, 2nd ed. Addison-Wesley.