APDR

Concurrency, Metaprogramming, and Debugging

Algorithms, Programming, and Data Representation · Module 92313 · Chapter 89a

Choose a concurrency model by the work and the sharing it needs, then use Python’s reflective tools deliberately. The guide ends with a testing and debugging workflow for code that behaves differently across runs.

Start from memory

Try each prompt first; mark it sure, unsure, or guessed.

  1. Which work benefits most from overlapping I/O waits?
  2. What does an await let an asyncio event loop do?
  3. Does every CPython build require the GIL?
  4. What does a decorator return?
  5. What does a metaclass control?
  6. Why can inspect.getsource fail?
Check the short answers
  1. I/O-bound work can progress while another task waits. §8.1–8.3
  2. It suspends the current task while the awaited operation is incomplete, allowing other tasks or I/O to run. §8.3
  3. No. Since Python 3.13 there are optional free-threaded builds; Python 3.14 officially supports them, while the ordinary build still has the GIL. §8.2
  4. Usually a replacement callable that wraps or otherwise changes the original function. §9.2
  5. How a class object is created. §9.3
  6. Its source may be unavailable, for example for built-ins or dynamically created code. §9.1

How to use this guide

Work the concurrency cases by first naming the bottleneck, the shared state, and the needed parallelism. For metaprogramming, trace what object is read or replaced at definition time before considering a more powerful mechanism.

  1. Day 0: Study §8.1–8.3; solve practice 1–6.
  2. Day 1: Rebuild §8.4–8.5 and solve practice 7–10.
  3. Day 3: Study §9.1–9.3; solve practice 11–15.
  4. About day 7: Rebuild §9.4–9.6; solve practice 16–21.
  5. About day 14: Attempt both exam problems closed-book, then explain your uncertain choices aloud.
  6. Before the exam: Recheck only skills supported by the listed practice evidence; revisit the section links for missed answers.

When stuck: write down the observable question, the state that can change, and the next event that can run. For a failing test, reduce the input while preserving the failure before changing the implementation.

How the chapter fits together

First choose how work is scheduled; then inspect or alter program objects only where the simpler language features are not enough; finally collect evidence with tests and debugging tools.

Measure · select and observe execution

  • Threads, processes, and tasks §8.1

    shared memory · separate process

    Rests on: how the work shares data.

  • GIL and free-threaded builds §8.2

    default build · optional free-threading

    Rests on: interpreter build and extensions.

  • Asyncio scheduling §8.3

    await → suspend → resume

    Rests on: the event loop and suspension points.

  • Workload and language models §8.4–8.5

    wait · compute · coordinate

    Rests on: bottleneck, sharing, and runtime.

Define · inspect and transform

  • Introspection §9.1

    type · attributes · signature

    Rests on: runtime objects expose metadata.

  • Decorators §9.2

    name = decorate(function)

    Rests on: functions are values that can be replaced.

  • Metaclasses and class hooks §9.3

    class object → metaclass

    Rests on: classes are runtime objects.

  • Dynamic code and ASTs §9.4

    syntax tree → compiled code

    Rests on: code can be represented as data, then executed.

Derive · observe and verify

  • Instrumentation and patching §9.5

    observe · replace · restore

    Rests on: names are resolved at lookup sites.

  • Testing and debugging §9.6

    reproduce → reduce → verify

    Rests on: evidence from tests, tasks, and stacks.

QuestionStart with
Many waits or many CPU calculations?Threads/async I/O versus processes, native code, or a free-threaded build
Need to change a callable’s behaviour?Decorator before a metaclass or dynamic code
Failure depends on timing or input?Reproduce, trace state, then add a focused test

8.1 Threads and processes

Concurrency overlaps progress; parallelism runs work at the same instant. The memory-sharing choice affects both coordination and failure isolation.

In plain words: Threads are several workers sharing one room and its objects; processes are workers in separate rooms who need a message or shared-memory arrangement to exchange results. A thread belongs to a process; a process has its own address space.

Model comparisonThreads → shared process memory; coordinate shared mutable stateProcesses → separate memory by default; communicate explicitlyThese are OS/runtime concepts, not a promise that every task will run faster. Startup, copying, communication and scheduling all cost time.

Python’s threading suits overlapping waits and APIs that block. Threads can share objects cheaply, but shared mutation needs a clear synchronisation rule. multiprocessing uses processes that can run on multiple cores; their state is separate by default, so results cross a queue, pipe, or shared-memory interface.

A pool hides some lifecycle work. ThreadPoolExecutor and ProcessPoolExecutor submit callables and return futures. Select the pool from the workload and data movement: passing a huge object to another process can erase the benefit of parallel calculation.

Trap: “A process is always faster.” Process creation, serialisation and communication can cost more than the calculation.

Near miss: Two threads increment one shared total and produce a stable answer in a tiny test. That does not prove the operation is atomic or safe under another schedule. Protect the whole update or avoid shared mutation.

Recall without looking

  1. Which memory is shared by threads?
  2. Name two costs to consider before using processes.
Check these answers
  1. Threads in one process share its address space, though each thread has its own execution state.
  2. Startup and memory costs, plus communication or data-serialisation costs.

8.2 The Global Interpreter Lock

The GIL affects CPU parallelism in ordinary CPython and is often overgeneralised as a rule about every Python implementation and build.

In plain words: In the usual GIL-enabled CPython build, a thread must hold the Global Interpreter Lock to operate on Python objects. The interpreter therefore serialises Python bytecode execution between threads, although I/O and some native code can release the lock.

Three cases to separateDefault CPython build → one thread at a time executes Python bytecodeFree-threaded CPython build → threads may execute Python code in parallelNative extension releases GIL → native work may overlap, subject to that library’s rulesFree-threading was added as an optional build in Python 3.13 and is officially supported as of Python 3.14; it is not the default. The Python 3.14 documentation notes that an extension not marked compatible may re-enable the GIL. Use explicit synchronisation for shared invariants.

For CPU-bound Python code in the default build, multiple threads generally do not give multicore speed-up. Consider processes, a native library that releases the GIL, or a tested free-threaded deployment when its dependency stack supports it. For I/O-bound work, threads may improve throughput because a waiting thread does not monopolise useful CPU time.

Trap: The GIL does not make application-level operations or compound updates safe. It also says nothing universal about PyPy, Jython, or a free-threaded CPython build.

Near miss: A package imports in free-threaded CPython, so you assume the GIL is disabled. A C extension may have enabled it during import; check the running interpreter’s state and the package’s support.

Recall without looking

  1. Is free-threaded CPython the default in Python 3.14?
  2. Why can a native numerical routine still use several cores?
Check these answers
  1. No. It is an officially supported optional build; the ordinary build remains GIL-enabled.
  2. It may release the GIL while native code runs; actual parallelism depends on the library and build.

8.3 Asyncio and cooperative concurrency

Asyncio gives many I/O tasks a lightweight event-loop scheduler, but its scheduling points and shared-state rules must be understood.

In plain words: An event loop runs one task until it finishes or suspends at an awaitable operation. That task gives up its turn while waiting, so another ready task can progress; a long CPU calculation blocks the loop.

Task lifecyclecreate_task(coro) → scheduled taskawait pending operation → task suspends; loop runs other workawaited operation completes → task resumesThis describes cooperative scheduling within an event loop. It is concurrency, not CPU parallelism by itself.

Use asyncio.gather or task groups to coordinate related coroutines, and use asynchronous I/O APIs instead of blocking calls. Move unavoidable blocking work to a suitable executor. Cancellation and exceptions are part of task control flow; ensure resources close in finally blocks or asynchronous context managers.

A task is not pre-empted in the middle of ordinary straight-line Python code by another task on the same loop, but any awaited operation can expose partially updated state. If an invariant spans an await, another task may observe or change it. A shared async resource can be protected with asyncio.Lock; see the asyncio synchronisation documentation.

Trap: “No locks are needed in async code.” Locks may be needed when a task releases control while an invariant is temporarily broken.

Near miss: Read a balance, await a network request, then write a new balance. A second task can make an update during the wait; make the critical operation atomic at the application level or hold an appropriate lock.

Recall without looking

  1. What does awaiting a pending future do to the current task?
  2. When can async shared state need a lock?
Check these answers
  1. It suspends that task and lets the event loop run other ready tasks or I/O.
  2. When an invariant spans a suspension point and another task could observe or change the shared state.

8.4 Concurrency models in other languages

Comparing models helps separate the idea of concurrent tasks from a language’s specific scheduler, memory model, and safety guarantees.

In plain words: Languages make different choices about who schedules tasks, how tasks communicate, and when the compiler checks shared-memory rules. A familiar word such as “thread” does not guarantee identical behaviour across runtimes.

Go combines goroutines with channels and a runtime scheduler; it also supports shared memory and synchronisation. Rust provides OS threads and async runtimes, while its ownership and Send/Sync rules constrain safe sharing. Java provides platform threads, virtual threads, executors and locks. GHC Haskell offers lightweight threads and synchronisation tools such as STM and MVars.

ModelUseful questionImportant limit
Go goroutines and channelsCan tasks communicate by messages?Channels do not remove every shared-state design choice.
Rust threads or async runtimeWhat data may safely cross threads?Runtime and ownership choices still matter.
Java platform/virtual threadsCan blocking-style code scale across many tasks?Shared mutable state still requires coordination.
Haskell threads, STM or MVarsCan concurrent updates be coordinated transactionally?Runtime and abstraction overhead remain trade-offs.

Trap: “This language has no GIL, so races are impossible.” A runtime lock is only one possible source of coordination; it does not establish the correctness of every application invariant.

Near miss: A channel passes a pointer to shared mutable data. The message was sent safely, but the data may still be concurrently mutated unless ownership or synchronisation rules prevent it.

Recall without looking

  1. What are two questions to ask when comparing language concurrency models?
  2. Does message passing guarantee that referenced data cannot be changed elsewhere?
Check these answers
  1. Who schedules tasks, how state is shared or communicated, and what safety rules constrain mutation.
  2. No. A message may carry a reference; ownership and mutation rules still matter.

8.5 Use cases and concurrency pitfalls

The right model follows the bottleneck and the state boundary; the wrong one can add complexity without useful overlap or speed.

In plain words: Ask whether the program spends time calculating, waiting, or coordinating. Then ask whether tasks must share live objects. This narrows the choice before you consider a framework or a pool.

Workload routingMany independent I/O waits → threads or asyncio, according to the APIsCPU-heavy Python in default CPython → processes or parallel native codeShared mutation → define ownership, locking, or message passingThese are starting points, not performance guarantees. Measure the real workload.

Common failures include data races, deadlocks caused by inconsistent lock order, starvation, hidden non-thread-safe library state, and overhead from excessive task or process creation. Minimise shared mutable state, use queues or higher-level pools where they clarify ownership, and measure end-to-end time including transfer and startup.

Trap: A faster microbenchmark for one function does not prove the full pipeline is faster after copying, queueing and coordination.

Near miss: Two locks appear harmless when acquired one at a time. If one path takes A then B and another takes B then A, both tasks can wait forever. Establish one global acquisition order or reduce the locks.

Recall without looking

  1. What makes a deadlock possible with two locks?
  2. What should a benchmark include when work crosses process boundaries?
Check these answers
  1. Tasks can hold one lock while waiting for another held by the other task, forming a cycle.
  2. Startup and data-transfer/serialisation time as well as the calculation.

9.1 Introspection

Introspection lets code adapt to objects and supports tools such as debuggers, frameworks and command-line help.

In plain words: A running program can ask an object what type it has and what names or call signature it exposes. This is introspection: examining live objects and their metadata.

Use type for an exact runtime type, isinstance when subclasses count, getattr for a named attribute, and dir for a discoverable-name list. The inspect module can read signatures and docstrings. Its getsource helper works only when source can be retrieved; built-ins, interactive definitions, or generated code may not have accessible source.

Duck typing asks whether an object supports the operation the caller needs, rather than requiring one concrete class. Prefer the actual operation or a small protocol when possible; testing attribute presence alone may not prove that the attribute behaves as expected.

QuestionTool
Exact runtime class?type(obj)
Instance of class or subclass?isinstance(obj, C)
Call signature or documentation?inspect.signature / inspect.getdoc

Trap: dir(obj) is not a list of only public methods or a stable API contract.

Near miss: A plugin has a run attribute, but it is a string rather than a callable. Check or invoke the capability with a clear error policy instead of assuming its type from its name.

Recall without looking

  1. When is isinstance more appropriate than comparing type directly?
  2. Why may inspect.getsource raise an error?
Check these answers
  1. When instances of subclasses should also be accepted.
  2. The object’s source may not be available, such as for built-ins or dynamically created code.

9.2 Decorators

Decorators give a function or class a transformation at definition time, with a compact syntax for wrapping cross-cutting behaviour.

In plain words: A decorator receives a function or class and returns the object that will be bound to its name. A wrapper can run code before and after the original call.

Decorator equivalence@decorate on def f … ≡ f = decorate(f)Read it as: “the name f is bound to the result of calling decorate with the original function f.” For stacked decorators, the one nearest the def is applied first; the outer decorator receives its result.

A general function wrapper accepts *args and **kwargs, calls the wrapped function with both, and returns the result. Use functools.wraps so metadata such as the name, docstring and wrapped-function link is preserved. A parameterised decorator is a factory that returns a decorator. A class instance can also decorate if it is callable.

Decorators are useful for caching, logging, validation and registration. Their order can change behaviour: a cache outside an authorisation wrapper may create a very different policy from the reverse.

Trap: A decorator that forgets to return the wrapped result changes the function’s return value to None.

Near miss: A wrapper logs positional arguments but rejects keyword arguments. Accept and forward both argument collections unless the wrapper intentionally defines a narrower signature.

Recall without looking

  1. What name is bound after a decorator is applied?
  2. Why use functools.wraps?
Check these answers
  1. The name is bound to the object returned by the decorator, often a wrapper.
  2. It copies useful metadata from the wrapped function and records the wrapped object.

9.3 Metaclasses

Metaclasses can enforce or construct rules across a family of classes, though simpler class-level hooks often communicate intent better.

In plain words: An instance is created from a class; a class object is itself created by a metaclass. Python’s usual metaclass is type.

A custom metaclass can inspect or alter the class name, bases and namespace while the class is created. The three-argument form type(name, bases, namespace) creates a class dynamically. Metaclasses can register subclasses or validate declarations, but they can make behaviour hard to find.

Before writing a metaclass, consider a class decorator, __init_subclass__, a factory, or composition. These often handle one-class or subclass-registration needs with less hidden machinery. Multiple metaclasses can conflict when base classes require incompatible metaclass hierarchies.

MechanismOperates on
Class decoratorOne completed class object
__init_subclass__Subclass creation through a base hook
MetaclassClass-object creation rules

Trap: A metaclass does not run as a substitute for each instance’s ordinary method calls; its main hook is class creation and class-level behaviour.

Near miss: A base class only needs to register each subclass. A full metaclass may work, but __init_subclass__ is often a simpler hook for that job.

Recall without looking

  1. What information is passed to a metaclass’s class-creation hook?
  2. Name a simpler alternative for subclass registration.
Check these answers
  1. The class name, base classes and namespace, along with the metaclass itself.
  2. A base class’s __init_subclass__ hook is often enough.

9.4 Dynamic code and abstract syntax trees

Runtime code generation is powerful but crosses a trust boundary and can make behaviour harder to inspect and test.

In plain words: eval evaluates an expression, exec executes statements, and compile turns source or an AST into a code object. An abstract syntax tree represents code by its grammatical structure.

Use a data format, mapping or ordinary function dispatch when those solve the problem. If generating code is justified, construct and validate it deliberately. An AST avoids some fragile string-building errors, but compiling and executing an AST still runs code; it is not a sandbox for untrusted input.

Never evaluate arbitrary user text as Python. Restricting the globals dictionary does not turn Python execution into a secure sandbox. If the goal is a small expression language, define and parse that language explicitly, with permitted operations and bounded resources.

Dynamic-code pipelinesource or AST → compile → code object → eval or execEvery step still belongs to an execution path. Parsing structure does not grant safety.

Trap: “It is an AST, so it is safe.” Structure helps transformation; it does not remove execution authority.

Near miss: A calculator accepts eval(user_text) because the interface asks for arithmetic only. The input remains arbitrary Python code. Parse a deliberately limited grammar instead.

Recall without looking

  1. What is the main difference between eval and exec?
  2. Why is an AST not a sandbox?
Check these answers
  1. eval evaluates an expression and returns its value; exec executes statements.
  2. It can still be compiled and executed, so the generated program retains its authority to perform operations.

9.5 Instrumentation and monkey patching

Instrumentation observes or changes behaviour at runtime; patching can help in tests but creates order-dependent global state.

In plain words: Instrumentation adds observation such as timing or tracing. A monkey patch replaces an existing attribute or callable while the program is running.

A patch can be useful to isolate a dependency in a test or to work around a temporary defect. Patch the name where the code under test looks it up, scope the replacement to a context manager or fixture, and restore it afterwards. A method patched on a class should be a function with the expected binding behaviour.

Long-lived patches can depend on import order, collide with other patches, bypass invariants, and surprise code that holds an earlier reference. Prefer a supported extension point, dependency injection, or a wrapper you own when the behaviour is part of normal product design.

Code under testPatch target
from transport import sendclient.send
import transport, then transport.sendtransport.send

Trap: Patching library.fetch does not affect code that already imported and bound fetch into another module.

Near miss: A test patches a global function and forgets to restore it. Later tests pass alone but fail in a suite depending on execution order. Use a scoped patch and verify cleanup.

Recall without looking

  1. Where should a dependency usually be patched in a unit test?
  2. Why keep a monkey patch scoped?
Check these answers
  1. At the name lookup site used by the code under test.
  2. To restore global state and prevent import-order or test-order effects.

9.6 Debugging and testing

Reliable fixes begin with a repeatable failure and end with a test that would have caught it.

In plain words: A test states what must hold; a debugger or trace helps show where execution diverges. Start with the smallest observation that distinguishes the expected result from the actual one.

In pytest, fixtures provide reusable setup and cleanup; parametrisation runs a case over explicit inputs. Property-based tools such as Hypothesis generate examples from a stated invariant and shrink failures. Mocks isolate external effects, while autospec can catch calls that do not match the real interface. Avoid mocks when they merely copy the implementation instead of checking a useful boundary.

For async code, inspect task names and stacks, enable event-loop debug mode when appropriate, and make task exceptions visible. For threads, collect stack traces and reason about lock ownership and ordering. faulthandler can dump Python tracebacks. Coverage reports which code ran; it does not prove that assertions were strong.

Use CI to run tests on supported Python versions and dependency configurations. The lecture’s Python 3.8 and 3.9 matrix is obsolete: both releases are end-of-life. Choose a current supported range for the project and pin that policy in its tooling, using the Python version status.

EvidenceWhat it can showWhat it cannot show by itself
Failing minimal testReproduces a behaviourIts root cause
Coverage reportWhich code executedWhether assertions are strong
Task/thread stackWhere work is paused or blockedWhether the program’s intended invariant is correct

Trap: High line coverage means every important behaviour has been tested.

Near miss: A mock returns the expected value for any call, including invalid arguments. Use a spec or a small integration test to verify the real boundary.

Recall without looking

  1. What extra information does property-based testing provide beyond one example?
  2. What does coverage fail to establish?
Check these answers
  1. It explores many generated inputs and can shrink a failure to a smaller counterexample.
  2. It does not show that the tests asserted the right behaviour or exercised meaningful cases.

Model map

This chapter has no core numerical formula. Use the following decision rules as a compact model map; check them against the workload and runtime you actually deploy.

NeedFirst choice to evaluateCheck before relying on it
Overlap blocking I/OThreads or asyncioWhether the APIs block and whether state is shared
CPU parallelism in default CPythonProcesses or native codeTransfer costs and library behaviour
CPU parallelism with CPython threadsFree-threaded buildBuild mode, extension compatibility, explicit locks
Shared state across an awaitRedesign invariant or use asyncio synchronisationEvery suspension point and cancellation path
Change function behaviourDecoratorSignature, metadata, return value and wrapper order
Generate or execute codeOrdinary dispatch or constrained parser firstTrust boundary and execution authority

Check every answer: state the runtime/build, workload, shared state and measurement boundary. “Concurrent”, “parallel” and “thread-safe” do not mean the same thing.

Derive it cold

  1. Route a workload: classify CPU versus I/O, shared versus isolated data, then compare setup and communication costs. §8.1–8.5
  2. Trace a coroutine schedule around every await and mark which invariants remain true at each suspension. §8.3
  3. Expand a decorated definition into the equivalent rebinding, then trace nested wrapper order and return value. §9.2
  4. Trace class creation from name, bases and namespace through the metaclass hook. §9.3
  5. Turn a flaky report into a minimal reproduction, a likely cause, a regression test and a measured fix. §9.6

Explain it

  1. Why can threads improve an I/O-bound program even when its default CPython build has a GIL?
  2. When can asyncio tasks race over shared data?
  3. Why might adding processes make a CPU task slower?
  4. When is a decorator clearer than a metaclass?
  5. Why does building an AST not make execution of untrusted code safe?
  6. When can a mock make a test less useful?
Show model answers
  1. A thread waiting for I/O does not need to hold the interpreter while another thread can progress. The gain is overlapping waits, not parallel Python-bytecode execution. §8.1–8.2
  2. Tasks can interleave at suspension points. If shared state is temporarily inconsistent across an await, another task can observe or change it. §8.3
  3. Worker startup and moving data to and from processes can cost more than the saved calculation time. §8.1, §8.5
  4. A decorator is usually clearer when one function or class needs a wrapper at definition time. A metaclass is broader and controls class creation. §9.2–9.3
  5. An AST represents structure, but it can still compile into executable operations with the authority of the process. §9.4
  6. A mock is less useful when it accepts invalid calls or mirrors implementation details instead of testing a meaningful boundary. §9.6

Mixed practice

24 mixed problems. Constants: use the stated runtime and do not assume a particular scheduler interleaving unless the prompt says so.

  1. Module client used from transport import send. Your test patches transport.send. Why may the client still call the original?
  2. A program downloads 200 small files and spends most time waiting. Name one suitable concurrency approach and one constraint to check.
  3. Name one technique that ensures a monkey patch is restored after a test, including on failure.
  4. On ordinary GIL-enabled CPython, will two CPU-bound Python threads normally execute Python bytecode simultaneously on separate cores?
  5. A suite has 100% line coverage but no assertion on an important result. What can you conclude?
  6. A process pool receives a 2 GB object to perform a 1 ms calculation. What cost may dominate?
  7. Which tool can help dump Python stack traces when a program hangs or crashes: faulthandler or functools?
  8. Two tasks both execute value += 1 with no await in a single-threaded event loop. Does another task normally interleave within that statement sequence?
  9. Why is a test with an unrestricted mock return less informative than an autospecced mock?
  10. Python 3.14 is installed. Is that alone enough to conclude that the GIL is disabled?
  11. As of the current Python release status, may a new project treat Python 3.8 and 3.9 as maintained test targets?
  12. One task reads inventory, awaits a remote price, then writes inventory minus one. Name the risk and a mitigation direction.
  13. A function has a flaky failure under load. Give a short evidence-first debugging sequence.
  14. Match: a Go program launches many lightweight tasks and passes messages through channels. Name the model components.
  15. A worker holds lock A and waits for B; another holds B and waits for A. What has occurred?
  16. What is the likely outcome of inspect.getsource(len)?
  17. A decorator wrapper calls f(*args, **kwargs) but does not return the call result. What does a successful wrapper call return by default?
  18. What does pytest parametrisation add when testing clamp at negative, boundary and positive inputs?
  19. For @outer above @inner on f, write the resulting binding.
  20. A class hierarchy needs to register each subclass. Name a standard hook to try before a metaclass.
  21. What does type("Worker", (Base,), namespace) return?
  22. Hypothesis reports a long failing list and then reduces it. What is the reduced value for?
  23. A calculator passes user text to eval after removing spaces. Is this a safe allowlist?
  24. An AST has been checked to contain a lambda. Does compiling it guarantee no dangerous behaviour?
Show the answers
  1. client already bound its own name send; patch the name where the code under test looks it up. §9.5
  2. Threads or asyncio can overlap waits. Check whether the client API is blocking or asynchronous and whether rate limits/shared state need coordination. §8.1, §8.3, §8.5
  3. Use a scoped patch context/decorator or a fixture finaliser so cleanup runs when the scope exits. §9.5
  4. No. The GIL serialises bytecode execution between threads in that build. §8.2
  5. Only that those lines executed; coverage does not establish that expected behaviour was checked. §9.6
  6. Serialising, copying or transferring the input and starting/scheduling work can dominate the calculation. §8.1, §8.5
  7. faulthandler can dump tracebacks. §9.6
  8. No pre-emptive task switch happens between ordinary statements in one task; tasks switch when the running task suspends. This does not generalise to threads or free-threaded execution. §8.3
  9. An unrestricted mock may accept invalid method calls and signatures; autospec constrains the mock to the real interface. §9.6
  10. No. Free-threaded execution uses an optional build; the ordinary build is still GIL-enabled, and extensions may enable the GIL. §8.2
  11. No. Both are end-of-life; choose versions that remain supported and match the project’s users. §9.6
  12. Another task may change inventory during the await. Keep the invariant within a protected operation, use an async lock, or redesign around a single owner/queue. §8.3
  13. Capture the failure and runtime conditions, reproduce it, reduce the case, inspect the relevant task and thread state, form one hypothesis, then add a regression test and rerun it. §8.5, §9.6
  14. Goroutines are scheduled by the Go runtime; channels communicate values. Shared memory still requires safe coordination. §8.4
  15. A deadlock cycle. Enforce a consistent acquisition order or restructure ownership. §8.5
  16. It raises TypeError for a built-in function because Python source is not available in the expected form. §9.1
  17. None, because the wrapper itself has no return statement carrying the result. §9.2
  18. It runs the same test logic against explicit input/expected-output cases. §9.6
  19. f = outer(inner(f)); the decorator nearest the definition is applied first. §9.2
  20. __init_subclass__ on a base class is often a simpler registration hook. §9.3
  21. A newly created class named Worker with the listed base and namespace. §9.3
  22. It is a smaller counterexample that still violates the property, making the defect easier to understand. §9.6
  23. No. Whitespace removal does not restrict Python syntax or execution authority. Parse a small explicit expression grammar. §9.4
  24. No. The accepted AST and its names or operations still need a safe, bounded execution model; an AST is not a sandbox. §9.4

Exam-style problems

1 · Schedule, sharing, and GIL · 20 minutes

A service downloads records, normalises each record in Python, and accumulates a shared count. The ordinary CPython deployment is GIL-enabled.

  1. Classify each stage as primarily I/O-bound or CPU-bound and choose a starting model. (3 marks)
  2. Explain whether two CPU-heavy Python threads should be expected to use two cores for bytecode. Give one alternative. (3 marks)
  3. Identify the shared-state risk in the count and propose a coordination or ownership design. (3 marks)
  4. The team considers free-threaded CPython. Name two deployment checks before adopting it. (3 marks)
Show worked answer
  1. Downloads are I/O-bound; normalisation is CPU-bound. Threads or asyncio can overlap downloads; the CPU stage may use a process pool or native implementation if measurement justifies transfer costs. §8.1, §8.3, §8.5
  2. No. In the default build, the GIL serialises Python bytecode between threads. Processes or suitable native code are alternatives. §8.2
  3. Concurrent increments may lose updates. Use a lock around the whole update, one aggregator that owns the count, or return local counts and combine them. §8.1, §8.5
  4. Check that the interpreter is actually a free-threaded build with the GIL disabled, and that C extensions/dependencies support free-threading without re-enabling the GIL. Also measure workload performance and test shared-state correctness. §8.2

2 · Inspect, transform, and test · 20 minutes

A framework discovers plugin classes and wraps each plugin’s run method with timing. A test fails intermittently after monkey-patching a transport dependency.

  1. Describe what a decorator does to the method binding and one metadata measure. (3 marks)
  2. Give a simpler alternative to a metaclass if the only requirement is subclass registration. (2 marks)
  3. Explain why generated AST code is not automatically safe for untrusted plugin input. (3 marks)
  4. Give a test/debugging sequence for the intermittent failure, including where to patch. (4 marks)
Show worked answer
  1. The decorator receives the function and returns a wrapper that is bound to run. Use functools.wraps to preserve metadata and identify the original callable. §9.2
  2. Use a base class’s __init_subclass__ or a class decorator if it suffices. §9.3
  3. An AST can still compile into executable code. Structural representation does not constrain what the resulting program can access or do. §9.4
  4. Reproduce and minimise the failure; inspect task and thread stacks and order of patch setup; patch the transport name where the plugin looks it up; scope cleanup; add a deterministic regression test. §8.5, §9.5–9.6

Slips in the notes

These points were checked against the rendered lecture slides and current official Python documentation.

  • Slide 3, GIL and parallelism. The statement that only separate processes achieve parallelism is too broad for CPython: optional free-threaded builds allow Python threads to run in parallel. The later slides mention this direction, but do not qualify the broad claim. The Python 3.14 documentation describes the optional build. §8.2
  • Slide 14, async locking. The claim that locks are unnecessary because tasks only switch at awaits is too broad. An invariant can be interrupted across an await; the asyncio documentation provides a task lock for shared resources. §8.3
  • Slides 53–54, Python version matrix. The sample CI/tox targets Python 3.8 and 3.9; both are end-of-life according to the Python version status. Select maintained versions for a live project matrix. §9.6

Self-check

Tick a skill only in a later session, at least one day after studying, when you can demonstrate it without notes.

Personal study guide based on “89a.pdf” (59 slides, 15 November 2025), written in my own words; no lecture pages or figures are reproduced. Not an official FAU publication; check course details against the current notes. Made by Thanate Amornjiraporn (Focus).