Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · Python · Chapter 16 / 16

Programming learning path

Memory model, performance, the GIL & metaprogramming

CPython memory management, profiling, free-threading and descriptors/metaclasses.

CPython's memory model: reference counting and the cyclic GC

Most objects are freed instantly by reference counting; a separate generational collector only handles cycles.

Every CPython object carries a reference count that increments on each new reference and decrements when a reference goes away; in the default GIL-enabled build, reaching zero frees the object immediately and deterministically, which is why most Python memory management feels instant and predictable there. Python 3.14's free-threaded build changes part of that picture: certain frequently-shared objects are made immortal and never freed via refcounting at all, and its deferred, per-thread reference counting means an object's memory is not always reclaimed the instant its count would logically reach zero — a trade for lower cross-thread synchronization cost. Either way, reference counting alone cannot free two or more objects that reference each other in a cycle, since neither's count ever naturally reaches zero, so a separate generational garbage collector (gc module) periodically scans for and breaks such cycles, organizing objects into three generations on the assumption that most objects die young and older survivors need less frequent scanning.

Key points

  • In the default GIL-enabled build, reference counting frees most objects immediately and deterministically
  • Reference counting alone cannot free objects in a reference cycle
  • The generational gc module periodically detects and breaks cycles; younger generations are scanned more often
  • Free-threaded 3.14 uses immortal objects and deferred per-thread refcounting, relaxing strict immediacy

Code

import gc, sys

class Node:
    def __init__(self):
        self.other = None

a, b = Node(), Node()
a.other, b.other = b, a   # a reference cycle
print(sys.getrefcount(a))
del a, b                  # neither reaches refcount 0 on its own
gc.collect()               # the cyclic collector frees them

A manual reference cycle that only the generational collector, not reference counting alone, can free.

Common pitfalls

  • Assuming del obj immediately frees memory whenever obj participates in a reference cycle
  • Defining __del__ on objects that end up in reference cycles used to prevent the cyclic collector from freeing them at all in older Python versions

Practice exercise

Call gc.disable() first, then create a small parent-child pair of objects that reference each other, attach a weakref to one of them, delete both external references, call gc.collect(), and confirm via the weakref that they are freed only once you call gc.collect() — then explain in one sentence why automatic collection could have freed them earlier if gc had been left enabled.

Profiling before optimizing

Measure first with cProfile; intuition about where a program is slow is frequently wrong.

python -m cProfile -s cumulative script.py instruments every function call in a run and reports call counts, per-call time, and cumulative time including callees — providing evidence instead of intuition, since the real bottleneck is often somewhere a developer would not have guessed. Once the real bottleneck is identified, the most reliable fixes are usually algorithmic: reducing the amount of work done per item, and replacing a manual loop with a built-in whose semantics genuinely match, like sum() (a real C-implemented builtin) or a list comprehension (compiled Python bytecode with some specialized instructions — faster than a hand-written append loop, but not literally the same thing as a C builtin). For genuinely hot numeric work, delegating to a vectorized library like NumPy usually beats any pure-Python loop. Older micro-tricks like binding a hot global or attribute to a local variable before a tight loop can still help in some cases, but modern specializing CPython (3.11+) already optimizes some of those patterns internally, so any such change should be benchmarked on the target Python version rather than applied as a blanket rule.

Key points

  • cProfile measures actual call counts and cumulative time per function before you optimize anything
  • Algorithmic fixes and well-matched built-ins are the most reliable wins; benchmark micro-tricks like local-binding on the target Python version
  • sum() is a genuine C builtin; a comprehension is compiled bytecode, not literally the same thing — vectorized libraries win for hot numeric work

Code

python -m cProfile -s cumulative slow_report.py

# after finding the real bottleneck:
# before:
# result = []
# for x in data:
#     result.append(transform(x))
# after:
# result = [transform(x) for x in data]

Profiling first to find the real bottleneck, then applying a comprehension instead of guessing at an optimization.

Common pitfalls

  • Optimizing the function you assume is slow, without profiling, frequently wastes effort on code that was never the bottleneck
  • Micro-optimizing a function that runs once at startup instead of one called a million times inside a loop yields no measurable benefit

Practice exercise

Profile a script of yours (or a deliberately slow one you write) with cProfile, identify the actual hottest function, and apply one targeted optimization, then re-profile to confirm it helped.

The GIL and the free-threaded build

Why the GIL exists, what it costs, and how the officially-supported free-threaded build in 3.14 changes the picture.

In the normal CPython build, the GIL is a single mutex that lets only one thread execute Python bytecode — more precisely, hold the interpreter lock while touching Python objects and C-API state — at a time. Protecting reference-count updates (covered in an earlier lesson) is one important reason it exists, but not the whole story: historically it has simplified thread-safety for much of the interpreter's other internal state too. PEP 703 proposed removing it via finer-grained internal locking, and PEP 779 defined the criteria under which that free-threaded build became officially supported starting in Python 3.14 — though it remains opt-in rather than default, because it currently costs some single-threaded performance and not every C extension is compatible with it yet. The exact command or installer for a free-threaded interpreter varies by platform rather than being one portable python3.14t; the reliable way to check whether the current interpreter is running free-threaded is python -VV, sys._is_gil_enabled(), or sysconfig.get_config_var("Py_GIL_DISABLED"). Whether multiprocessing, the free-threaded build, or InterpreterPoolExecutor fits a given CPU-bound workload best now depends on the specifics — data sharing, extension compatibility, overhead — not one blanket default.

Key points

  • The GIL protects reference-count updates and broader interpreter/C-API state — not only reference counting
  • PEP 703 proposed removal; PEP 779 made the free-threaded build officially supported in Python 3.14
  • Free-threading remains opt-in; check with python -VV or sys._is_gil_enabled() rather than assuming a fixed python3.14t command

Code

# Standard build: only one thread executes bytecode at a time
python script.py

# Checking whether the CURRENT interpreter is free-threaded (portable):
python -VV
python -c "import sys; print(sys._is_gil_enabled())"

# The actual free-threaded executable name/invocation varies by platform and installer.

Checking whether an interpreter is free-threaded portably, instead of assuming a fixed python3.14t launch command.

Common pitfalls

  • Assuming the free-threaded build is now the default — it remains opt-in as of Python 3.14
  • Switching to the free-threaded build without checking whether your C-extension dependencies support it can silently re-enable the GIL anyway

Practice exercise

Read Python's official free-threading documentation and write two or three sentences comparing when you would consider the free-threaded build, InterpreterPoolExecutor, and multiprocessing for a real CPU-bound workload.

Descriptors and metaclasses: how @property and ORMs work under the hood

The mechanisms behind @property, ORM model fields, and framework "magic" — used rarely, but worth understanding.

A descriptor is any object defining __get__ (and optionally __set__/__delete__) that is stored as a class attribute; when accessed through an instance, Python calls the descriptor's methods instead of returning it directly, which is literally the mechanism @property is built on. A metaclass is "the class of a class": just as a class defines how its instances behave, a metaclass (usually a subclass of type, used via class Foo(metaclass=MyMeta):) defines how classes themselves are constructed, letting a framework automatically register subclasses, validate class-level declarations, or inject behavior at class-creation time. Descriptors are the common mechanism behind properties and framework-managed attributes; a metaclass is one of several class-creation hooks a framework can reach for — class decorators and __init_subclass__ are others — and different ORMs and frameworks combine these mechanisms differently rather than all uniformly using both.

Key points

  • A descriptor (__get__/__set__ on a class attribute) is the mechanism @property is built on
  • A metaclass is "the class of a class", controlling how classes themselves are constructed
  • Descriptors are the common mechanism behind managed attributes; metaclasses are one of several class-creation hooks, alongside class decorators and __init_subclass__

Code

class PositiveNumber:
    def __set_name__(self, owner, name):
        self.name = f"_{name}"
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self  # accessed on the class itself, e.g. Account.balance
        return getattr(obj, self.name)
    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError("must be positive")
        setattr(obj, self.name, value)

class Account:
    balance = PositiveNumber()

a = Account()
a.balance = 10  # goes through PositiveNumber.__set__

A reusable descriptor enforcing validation across any class attribute it is assigned to — including safe access through the class itself, not just an instance — the same mechanism behind @property.

Common pitfalls

  • Reaching for a custom metaclass to solve a problem a simpler class decorator or __init_subclass__ hook would solve is usually overengineering
  • Descriptors are stored on the class, not the instance, so naive implementations without per-instance storage can accidentally share state across instances

Practice exercise

Write a reusable descriptor class ValidatedString(min_length) that can be attached to any class attribute and raises ValueError if an assigned string is shorter than min_length.

Source registry

7 chapter references
gc — Garbage collector interface

Generational garbage collection and cyclic-reference behavior

Python Software Foundation · Official reference
Source ↗
The Python Standard Library

Authoritative behavior for built-in types and standard library modules

Python Software Foundation · Official reference
Source ↗
dis — Disassembler for Python bytecode

Bytecode execution model used to reason about interpreter performance

Python Software Foundation · Official reference
Source ↗
PEP 703 — Making the Global Interpreter Lock Optional

The technical proposal behind the free-threaded CPython build

Python Software Foundation · Official specification
Source ↗
PEP 779 — Criteria for supported status for free-threaded Python

The criteria that made free-threaded Python officially supported starting with 3.14

Python Software Foundation · Official specification
Source ↗
Python support for free threading

The GIL, the free-threaded build and its compatibility trade-offs

Python Software Foundation · Official guide
Source ↗
Data model

Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols

Python Software Foundation · Official reference
Source ↗