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.
for i in events(moving_avg(samples(sensor), k=3), threshold=4):
alert(i) # each next() pulls ONE sample through all stagesyield) 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.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.
- 1. A generator is most like…
- 2. A `with` block guarantees…
- 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.
- 1. In def f(a, *, b), b must be passed…
- 2. len(obj) calls…
- 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.
- 1. @retry(3) above def f means…
- 2. Why use functools.wraps?
- 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__raisesStopIterationwhen done. Aforloop 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 inwithblocks, not with manualclose()calls. - Descriptors:
@property, methods and@classmethodare descriptors (objects with__get__). That’s howobj.methodbecomes 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 calls (exponential); memoized, it makes n + 1.
- 1. [lambda: i for i in range(3)][0]() returns…
- 2. A for loop ends when the iterator…
- 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.
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
- Python Software Foundation. Python Tutorial, sections 4 (functions), 9 (classes) and Data model reference.
- L. Ramalho (2022). Fluent Python, 2nd ed. O’Reilly (chapters 9, 17, 18).
- PEP 255 (generators), PEP 318 (decorators), PEP 343 (the with statement).
- D. Beazley (2008). “Generator tricks for systems programmers.” PyCon tutorial.
- B. Slatkin (2019). Effective Python, 2nd ed. Addison-Wesley.