Advanced Python: Internals, Concurrency, Metaclasses, Performance
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
- The source is parsed into an abstract syntax tree.
- The tree is compiled to bytecode, cached as
.pycfiles in__pycache__. - 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
| Mechanism | Handles | When |
|---|---|---|
| Reference counting | Most objects | Immediately, when the count reaches zero |
Cyclic garbage collector (gc) | Groups of objects that reference each other | Periodically, by generations |
import sys a = [] sys.getrefcount(a) # 2: the name a, plus the temporary argument
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
| Workload | Effect of the GIL on threads |
|---|---|
| CPU-bound pure Python | No parallel speed-up: threads take turns |
| I/O-bound (network, disk) | Threads help: the GIL is released while waiting |
| NumPy and other C extensions | Often release the GIL during heavy computation |
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
- What does CPython compile Python source code into?
- What is CPython's primary memory management mechanism?
- What does the GIL prevent?
- For which workload do threads still help despite the GIL?
- Because of the GIL, counter += 1 from several threads is always safe.
- Which module shows the bytecode of a function?
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.
| Model | Parallel CPU | Best for | Cost |
|---|---|---|---|
threading | No (GIL) | Blocking I/O with existing libraries | Shared state needs locks |
multiprocessing | Yes | CPU-bound work | Process start-up; data is pickled between processes |
asyncio | No | Thousands of concurrent connections | Needs 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-boundThread safety
lock = threading.Lock()
def increment():
global counter
with lock:
counter += 1Use 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())await, where it hands control back to the loop. This is cooperative multitasking: switches happen only at await points.- Calling an
async deffunction returns a coroutine object. Nothing runs until it is awaited or scheduled. asyncio.gatherandasyncio.TaskGrouprun coroutines concurrently.asyncio.create_taskschedules one in the background.- Awaiting coroutines one after the other is sequential, not concurrent.
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
- CPU-bound: processes, or a library that releases the GIL.
- I/O-bound with a few dozen tasks and synchronous libraries: threads.
- I/O-bound with thousands of connections: asyncio.
Check yourself
- Which model gives true parallelism for CPU-bound pure Python code?
- On how many threads does an asyncio event loop run coroutines?
- What does calling an async def function return?
- What happens if a coroutine calls time.sleep(5)?
- Which call runs several coroutines concurrently and collects their results?
- What is a cost of multiprocessing compared with threading?
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()__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
- A data descriptor (has
__set__) found on the class or its bases. - The instance's own
__dict__. - A non-data descriptor or plain class attribute.
__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 timeMetaclasses
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.
__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
- What makes an object a descriptor?
- When is __getattr__ called?
- What is the type of a class such as int?
- What does a metaclass control?
- Which simpler hook often replaces a metaclass for registering subclasses?
- What is the effect of __slots__?
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
| Tool | Answers |
|---|---|
cProfile with pstats | Which functions take the time, and how often they are called |
timeit | How long a small snippet takes, averaged over many runs |
tracemalloc | Where memory is allocated |
| py-spy, Scalene | Sampling 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
| Operation | list | dict / set | deque |
|---|---|---|---|
Membership x in c | O(n) | O(1) average | O(n) |
| Append at the end | O(1) amortised | O(1) | |
| Insert or pop at the front | O(n) | O(1) | |
| Lookup by key or index | O(1) | O(1) average | O(n) in the middle |
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
| Approach | Use |
|---|---|
| NumPy and pandas vectorisation | Array maths in C, with no Python-level loop |
| Numba | JIT-compiles numeric functions |
| Cython, C or Rust extensions | Compile the hot path |
| PyPy | An alternative interpreter with a JIT |
| multiprocessing | Use 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
Check yourself
- Which tool shows which functions consume the most time?
- What is the average complexity of x in s for a set?
- Why is list.pop(0) slow on a large list?
- What is the efficient way to build a string from many pieces?
- Why is NumPy much faster than a Python loop for array maths?
- What should come before any optimisation?
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()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
| Construct | Describes |
|---|---|
Literal['r', 'w'] | Only those exact values |
TypedDict | A dict with fixed keys and typed values, such as a JSON payload |
Final | A name that must not be reassigned |
Self | The type of the current class, for fluent methods |
NewType('UserId', int) | A distinct type for the checker, with no run-time cost |
@overload | Several 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 wrapperParamSpec preserves the wrapped function's parameter list, so calls to the decorated function are still checked.
Any, object and narrowing
Anydisables checking in both directions.objectaccepts any value but allows almost no operation on it without narrowing.- Checkers narrow types after
isinstance,is Nonetests andmatch.
Run time
__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 checkerCheck yourself
- How does a class satisfy a typing.Protocol?
- What does a type variable T express in def first[T](items: list[T]) -> T?
- What does ParamSpec capture?
- What is the difference between Any and object as annotations?
- Which construct describes a dict with fixed keys and typed values?
- Which kind of tool actually enforces type annotations at run time?
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)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-generatorWeak 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
| Feature | Mechanism |
|---|---|
| Reversed operators | 3 + obj calls obj.__radd__(3) when int cannot handle it |
| Callable objects | __call__ |
| Function overloading by type | functools.singledispatch |
| Pre-filled arguments | functools.partial |
pickle can execute arbitrary code while loading. Never unpickle data from an untrusted source; use JSON or another data-only format.Check yourself
- What does super() refer to inside a method?
- With class D(B, C) where B and C both inherit from A, what is D's MRO?
- What does yield from iterable do in a generator?
- What does generator.send(value) do?
- What is true of a weak reference?
- Why is loading pickle data from an untrusted source dangerous?