Python Capsule API — Explain Like I'm 5
The Sealed Envelope
Imagine two of your friends want to share a secret toy, but they live far apart. They can’t hand it to each other directly. So they put the toy in a sealed envelope and drop it in a shared mailbox.
Your friend picks it up, opens the envelope, and gets the toy. The mailbox (Python) carried the envelope, but it never peeked inside — it has no idea what’s in there.
That’s what a Python Capsule does. It’s a sealed envelope that carries a C pointer through the Python world. Python holds onto it, passes it around, but never opens it. Only C code that knows the secret label can open the envelope and use what’s inside.
Why This Exists
Sometimes two C extensions need to share something between them — like a special function or a chunk of data. They can’t do this through regular Python objects because Python doesn’t understand C pointers.
Capsules solve this by wrapping the pointer in a Python object. Python can store it, import it, and pass it around, while the C code on both sides knows exactly how to unwrap it.
A Real Example
NumPy uses Capsules to share its internal C functions with other extensions. When SciPy needs to call a fast NumPy function directly (without going through Python), NumPy puts a pointer to that function in a Capsule. SciPy imports the Capsule and extracts the pointer.
The result: SciPy calls NumPy’s C code at full speed, without Python getting in the way.
One Thing to Remember
A Python Capsule is a sealed container for a C pointer that travels safely through Python-land. Python carries it without understanding it, and only C code with the right name can open it.
See Also
- Python Boost Python Bindings Boost.Python lets C++ code talk to Python using clever C++ tricks, like teaching two people to understand each other through a shared phrasebook.
- Python Buffer Protocol The buffer protocol lets Python objects share raw memory without copying, like passing a notebook around the table instead of photocopying every page.
- Python Cffi Bindings CFFI lets Python talk to fast C libraries, like giving your app a translator that speaks both languages at the same table.
- Python Extension Modules Api The C Extension API is how Python lets you plug in hand-built C code, like adding a turbo engine under your Python program's hood.
- Python Maturin Build Tool Maturin packages Rust code into Python libraries you can pip install, like a gift-wrapping service for super-fast code.