Table of Contents


Generators

A yield turns a function into a lazy iterable — values are produced on demand, one at a time, and the function state is suspended between calls.

def number_generator(number_range: int):
    for i in range(number_range + 1):
        yield i
 
[x for x in number_generator(5)]

Output:

[0, 1, 2, 3, 4, 5]

Generators vs coroutines

yield also enables two-way communication (value = yield x), which is why generators are the historical root of Python coroutines. In modern code, prefer async/await for cooperative concurrency and keep generators for streaming data.

Creating iterators with iter()

Any class that implements __iter__ (and optionally __getitem__) can be used with for, zip, sorted, list comprehensions — the whole iteration protocol.

class StatsList3:
    """List that keeps running sums for O(1) statistics."""
 
    def __init__(self):
        self._list = list()
        self.sum0 = 0  # len(self), sometimes called "N"
        self.sum1 = 0  # sum(self)
        self.sum2 = 0  # sum(x**2 for x in self)
 
    def append(self, value):
        self._list.append(value)
        self.sum0 += 1
        self.sum1 += value
        self.sum2 += value * value
 
    def __getitem__(self, index):
        return self._list[index]
 
    @property
    def mean(self):
        return self.sum1 / self.sum0
 
    def __iter__(self):
        return iter(self._list)
sl = StatsList3()
for data in 2, 4, 4, 4, 5, 5, 7, 9:
    sl.append(data)
sl.mean

Output:

5.0
sl[0]  # via __getitem__

Output:

2

Why keep sum0, sum1, sum2?

Recomputing sum(self) / len(self) on every access is ; maintaining running sums makes mean (and later variance, sum2) per access. The cost moves to append — a classic space/time trade-off.

Coroutines

Coroutines are subroutines that offer non-pre-emptive multitasking through multiple entry points: two functions can communicate while running, suspending and resuming without blocking.

import asyncio
import time
 
async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

Sequential vs. concurrent vs. structured

Version 1 — sequential await: total time is the sum of the delays (~3 s).

async def main():
    print(f"started at {time.strftime('%X')}")
 
    await say_after(1, 'hello')
    await say_after(2, 'world')
 
    print(f"finished at {time.strftime('%X')}")
 
await main()

Output:

started at 10:23:01
hello
world
finished at 10:23:04

Version 2 — concurrent tasks: create_task schedules both coroutines immediately; total time is the maximum delay (~2 s).

async def main():
    task1 = asyncio.create_task(say_after(1, 'hello'))
    task2 = asyncio.create_task(say_after(2, 'world'))
    print(f"started at {time.strftime('%X')}")
 
    # Wait until both tasks are completed (should take
    # around 2 seconds)
    await task1
    await task2
 
    print(f"finished at {time.strftime('%X')}")
 
await main()

Output:

started at 10:23:04
hello
world
finished at 10:23:06

Version 3 — structured concurrency (Python 3.11+): the TaskGroup context manager awaits all tasks implicitly on exit, and cancels every sibling task if one raises — far safer than manual await.

async def main():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(say_after(1, 'hello'))
        tg.create_task(say_after(2, 'world'))
        print(f"started at {time.strftime('%X')}")
 
    # The await is implicit when the context manager exits.
 
    print(f"finished at {time.strftime('%X')}")
 
await main()

Output:

started at 10:23:06
hello
world
finished at 10:23:08

Bare await is a fire-and-forget trap

Calling say_after(1, 'hello') without await does nothing useful — it merely creates a coroutine object. Un-awaited coroutines are a common source of silent bugs; TaskGroup makes the error surfaces explicit.

Example — websockets

Client

%%writefile websocket_client.py
import asyncio
from websockets import connect
 
async def hello(uri):
    async with connect(uri) as websocket:
        await websocket.send("Hello world!")
        result = await websocket.recv()
        print(result)
 
asyncio.run(hello("ws://localhost:8765"))
Overwriting websocket_client.py

Server

%%writefile websocket_server.py
import asyncio
from websockets import serve
 
 
async def echo(websocket):
    async for message in websocket:
        await websocket.send('Echo: ' + message)
 
 
async def main():
    async with serve(echo, "localhost", 8765):
        try:
            async with asyncio.timeout(5):
                await asyncio.Future()
        except TimeoutError:
            print('TimeOut')
 
# await main()        # jupyter
asyncio.run(main())   # script
Overwriting websocket_server.py

Run in two terminals (the server must be running first):

python websocket_server.py &
python websocket_client.py

Output (client):

Echo: Hello world!

Inspect the event loop with pyinstrument:

pyinstrument websocket_server.py

Why async for sockets?

While waiting for network I/O, the event loop runs other tasks. One single-threaded server process can hold thousands of concurrent connections — something threads only achieve at much higher memory cost.

Multi-threading

CPU-bound work in threads does not scale in CPython: the GIL (Global Interpreter Lock) lets only one thread execute Python bytecode at a time. Threads remain useful for I/O-bound tasks.

%%writefile threading_example.py
import threading
import math
 
def func_a():
    print('start factorial')
    for _ in range(10):
        math.factorial(1_000_000)
 
 
if __name__ == '__main__':
    for i in range(10):
        t = threading.Thread(target=func_a)
        t.start()
Overwriting threading_example.py

Exercise idea — Singleton under threads

A classic follow-up: add a thread-safe Singleton metaclass (with threading.Lock in __call__) and a shared Logger, then verify that all 10 threads observe the same instance. Check the linked note PY56-python-garbage-collectors — its Metaclass section shows how to build one.

Multiprocessing

Processes sidestep the GIL — each Process has its own interpreter and memory. Ideal for CPU-bound work, at the cost of serialization overhead between processes.

# %%writefile multiprocessing.py
import multiprocessing
import math
 
def func_a():
    print('start factorial')
    for _ in range(10_000):
        math.factorial(10_000)
 
 
if __name__ == '__main__':
    for i in range(3):
        t = multiprocessing.Process(target=func_a)
        t.start()

Output:

start factorial
start factorial
start factorial

Threads vs processes

threadingmultiprocessing
GILsharedone per process
Best forI/O-boundCPU-bound
Memorysharedcopied (expensive to share)
Startup costtiny~ms + fork/spawn
Communicationlocks/queuespickling, Manager, pipes

Pool of workers

pool.map_async dispatches without blocking; the results are consumed later.

import time
import multiprocessing
 
def busy_wait(n):
    while n > 0:
        n -= 1
 
n = 100_000_000
items = [n for _ in range(8)]
 
with multiprocessing.Pool() as pool:
    results = []
    start = time.time()
    print('Start processing...')
 
    for _ in range(5):
        results.append(pool.map_async(busy_wait, items))
 
    print('Still processing %.5f' % (time.time() - start))
 
    for result in results:
        result.wait()
 
    print('Result done %.5f' % (time.time() - start))
    print('Done processing: %.5f' % (time.time() - start))

Output:

Start processing...
Still processing 0.00038
Result done 24.67868
Done processing: 24.67877

Reading the output

Still processing returns in microseconds — the work is only queued. The real cost appears at wait(). Run nproc on your machine: busy_wait is CPU-bound, so scaling beyond the core count gains nothing.

Sharing data

Multiprocessing isolates memory, so sharing state requires explicit machinery. Manager provides proxy objects that are synchronized across processes (over a socket, internally).

import multiprocessing
 
manager = multiprocessing.Manager()
namespace = manager.Namespace()
namespace.spam = 123
namespace.eggs = 456

Example — shared namespace between two processes

import time
import multiprocessing
 
manager = multiprocessing.Manager()
namespace = manager.Namespace()
 
def func_a():
    print('Start factorial:A')
    namespace.a = time.time()
    for _ in range(1_000):
        math.factorial(10_000)
    print('End factorial')
 
def func_b():
    print('Start factorial:B')
    namespace.b = time.time()
    for _ in range(1_000):
        math.factorial(10_000)
    print('End factorial:')
 
a = multiprocessing.Process(target=func_a)
b = multiprocessing.Process(target=func_b)
a.start()
b.start()
 
a.join()
b.join()
print(namespace)

Output:

Start factorial:A
Start factorial:B
End factorial:
End factorial
Namespace(a=1717716396.3518615, b=1717716396.3545907)

Manager is a bottleneck, not a silver bullet

Every attribute access on namespace is a round-trip to the manager process. Fine for checkpoints like the timestamps above; disastrous for tight loops. For high-throughput sharing, prefer multiprocessing.Queue or shared_memory.

Python 3.15 Free-Threading Lab

  • Python 3.13 introduced the free-threaded build as experimental.
  • Under PEP 779, 3.14 made free-threaded Python “officially supported but still optional”.
  • PEP 803 (accepted for 3.15) adds a stable ABI for free-threaded Python (abi3t), so extension authors can ship one wheel for both builds.
  • Phase III, making free-threading the only build, is still undecided.

Goal

Show with measurements that the free-threaded build (python3.15t) runs CPU-bound threads in parallel, while the default build does not.

Key fact

The standard Python 3.15 is not GIL-free. Free-threading is an opt-in, separate build (3.15t). It is officially supported (PEP 779) but not the default.


1. Setup

Install both builds (using uv)

uv python install 3.15      # default build (GIL)
uv python install 3.15t     # free-threaded build
uv python list | grep 3.15

Alternatives: python.org installers (select “free-threaded” in the custom install), pyenv install 3.15t, or conda create -n ft python-freethreading.

Create a lab folder

mkdir gil-lab && cd gil-lab

2. Exercise 1: Is the GIL on?

check_gil.py

import sys
import sysconfig
 
print("Version          :", sys.version)
print("Built free-thread:", bool(sysconfig.get_config_var("Py_GIL_DISABLED")))
print("GIL enabled now  :", sys._is_gil_enabled())

Run:

uv run --python 3.15  check_gil.py
uv run --python 3.15t check_gil.py

Expected

InterpreterBuilt free-threadGIL enabled now
3.15FalseTrue
3.15tTrueFalse

Runtime override

On 3.15t you can re-enable the GIL:
PYTHON_GIL=1 uv run --python 3.15t check_gil.py or python -X gil=1 ...
A C extension that is not marked free-thread-safe can also make Python re-enable the GIL at import time (with a warning).

  • Ran on 3.15 and saw the GIL enabled
  • Ran on 3.15t and saw the GIL disabled

3. Exercise 2: CPU-bound benchmark

bench.py

import sys
import time
from concurrent.futures import ThreadPoolExecutor
 
N = 5_000_000          # work per task
TASKS = 12             # number of tasks (set to your core count)
 
 
def burn(n: int) -> int:
    """Pure-Python CPU-bound work."""
    total = 0
    for i in range(n):
        total += i * i % 7
    return total
 
 
def run_serial() -> float:
    start = time.perf_counter()
    for _ in range(TASKS):
        burn(N)
    return time.perf_counter() - start
 
 
def run_threads() -> float:
    start = time.perf_counter()
    with ThreadPoolExecutor(max_workers=TASKS) as pool:
        list(pool.map(burn, [N] * TASKS))
    return time.perf_counter() - start
 
 
if __name__ == "__main__":
    gil = sys._is_gil_enabled()
    serial = run_serial()
    threaded = run_threads()
    print(f"GIL enabled : {gil}")
    print(f"Serial      : {serial:6.2f} s")
    print(f"{TASKS} threads   : {threaded:6.2f} s")
    print(f"Speedup     : {serial / threaded:5.2f}x")

Run all three configurations:

uv run --python 3.15  bench.py
uv run --python 3.15t bench.py
PYTHON_GIL=1 uv run --python 3.15t bench.py

Results table (fill in)

BuildGILSerial (s)Threads (s)Speedup
3.15on2.57s3.57s0.67x
3.15toff2.80s0.51s5.43x

What you should see

  • 3.15 (GIL): speedup around 1.0x or lower. Threads take turns, so there is no parallelism.
  • 3.15t (no GIL): speedup approaching the number of physical cores, up to TASKS.
  • Serial time on 3.15t may be slightly slower than on 3.15. That is the single-thread overhead of free-threading.

Reflection

  • Why is speedup below TASKS even without the GIL? (cores, memory bandwidth, turbo boost, other apps)
  • What happens if you set TASKS higher than your core count?

4. Exercise 3: Race conditions are back

Without the GIL, “accidentally safe” code can break.

race.py

import sys
import threading
 
counter = 0
ITER = 1_000_000
THREADS = 4
 
 
def unsafe():
    global counter
    for _ in range(ITER):
        counter += 1          # read-modify-write, NOT atomic
 
 
def run(worker) -> int:
    global counter
    counter = 0
    ts = [threading.Thread(target=worker) for _ in range(THREADS)]
    for t in ts: t.start()
    for t in ts: t.join()
    return counter
 
 
lock = threading.Lock()
safe_counter = 0
 
def safe():
    global safe_counter
    for _ in range(ITER):
        with lock:
            safe_counter += 1
 
 
if __name__ == "__main__":
    expected = ITER * THREADS
    print("GIL enabled:", sys._is_gil_enabled())
    print("Expected   :", expected)
    print("Unsafe     :", run(unsafe))
 
    ts = [threading.Thread(target=safe) for _ in range(THREADS)]
    for t in ts: t.start()
    for t in ts: t.join()
    print("With Lock  :", safe_counter)
uv run --python 3.15  race.py
uv run --python 3.15t race.py

Expected

On 3.15t the Unsafe total is usually less than expected (lost updates). The version with a Lock always gives the exact number. On the GIL build you may get the right number by luck, but you should not rely on it.

  • Reproduced lost updates on 3.15t
  • Fixed with threading.Lock
  • Tried threading.Lock vs. one counter per thread, then summing (lock-free pattern)

5. Exercise 4 (stretch): Compare with multiprocessing

Rewrite run_threads using ProcessPoolExecutor and compare on the 3.15 build.

ApproachTime (s)MemoryNotes
Threads, GIL
Processes, GIL
Threads, no GIL

Questions:

  • Which uses the least memory?
  • Which has the highest start-up cost?
  • When are processes still the better choice? (isolation, crash safety, not-yet-compatible C extensions)

6. Cheat sheet

TaskCommand / API
Check if the build is free-threadedsysconfig.get_config_var("Py_GIL_DISABLED")
Check if the GIL is active right nowsys._is_gil_enabled()
Force GIL on or offPYTHON_GIL=1 / PYTHON_GIL=0 or -X gil=1 / -X gil=0
Run the free-threaded interpreterpython3.15t
uv installuv python install 3.15t

7. Takeaways

  • Python 3.15 default build: GIL on.
  • Python 3.15t: GIL off. Pure-Python threads scale across cores.
  • Free-threading is supported but opt-in. Making it the default is still undecided.
  • Expect slight single-thread overhead and a need for explicit locking.
  • Check that your dependencies publish free-threaded wheels before relying on 3.15t. Otherwise Python may re-enable the GIL.

8. Further reading

  • PEP 703: Making the GIL optional
  • PEP 779: Criteria for supported free-threaded Python
  • PEP 803: Stable ABI for free-threaded Python (abi3t)
  • Python Free-Threading Guide (py-free-threading.github.io)