Master the fundamental concepts of cpython internals through this focused micro-challenge.
Builtins like len, abs, and sum are C functions registered on the builtins module. They parse PyObject* arguments, do native work, and return new Python objects without ever entering the bytecode interpreter loop.
A builtin uses the same C API as extensions but lives in Python/bltinmodule.c or similar:
cLoading…
Every builtin you study follows the same checklist:
PyArg_ParseTuple with a format string like "i" or "O"PyLong_Check, PySequence_Check, or similar type guardsPyLong_FromLong) or NULL with PyErr_SetStringType checks, error handling, and correct refcounting are mandatory. Fast paths often bypass generic PyNumber dispatch when the argument type is known.
For example, abs(-42) calls C code that reads the PyLong digits directly instead of re-entering the interpreter loop.
Fast paths should validate types once, then read internal struct fields directly. Falling back to abstract PyNumber APIs preserves semantics but costs the speed that motivated writing C in the first place.
This exercise asks you to implement a Python builtin in C following CPython conventions. You will write argument parsing, type validation, and return value construction for a function callable from the REPL.
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 how to implement a built-in function.
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