Master the fundamental concepts of cpython internals through this focused micro-challenge.
CPython exposes a C API for writing native modules that import like Python code. Extensions accelerate hot paths and wrap system libraries. NumPy, optional C helpers in networking libraries, and countless stdlib modules all build on this same scaffolding.
A minimal extension exports a PyMethodDef table and a module init function:
cLoading…
Key pieces you will wire up:
PyModule_CreateBuild with python3-config --cflags --ldflags or setuptools. Reference counting rules apply: Py_INCREF/Py_DECREF around objects you create or borrow.
For example, a C add that parses two PyLong arguments and returns a new PyLong runs at native speed when called from Python.
Reference counts on borrowed versus new references trip up most first extensions. Document whether each helper returns a borrowed reference from a tuple slot or a new reference you must decref.
This exercise asks you to scaffold a C extension module from scratch. You will implement method definitions, argument parsing with PyArg_ParseTuple, and module initialization so Python can import your native code.
You will use the same mental model here when reading production interpreter source later in the track. Sketch one concrete input on paper, predict the outcome, then confirm with code. That discipline catches logic errors early and makes debugging far faster when you extend the implementation in follow-on tasks.
Write a C program showing a C extension module structure.
Requirements:
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github