<class 'builtin_function_or_method'>
<class 'builtin_function_or_method'>
<class 'function'>
2026-07-14
What this course will not teach you:
What this course will teach you:
In the course we will assume:
std::vector, std::string, std::function[](int x){return x*x;}This deck of slides is available online:
https://cambridge-iccs.github.io/python-bindings-summer-school-2026/
GitHub repository:
https://github.com/Cambridge-ICCS/python-bindings-summer-school-2026
To run the exercises we will use a GitHub Codespace. You can access it by clicking the link below:
https://codespaces.new/Cambridge-ICCS/python-bindings-summer-school-2026
If you close a tab, the link above will create a new Codespace. To resume latest work, you can use the link below:
https://codespaces.new/Cambridge-ICCS/python-bindings-summer-school-2026?quickstart=1
Warning
GitHub may include a warning saying:
“Codespace usage for this repository is paid for by <you>”
Don’t worry, you will not be charged. There is a free quota each month.
Slides link
In the repository: https://github.com/Cambridge-ICCS/python-bindings-summer-school-2026
List or open a codespace:

Task
Open a codespace now.
Don’t forget to delete when you are done:

System requirements:
python3 --versioncmake --versiongcc --versionpython3-dev on Ubuntu)Running locally is the danger zone 🛦🛦🛦
Please prefer the codespace for the course. Try on your machine during miniproject or at home.
Bindings make Python a ‘glue’ between different optimised high-performance libraries.
I will be stealing an analogy (might be a spoiler for the dinner! ;-) )
“Programming is like swimming. You can only learn by doing it.”
In the cloned repository navigate to exercise_1 folder.
We can build the package using the following commands:
Task
pip.punge_ex module.helpLet us go through it now together!
Try to look inside the source in src/plunge_ex.cpp and see the C++ source of the Python methods.
Don’t worry if they seem arcane. We will go through the details in a moment ;-)
<class 'builtin_function_or_method'>
<class 'builtin_function_or_method'>
<class 'function'>
PyObject pointers.Py prefixed functionsPython allows external code to plug-into the ‘built-in’ methods mechanism.
This is what ‘Python extension modules’ do!
This is accomplished by shared libraries: *.so on Linux, *.dll on Windows, or *.dylib on MacOS.

Shared libraries allow programs to load extra code at runtime. They select them ‘like’ a file and can extract functions to run
‘Python extension module’ is a shared library with extra properties:
<module_name>.cpython-<python_version><extra_metadata>.so
my_mod.cpython-311-x86_64-linux-gnu.soPyInit_<module_name>
import <module_name>*.so in sys.path (like any module file)Python 3 stable ABI
Extensions that limit themselves to a Limited Python C API are compatible with all Python 3 versions and don’t need cpython-<version> suffix (<name>.abi3.so instead).
Look into exercise_1/src/plunge_ex.cpp:
At the start of the file:
These must be first lines (before any other include of C/C++ headers).
At the end of the file:
We define the hook by which Python will load the module.
Caution
The name of the function must be PyInit_<module_name>, where <module_name> must match the name of the .so file! Try to break it! Rename the .so (e.g. with cp) and try to load!
Note
PyMODINIT_FUNC is a quality-of-life macro. Makes sure it works correctly with C/C++ on different systems.
Ok sure… but what goes into the PyModule_Create function?
PyModuleDef structUnsurprisingly, a Python structure that collects the information about the module.
// Doc: https://docs.python.org/3/c-api/module.html#c.PyModuleDef
static struct PyModuleDef plunge_ex_module_def = {
PyModuleDef_HEAD_INIT, // Magic macro that handles Python internals
"plunge_ex", // Module name
"\"Jump into the water of Python extensions!\" module", // Module docstring
-1, // Set to -1 for 'single pass initialisation'
plunge_ex_methods, // Provide list of methods module contains
NULL, // Non null only in multi-pass initialisation
NULL, // Function slots for deconstruction
NULL,
NULL
};Note
Just try to ignore the extra fields for now! They are out of the scope for the simple example.
Note
Single pass initialisation is what we use. It may not work well with the new free-threaded Python! It is still a default for many Python binding tools.
The methods in a module are specified by a C-style array of PyMethodDef structures.
Caution
The list is null terminated with the special ‘sentinel’ value {NULL, NULL, 0, NULL}.
Required function signature depends on the calling convention.
For METH_VARARGS function must accept two pointers to PyObject (Python object descriptors).
self is the module objectargs is a tuple of arguments passed from Python.We can extract data from args via PyArg_ParseTuple function, format string describes contents, e.g.:
"s":single string; "ss": two strings; "f": a floatCurrently the plunge_ex module contains two functions: splash and raise_exception.
To compile and run, in the exercise_1 directory run:
Task
Create a new function multiple_splash that takes two arguments name and count and prints ‘name made a splash!’ count times.
If the count is negative, it should raise a ValueError exception.
Getting integer out of a Tuple
See ‘Numbers’ section in parsing arguments in the Python doc.
More things to try (time allowing)
count or non-bool to raise_exception? Is the behaviour what you expected?The purpose of this section was to give you a peek behind the curtain.

Photo by Kristina Lenberg

Can be found on github
pybind11 uses C++ metaprogramming to allow describing bindings in a way reminiscent of Python syntax.
class, defPy*** functions and details (you bind pure C++ directly).C++ raw string literals
Writing well formatted Python docstrings in C++ can be a bit of a pain. Raw string literal helps a lot.
It allows to write multi-line strings that will render ‘as written’:
int square(int x) { return x * x; }
PYBIND11_MODULE(module_name, m) {
m.doc() = R"pbdoc(
Docstring goes here!
)pbdoc";
// We can add attributes and functions with a natural syntax
m.attr("__version__") = "0.1.0";
// We take an address of function when we bind them
// py:arg allows us to specify the name for arguments
m.def("square", &square, "Function docstring", py::arg("x"));
// Not necessary but we can delegate to functions to bind classes/sets of functions
// Keeps things clean
bind_particular_class(m);
}PyInit_module_name function.doc method to access docstringattr method to access attributesdef method to define functionspybind11 has a modular header system. To enable extra features you need to include extra headers:
pybind11 aims to be as seamless as possible:
There be dragons: mutable references
In Python:
Not quite the result we expected…
You will find a familiar splash and raise_exception functions inside the exercise_2/src/plunge_pyb.cpp file!
The extension module name is plunge_pyb, to compile and run:
Task
Once again create a new function multiple_splash that takes two arguments name and count and prints ‘name made a splash!’ count times.
If the count is negative, it should raise a ValueError exception.
Exception translation
pybind11 converts thrown C++ exceptions to different Python exceptions. Consult the translation table to know what to raise on C++ side.
Please ignore ‘Task 2’ parts for now ツ
We bind in C++ with:
In Python we can use like:
Spot the issue with this example?
We could have written std::vector<int>! We take a reference of a temporary copy.
This problem is deadly for scientific workflows (╯°□°)╯︵ ┻━┻
Python and pybind11 have solutions to this problem ┬─┬ノ( º _ ºノ)
py::array type that is compatible with numpy.ndarray
Eigen C++ librarypy::array_tSubset of functionality needed for the exercises:
#include <pybind11/numpy.h> // <- Enables Numpy interoperability
...
py::array_t<double> my_array = py::array_t<double>(10); // 1D array of 10 doubles
my_array.mutable_at(0) = 3.14; // Mutable access to an element
auto b = my_array.at(0); // Immutable access to an element
...
// You can accept it as an argument to a function
void my_function(py::array_t<double> arr) {
arr.size() // You can query the size
...
}Note
This should be all you need for the exercise later on.
pybind11 supports std::function and accepts Python functions as arguments!
Once again we have two functions written for reference: print_numpy_array and apply_on_range that demonstrate the use of py::array_t and callback via std::function.
Compile and run:
Task
Implement a new function interpolate that takes a py::array_t<double> and a std::function<double(double)> as arguments and returns a new py::array_t<double> with the function applied to each element of the input array.
Return either std::vector<double> or py::array_t<double> from the function. Choose your favourite (or do both!).
Example signature:
Not covered:
Takeaway message
Binding C++ to Python is possible and ultimately not that hard.
Since Fortran is a language with less ‘industrial’ interest support is limited:
f2py interface generator, part of numpy
And many more that I have missed…
pybind11 in C++
Python Bindings | ICCS Summer School 2026