Brainbotox · Lessons · Exams

Advanced Python: Internals, Concurrency, Metaclasses, Performance

by lazizanie · Programming · Python · English

Advanced Python for senior developers: CPython internals and the GIL, threading, multiprocessing and asyncio, descriptors and metaclasses, profiling, advanced typing and the MRO.

Study this lesson with its quizzes on Brainbotox →

CPython internals: bytecode, reference counting and the GIL

CPython, the standard Python implementation, compiles source code to bytecode, runs it on a stack-based virtual machine, frees memory mainly by reference counting, and protects its internals with the Global Interpreter Lock (GIL).

From source to execution

  1. The source is parsed into an abstract syntax tree.
  2. The tree is compiled to bytecode, cached as .pyc files in __pycache__.
  3. The interpreter loop executes the bytecode instructions one by one.
import dis
dis.dis(lambda x: x + 1)      # shows LOAD_FAST, BINARY_OP, RETURN_VALUE ...

Recent versions specialise hot bytecode at run time (the adaptive interpreter introduced in 3.11), and an experimental JIT exists.

Memory management

MechanismHandlesWhen
Reference countingMost objectsImmediately, when the count reaches zero
Cyclic garbage collector (gc)Groups of objects that reference each otherPeriodically, by generations
import sys
a = []
sys.getrefcount(a)     # 2: the name a, plus the temporary argument
Because of reference counting, an object is usually destroyed the moment its last reference disappears. This is deterministic in CPython, but not guaranteed by the language: always close resources with with.

CPython caches small integers (from -5 to 256) and interns some strings, which is why is gives misleading results on numbers and strings. Compare values with ==.

The GIL

The GIL is a mutex that allows only one thread at a time to execute Python bytecode in a process. It keeps reference counts and C extensions safe without fine-grained locks.
WorkloadEffect of the GIL on threads
CPU-bound pure PythonNo parallel speed-up: threads take turns
I/O-bound (network, disk)Threads help: the GIL is released while waiting
NumPy and other C extensionsOften release the GIL during heavy computation
The GIL does not make your code thread-safe. counter += 1 is several bytecode instructions, and a thread switch can occur between them.

Since Python 3.13 an optional free-threaded build without the GIL is available, and separate interpreters in one process can each have their own GIL.

Check yourself

  1. What does CPython compile Python source code into?
  2. What is CPython's primary memory management mechanism?
  3. What does the GIL prevent?
  4. For which workload do threads still help despite the GIL?
  5. Because of the GIL, counter += 1 from several threads is always safe.
  6. Which module shows the bytecode of a function?

Take the quiz on Brainbotox

Python concurrency: threading, multiprocessing and asyncio

Python offers three concurrency models: threads for blocking I/O, processes for CPU-bound work, and asyncio for very many I/O tasks on a single thread. Choosing the right one depends on what the code waits for.

ModelParallel CPUBest forCost
threadingNo (GIL)Blocking I/O with existing librariesShared state needs locks
multiprocessingYesCPU-bound workProcess start-up; data is pickled between processes
asyncioNoThousands of concurrent connectionsNeeds async libraries throughout

Executors

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
with ThreadPoolExecutor(max_workers=20) as pool:
    pages = list(pool.map(download, urls))        # I/O-bound
with ProcessPoolExecutor() as pool:
    results = list(pool.map(crunch, chunks))      # CPU-bound

Thread safety

lock = threading.Lock()
def increment():
    global counter
    with lock:
        counter += 1

Use queue.Queue to pass work between threads safely.

asyncio

import asyncio
async def get_page(session, url):
    async with session.get(url) as resp:
        return await resp.text()
async def main():
    async with aiohttp.ClientSession() as session:
        pages = await asyncio.gather(*(get_page(session, u) for u in urls))
asyncio.run(main())
An event loop runs coroutines on one thread. A coroutine runs until it reaches an await, where it hands control back to the loop. This is cooperative multitasking: switches happen only at await points.
  • Calling an async def function returns a coroutine object. Nothing runs until it is awaited or scheduled.
  • asyncio.gather and asyncio.TaskGroup run coroutines concurrently. asyncio.create_task schedules one in the background.
  • Awaiting coroutines one after the other is sequential, not concurrent.
A blocking call inside a coroutine, such as time.sleep(5), a synchronous HTTP client or heavy computation, freezes the whole event loop. Use await asyncio.sleep(), an async library, or move the call off the loop with await asyncio.to_thread(func).

Choosing

  1. CPU-bound: processes, or a library that releases the GIL.
  2. I/O-bound with a few dozen tasks and synchronous libraries: threads.
  3. I/O-bound with thousands of connections: asyncio.

Check yourself

  1. Which model gives true parallelism for CPU-bound pure Python code?
  2. On how many threads does an asyncio event loop run coroutines?
  3. What does calling an async def function return?
  4. What happens if a coroutine calls time.sleep(5)?
  5. Which call runs several coroutines concurrently and collects their results?
  6. What is a cost of multiprocessing compared with threading?

Take the quiz on Brainbotox

Python metaprogramming: descriptors, metaclasses and __slots__

Metaprogramming is code that customises how classes and attribute access behave. In Python its building blocks are descriptors, __getattr__, class decorators, __init_subclass__ and metaclasses.

Descriptors

class Positive:
    def __set_name__(self, owner, name):
        self.name = '_' + name
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(obj, self.name)
    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError('must be positive')
        setattr(obj, self.name, value)
class Product:
    price = Positive()
    stock = Positive()
A descriptor is an object stored in a class whose __get__, __set__ or __delete__ methods take over attribute access. property, classmethod, staticmethod and plain functions (which become bound methods) are all descriptors.

Attribute lookup order for obj.x

  1. A data descriptor (has __set__) found on the class or its bases.
  2. The instance's own __dict__.
  3. A non-data descriptor or plain class attribute.
  4. __getattr__, if defined, as a last resort.

__getattr__ runs only when normal lookup fails. __getattribute__ runs on every access and is rarely the right tool.

Classes are objects

type(42)            # <class 'int'>
type(int)           # <class 'type'>
Point = type('Point', (object,), {'x': 0})     # a class built at run time

Metaclasses

class Registry(type):
    classes = {}
    def __new__(mcls, name, bases, namespace):
        cls = super().__new__(mcls, name, bases, namespace)
        mcls.classes[name] = cls
        return cls
class Plugin(metaclass=Registry): ...

A metaclass is the class of a class: it controls how classes are created. ORMs and abc.ABC use them.

Most needs are met by simpler tools. Try a class decorator or __init_subclass__ first:
class Plugin:
    registry = []
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.registry.append(cls)

__new__ and __slots__

__new__ creates the instance and __init__ initialises it. Override __new__ for singletons or to subclass immutable types such as tuple.

class Point:
    __slots__ = ('x', 'y')

__slots__ replaces the per-instance __dict__ with fixed storage: much less memory for millions of objects and slightly faster access, but no attributes beyond those listed.

Check yourself

  1. What makes an object a descriptor?
  2. When is __getattr__ called?
  3. What is the type of a class such as int?
  4. What does a metaclass control?
  5. Which simpler hook often replaces a metaclass for registering subclasses?
  6. What is the effect of __slots__?

Take the quiz on Brainbotox

Python performance: profiling, complexity and faster code

Making Python fast is a three-step method: measure to find the hot spot, fix the algorithm and data structures, then push the remaining heavy loops into compiled code.

Measure first

ToolAnswers
cProfile with pstatsWhich functions take the time, and how often they are called
timeitHow long a small snippet takes, averaged over many runs
tracemallocWhere memory is allocated
py-spy, ScaleneSampling profilers for running programs
python -m cProfile -s cumulative app.py
python -m timeit "','.join(str(n) for n in range(100))"

Complexity of built-in operations

Operationlistdict / setdeque
Membership x in cO(n)O(1) averageO(n)
Append at the endO(1) amortisedO(1)
Insert or pop at the frontO(n)O(1)
Lookup by key or indexO(1)O(1) averageO(n) in the middle
The most common fix: replace if x in big_list inside a loop by a set. An O(n squared) loop becomes O(n).

Idioms that matter

  • Build strings with ''.join(parts), not += in a loop.
  • Use built-ins implemented in C: sum, min, max, sorted, any, all.
  • Comprehensions are faster than a loop with append.
  • Local variable access is faster than global or attribute access: bind a method to a local name in a very hot loop.
  • Generators keep memory flat for large data.
  • Cache pure, expensive functions with functools.lru_cache.
  • __slots__ for millions of small objects.

Leaving pure Python

ApproachUse
NumPy and pandas vectorisationArray maths in C, with no Python-level loop
NumbaJIT-compiles numeric functions
Cython, C or Rust extensionsCompile the hot path
PyPyAn alternative interpreter with a JIT
multiprocessingUse all cores for CPU-bound work
import numpy as np
a = np.arange(1_000_000)
total = (a * a).sum()          # far faster than a Python loop
Do not optimise without a profile. Guesses about the bottleneck are usually wrong, and the real cost is often I/O, a database query or an accidental quadratic loop.

Check yourself

  1. Which tool shows which functions consume the most time?
  2. What is the average complexity of x in s for a set?
  3. Why is list.pop(0) slow on a large list?
  4. What is the efficient way to build a string from many pieces?
  5. Why is NumPy much faster than a Python loop for array maths?
  6. What should come before any optimisation?

Take the quiz on Brainbotox

Advanced Python typing: Protocol, generics and ParamSpec

Python's type system is gradual and static: annotations are checked by tools such as mypy and pyright, not by the interpreter, and advanced features let you describe duck typing, generic containers and decorators precisely.

Protocol: structural typing

from typing import Protocol
class SupportsClose(Protocol):
    def close(self) -> None: ...
def shutdown(resource: SupportsClose) -> None:
    resource.close()
A Protocol is satisfied by any class that has the required methods, with no inheritance. It is duck typing that a type checker can verify. An abstract base class, by contrast, needs explicit subclassing (nominal typing).

Generics

# Python 3.12+ syntax
def first[T](items: list[T]) -> T:
    return items[0]
class Stack[T]:
    def __init__(self) -> None:
        self._items: list[T] = []
    def push(self, item: T) -> None:
        self._items.append(item)
    def pop(self) -> T:
        return self._items.pop()
# older syntax
from typing import TypeVar
T = TypeVar('T')

A type variable links input and output types: first([1, 2]) is known to return an int.

Precise types

ConstructDescribes
Literal['r', 'w']Only those exact values
TypedDictA dict with fixed keys and typed values, such as a JSON payload
FinalA name that must not be reassigned
SelfThe type of the current class, for fluent methods
NewType('UserId', int)A distinct type for the checker, with no run-time cost
@overloadSeveral signatures for one function

Typing decorators with ParamSpec

from typing import Callable, ParamSpec, TypeVar
P = ParamSpec('P')
R = TypeVar('R')
def logged(func: Callable[P, R]) -> Callable[P, R]:
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        print(func.__name__)
        return func(*args, **kwargs)
    return wrapper

ParamSpec preserves the wrapped function's parameter list, so calls to the decorated function are still checked.

Any, object and narrowing

  • Any disables checking in both directions. object accepts any value but allows almost no operation on it without narrowing.
  • Checkers narrow types after isinstance, is None tests and match.

Run time

Annotations are stored in __annotations__ and never enforced by Python. Libraries such as pydantic read them to validate data at run time, which is what you want at system boundaries (API input, config files).
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from heavy_module import BigClass     # imported only for the checker

Check yourself

  1. How does a class satisfy a typing.Protocol?
  2. What does a type variable T express in def first[T](items: list[T]) -> T?
  3. What does ParamSpec capture?
  4. What is the difference between Any and object as annotations?
  5. Which construct describes a dict with fixed keys and typed values?
  6. Which kind of tool actually enforces type annotations at run time?

Take the quiz on Brainbotox

Python MRO, super, advanced generators, weak references and imports

The method resolution order (MRO) is the linear order in which Python searches classes for an attribute, and super() follows that order, not simply "the parent class". This chapter also covers other advanced corners of the runtime.

MRO and cooperative super

class A:
    def hello(self): print('A')
class B(A):
    def hello(self): print('B'); super().hello()
class C(A):
    def hello(self): print('C'); super().hello()
class D(B, C):
    def hello(self): print('D'); super().hello()
D().hello()          # D B C A
D.__mro__            # (D, B, C, A, object)
The MRO is computed by C3 linearisation: a class comes before its parents, parents keep their declared order, and each class appears once. In B, super() means "the next class after B in the MRO of the instance", which is C here, not A.

For this to work, every class in the hierarchy must call super() and accept **kwargs for arguments it does not use. Mixins are small classes designed to be combined this way.

Advanced generators

def averager():
    total = count = 0
    average = None
    while True:
        value = yield average      # receives what send() passes in
        total += value; count += 1
        average = total / count
g = averager(); next(g)
g.send(10)      # 10.0
g.send(20)      # 15.0
def flatten(nested):
    for part in nested:
        yield from part            # delegate to a sub-generator

Weak references

import weakref
cache = weakref.WeakValueDictionary()
cache['big'] = obj        # does not keep obj alive

A weak reference does not increase the reference count. Use it for caches and observer lists so that they do not cause memory leaks.

The import system

  • An imported module is executed once and stored in sys.modules. Later imports return the cached object.
  • A circular import fails when one module needs a name the other has not defined yet. Restructure, or import inside the function.
  • importlib.import_module(name) imports by string, for plugins.
  • Monkey patching replaces attributes of modules or classes at run time. It is useful in tests and risky elsewhere.

More of the data model

FeatureMechanism
Reversed operators3 + obj calls obj.__radd__(3) when int cannot handle it
Callable objects__call__
Function overloading by typefunctools.singledispatch
Pre-filled argumentsfunctools.partial
pickle can execute arbitrary code while loading. Never unpickle data from an untrusted source; use JSON or another data-only format.

Check yourself

  1. What does super() refer to inside a method?
  2. With class D(B, C) where B and C both inherit from A, what is D's MRO?
  3. What does yield from iterable do in a generator?
  4. What does generator.send(value) do?
  5. What is true of a weak reference?
  6. Why is loading pickle data from an untrusted source dangerous?

Take the quiz on Brainbotox