man python-in-c/type-slots

lesson 7 of 33 · Objects

Operators through type slots

lib / Building a Python in C 15 mindraft

checked against: CPython 3.15.2, Apple clang 21.0.0

code: toothywalrus/minipy@lesson-07.1

In lesson 6 every value became an object with a type, but the evaluator still decided what + meant: it checked that both operands were ints and did the arithmetic itself. That does not scale. Every new type would mean another branch in the evaluator, for every operator. CPython does it the other way round: each type carries pointers to the functions that implement its operators, and the evaluator’s general path asks the types (its specialized instructions, below, are the exception). This lesson moves minipy to that design.

The code is minipy at tag lesson-07.1, which is lesson-07 with two caption fixes in the figure’s trace. The slot machinery is in src/object.c, the int and bool slots in the new src/intobject.c, and src/otrace.c draws the figure. make test runs 166 tests, among them the 43 programs in tests/run/, each also checked for objects left alive. Every terminal output below was recorded from a run of the command shown with it.

The example

$ ./minipy examples/slots.py; python3 - < examples/slots.py
False
2
1
examples/slots.py:4:7: error: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
False
2
1
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

The four lines of examples/slots.py are print(True & False), print(True + True), print(5 & True) and print(None + 1). minipy built from the lesson-06 tag prints 0 for the first line, because bool had no operators of its own then:

$ ./minipy examples/slots.py
0
2
1
examples/slots.py:4:7: error: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Now the two interpreters agree, and each line takes a different route through the type slots.

A table of functions

A type can now have a table of number slots, one function pointer per operator:

typedef struct {
    BinaryFunc nb_add;
    BinaryFunc nb_subtract;
    BinaryFunc nb_multiply;
    BinaryFunc nb_remainder;
    BinaryFunc nb_power;
    UnaryFunc nb_negative;
    UnaryFunc nb_positive;
    InquiryFunc nb_bool;
    UnaryFunc nb_invert;
    BinaryFunc nb_lshift;
    BinaryFunc nb_rshift;
    BinaryFunc nb_and;
    BinaryFunc nb_xor;
    BinaryFunc nb_or;
    BinaryFunc nb_floor_divide;
} NumberMethods;

The type points at its table, and has a slot for comparisons and a pointer to its base type:

struct TypeObject {
    Object base;                /* a type is an object */
    const char *name;
    TypeObject *base_type;      /* CPython's tp_base; NULL: no base */
    void (*dealloc)(Object *self);                  /* refcnt reached 0 */
    int (*repr)(Object *self, char *buf, size_t size);  /* like snprintf */
    NumberMethods *as_number;   /* NULL: no number slots at all */
    RichCmpFunc richcompare;
    bool ready;
};

CPython’s PyNumberMethods begins the same way (Include/cpython/object.h#L66-L84):

    binaryfunc nb_add;
    binaryfunc nb_subtract;
    binaryfunc nb_multiply;
    binaryfunc nb_remainder;
    binaryfunc nb_divmod;
    ternaryfunc nb_power;
    unaryfunc nb_negative;
    unaryfunc nb_positive;
    unaryfunc nb_absolute;
    inquiry nb_bool;
    unaryfunc nb_invert;
    binaryfunc nb_lshift;
    binaryfunc nb_rshift;
    binaryfunc nb_and;
    binaryfunc nb_xor;
    binaryfunc nb_or;
    unaryfunc nb_int;
    void *nb_reserved;  /* the slot formerly known as nb_long */
    unaryfunc nb_float;

It has 36 fields in all, one of them the unused nb_reserved, against minipy’s 15. Among the ones minipy leaves out are abs(), divmod(), the conversions, true division, matrix multiplication, and in-place versions of the binary operators for += and the like. nb_power takes three arguments in CPython because pow() takes an optional modulus. The type points at its table from a field in the middle of PyTypeObject (Include/cpython/object.h#L165):

    PyNumberMethods *tp_as_number;

and a type with no number behaviour leaves it NULL, as minipy’s type does. CPython’s type has a table, but with only nb_or in it, for unions such as int | None.

A slot that can say no

int’s nb_add is int_add(), the addition of lesson 5 moved into a function of two objects:

static Object *int_add(Object *v, Object *w)
{
    CHECK_BINOP(v, w);
    int64_t a = int_value(v), b = int_value(w);
    if ((b > 0 && a > INT64_MAX - b) || (b < 0 && a < INT64_MIN - b))
        return overflow();
    return int_new(a + b);
}

The first line is the new part. int_add() is reached whenever either operand is an int, so the other may be anything:

#define CHECK_BINOP(a, b) \
    if (!is_int(a) || !is_int(b)) return incref(NotImplemented)

NotImplemented is a static object, like None, that a slot returns to mean “not for these operands”. It is not an error: it passes the turn to the other operand’s type. CPython’s int methods start with a macro of the same name and job (Objects/longobject.c#L1843-L1847):

#define CHECK_BINOP(v,w)                                \
    do {                                                \
        if (!PyLong_Check(v) || !PyLong_Check(w))       \
            Py_RETURN_NOTIMPLEMENTED;                   \
    } while(0)

A slot that fails for real, as int_add() does on overflow, returns NULL and leaves a message with err_format(), standing in for CPython’s current exception. The evaluator takes the message with err_take() and reports it at the node being evaluated.

Finding the slot

The evaluator now turns an operator into an offset into the table and hands the rest over:

static Object *binop(Eval *ev, Pos pos, Operator op, bool inplace, Object *a, Object *b)
{
    char name[4];
    snprintf(name, sizeof name, "%s%s", operator_symbol(op), inplace ? "=" : "");
    Object *r = binary_op(a, b, operator_slot(op), name);
    return r ? r : raise(ev, pos);
}

operator_slot(Add) is offsetof(NumberMethods, nb_add), through the NB_SLOT macro. With an offset, one function can read any slot:

static BinaryFunc number_slot(const TypeObject *t, size_t slot)
{
    if (!t->as_number)
        return NULL;
    return *(const BinaryFunc *)((const char *)t->as_number + slot);
}

and binary_op1() decides the order. The op_step() calls only report to the figure’s trace:

static Object *binary_op1(Object *v, Object *w, size_t slot)
{
    BinaryFunc slotv = number_slot(v->type, slot);
    op_step((OpStep){ .kind = OP_SLOT_V, .v = v, .w = w, .slot = slot, .fn = slotv,
                      .type = v->type });
    BinaryFunc slotw = NULL;
    if (w->type != v->type) {
        slotw = number_slot(w->type, slot);
        if (slotw == slotv)
            slotw = NULL;
    }
    op_step((OpStep){ .kind = OP_SLOT_W, .v = v, .w = w, .slot = slot, .fn = slotw,
                      .type = w->type });
    if (slotv) {
        Object *x = slotv(v, w);
        op_step((OpStep){ .kind = OP_CALLED, .v = v, .w = w, .slot = slot, .fn = slotv,
                          .type = v->type, .result = x });
        if (x != NotImplemented)
            return x;
        decref(x);
    }
    if (slotw) {
        Object *x = slotw(v, w);
        op_step((OpStep){ .kind = OP_CALLED, .v = v, .w = w, .slot = slot, .fn = slotw,
                          .type = w->type, .result = x });
        if (x != NotImplemented)
            return x;
        decref(x);
    }
    return incref(NotImplemented);
}

The left operand’s function goes first, then the right one’s, and the first answer that is not NotImplemented wins. If the two types share the function, it is called once. binary_op() turns a final NotImplemented into the TypeError, with CPython’s wording.

CPython reads its slots by offset the same way (Objects/abstract.c#L923-L925):

#define NB_SLOT(x) offsetof(PyNumberMethods, x)
#define NB_BINOP(nb_methods, slot) \
        (*(binaryfunc*)(& ((char*)nb_methods)[slot]))

Its binary_op1(), listed in the sources, is minipy’s with one more rule, in the part where the order is decided (Objects/abstract.c#L965-L974):

    if (slotv) {
        PyObject *x;
        if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
            x = slotw(v, w);
            if (x != Py_NotImplemented)
                return x;
            Py_DECREF(x); /* can't do it */
            slotw = NULL;
        }
        x = slotv(v, w);

When w’s type derives from v’s, w’s function goes first, so that a subclass can override what its base does with it. minipy leaves that rule out (see the last section).

Each operator in CPython has a C function, PyNumber_Add(), PyNumber_And() and so on, most of them written by one macro (Objects/abstract.c#L1123-L1127):

#define BINARY_FUNC(func, op, op_name) \
    PyObject * \
    func(PyObject *v, PyObject *w) { \
        return binary_op(v, w, NB_SLOT(op), op_name); \
    }

PyNumber_Add() is written out by hand, because + on sequences falls back to their sq_concat slot. The bytecode instruction BINARY_OP reaches these functions through a table indexed by its argument, _PyEval_BinaryOps. That is the unspecialized path (Python/bytecodes.c#L5924-L5938):

        op(_BINARY_OP, (lhs, rhs -- res, l, r)) {
            PyObject *lhs_o = PyStackRef_AsPyObjectBorrow(lhs);
            PyObject *rhs_o = PyStackRef_AsPyObjectBorrow(rhs);

            assert(_PyEval_BinaryOps[oparg]);
            PyObject *res_o = _PyEval_BinaryOps[oparg](lhs_o, rhs_o);
            if (res_o == NULL) {
                ERROR_NO_POP();
            }
            res = PyStackRef_FromPyObjectSteal(res_o);
            l = lhs;
            r = rhs;
            DEAD(lhs);
            DEAD(rhs);
        }

Once an instruction has seen the same operand types a number of times, CPython replaces it with a specialized one that skips the slots for that case:

$ python3 - < adaptive.py
  3           RESUME                   0

  4           LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (a, b)
              BINARY_OP                0 (+)
              RETURN_VALUE
  3           RESUME_CHECK             0

  4           LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (a, b)
              BINARY_OP_ADD_INT        0 (+)
              RETURN_VALUE

adaptive.py disassembles a function add(a, b) that returns a + b, calls it 1,000 times with two ints, and disassembles it again with adaptive=True. Specialization is the subject of lesson 32; the slots are what every case not specialized falls back to.

The figure steps through binary_op() for the four lines of the example.

./minipy --trace-ops examples/slots.py at tag lesson-07.1, 19 frames. Note that bool’s table has int_add in nb_add, that 5 & True finds a different function in each operand’s type, and that None + 1 ends in a TypeError after int_add() declines.

bool, a subclass of int

bool sets three slots itself:

static NumberMethods bool_as_number = {
    .nb_and = bool_and,
    .nb_xor = bool_xor,
    .nb_or = bool_or,
};

and names int as its base:

TypeObject Bool_Type = {
    .base = { 1, &Type_Type }, .name = "bool", .base_type = &Int_Type,
    .dealloc = static_dealloc, .repr = bool_repr, .as_number = &bool_as_number,
};

bool_and() gives a bool when both operands are bools, and hands any other pair to int’s slot:

static Object *bool_and(Object *a, Object *b)
{
    if (a->type != &Bool_Type || b->type != &Bool_Type)
        return Int_Type.as_number->nb_and(a, b);
    return bool_from(a == True && b == True);
}

which is what CPython’s does (Objects/boolobject.c#L86-L92):

static PyObject *
bool_and(PyObject *a, PyObject *b)
{
    if (!PyBool_Check(a) || !PyBool_Check(b))
        return PyLong_Type.tp_as_number->nb_and(a, b);
    return PyBool_FromLong((a == Py_True) & (b == Py_True));
}

The other twelve slots of bool’s table are empty in the source. type_ready() fills them once, at start, from the base’s table, slot by slot, with one macro call per slot:

#define COPYSLOT(slot) \
    if (!type->slot) type->slot = base->slot
#define COPYNUM(slot) \
    if (!type->as_number->slot) type->as_number->slot = base->as_number->slot

CPython’s inherit_slots(), which PyType_Ready() reaches, has the same shape (Objects/typeobject.c#L8889-L8897):

#define SLOTDEFINED(SLOT) \
    (base->SLOT != 0 && \
     (basebase == NULL || base->SLOT != basebase->SLOT))

#define COPYSLOT(SLOT) \
    if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT

#define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)

SLOTDEFINED adds a condition minipy does not need: copy a slot only if the base set it itself rather than inheriting it from its own base. The caller runs inherit_slots() once for each class in the method resolution order, so the base’s base gets its own turn. minipy’s types are one level deep.

So True + True reads nb_add in bool’s table, finds int_add, and gets the int 2. With type_ready() not called, in a scratch copy of the tag, the slot is empty:

$ ./minipy ex7a.py
True
ex7a.py:2:7: error: TypeError: unsupported operand type(s) for +: 'bool' and 'bool'

ex7a.py is print(True & True) and print(True + True). The first still works: nb_and is bool’s own.

Comparisons and truth

Comparisons have one slot, richcompare, that takes the operation as an argument. rich_compare() tries the left operand’s type, then the right one’s with the operation reversed, since a < b is b > a:

Object *rich_compare(Object *v, Object *w, CmpOp op)
{
    RichCmpFunc f;
    Object *r;
    if ((f = v->type->richcompare) != NULL) {
        r = f(v, w, op);
        if (r != NotImplemented)
            return r;
        decref(r);
    }
    if ((f = w->type->richcompare) != NULL) {
        r = f(w, v, swapped[op]);
        if (r != NotImplemented)
            return r;
        decref(r);
    }
    switch (op) {
    case CMP_EQ:
        return bool_from(v == w);
    case CMP_NE:
        return bool_from(v != w);
    default:
        err_format("TypeError: '%s' not supported between instances of '%s' and '%s'",
                   cmp_symbols[op], v->type->name, w->type->name);
        return NULL;
    }
}

If both decline, == and != fall back to identity, and an ordering is an error. CPython’s do_richcompare() ends the same way (Objects/object.c#L1076-L1094):

    /* If neither object implements it, provide a sensible default
       for == and !=, but raise an exception for ordering. */
    switch (op) {
    case Py_EQ:
        res = (v == w) ? Py_True : Py_False;
        break;
    case Py_NE:
        res = (v != w) ? Py_True : Py_False;
        break;
    default:
        _PyErr_Format(tstate, PyExc_TypeError,
                      "'%s' not supported between instances of '%.100s' and '%.100s'",
                      opstrings[op],
                      Py_TYPE(v)->tp_name,
                      Py_TYPE(w)->tp_name);
        return NULL;
    }
    return Py_NewRef(res);
}

bool has no richcompare of its own and gets int’s from type_ready(). With an int on either side, int’s own slot would answer anyway, so the case that needs the copy is two bools. cmp7.py prints 1 == True, True == 1 and True < False, False < True, first at the tag, then in the scratch copy without type_ready():

$ ./minipy cmp7.py
True True
False True
$ ./minipy cmp7.py
True True
cmp7.py:2:7: error: TypeError: '<' not supported between instances of 'bool' and 'bool'

Truth goes through a slot too: is_true() answers for True, False and None directly, and otherwise calls the type’s nb_bool, so while x: asks int_bool(). A type with no number table counts as true, which makes not int False, as in tests/run/truth.py.

Where minipy differs

  • No subclass first. CPython calls the right operand’s function first when its type derives from the left one’s. In minipy the only subclass is bool, and its slots hand mixed operands to int’s, so the order changes which function runs but not the result: 5 & True is int_and() in minipy, while CPython’s binary_op1() calls bool_and() first, which hands the pair to int’s nb_and; the result is 1 in both. rich_compare() leaves the same rule out. Classes in lesson 28 will need it.
  • No in-place slots. x += 1 uses nb_add. The error message still says +=, as CPython’s does.
  • 15 number slots, not 36, and nb_power takes two arguments.
  • Errors are a message in a buffer, not an exception object.
  • NotImplemented is true. Its type has no number table, so if NotImplemented: runs its body. CPython’s NotImplementedType has an nb_bool that raises TypeError: NotImplemented should not be used in a boolean context.
  • ~True is -2 in both, but CPython 3.15 also warns. bool’s table in CPython has its own nb_invert for that warning; minipy’s inherits int’s.
$ ./minipy tests/run/invert-bool.py; python3 - < tests/run/invert-bool.py
-2
<stdin>:1: DeprecationWarning: Bitwise inversion '~' on bool is deprecated and will be removed in Python 3.16. This returns the bitwise inversion of the underlying int object and is usually not what you expect from negating a bool. Use the 'not' operator for boolean negation or ~int(x) if you really want the bitwise inversion of the underlying int.
-2

Only the last of these changes what a program in tests/run/ prints. make compare-run lists the 16 programs that differ from CPython on purpose, each with its reason, most of them for 64-bit ints and features not built yet:

$ sh tests/run.sh ./minipy | tail -1; sh tests/run.sh ./minipy-asan | tail -1; python3 tests/compare-run.py ./minipy | tail -1
166 passed, 0 failed
166 passed, 0 failed
27 same, 16 differ on purpose, 0 differ otherwise

Try it yourself

Check out lesson-07.1 and keep make test and make check passing.

  1. The order of names. print(1 < None) stops with a TypeError that names int first and NoneType second. Which functions were tried before that, and with which operation?

    Answer

    int_richcompare(1, None, CMP_LT) first, from int’s slot; it returns NotImplemented because None is not an int. NoneType has no richcompare, so the swapped call, (None, 1, CMP_GT), is never made. The message names the operands in the order they were written, which matches CPython:

    $ ./minipy tests/run/err-type-compare-reflected.py; python3 - < tests/run/err-type-compare-reflected.py
    tests/run/err-type-compare-reflected.py:1:7: error: TypeError: '<' not supported between instances of 'int' and 'NoneType'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: '<' not supported between instances of 'int' and 'NoneType'
    
  2. Plus a bool. int_positive() returns its argument for an int but makes a new object for a bool. Why not return the bool?

    Answer

    +True is the int 1 in Python, not True: unary plus on a bool gives an int, like the other arithmetic. bool inherits nb_positive from int, so int_positive() sees bools too and has to make an int with the same value. tests/run/slots.py prints 1 for +True in both interpreters.

  3. Two tables, one function. In the frames for True + True, binary_op1() reads no slot in the right operand’s type. In which other case would it skip the right operand’s slot even though the types differ?

    Answer

    When the right type’s slot holds the same function as the left’s. True + 5 reads int_add in bool’s table, which was copied from int’s, and the same int_add in int’s table, so it sets slotw to NULL and calls int_add() once. Calling it twice could not give a different answer. ./minipy --trace-ops on print(True + 5) has the frame that says so.

  4. Truth of a type. Why is not int False?

    Answer

    int is a type object, whose type is type. type has no number table, so is_true() finds no nb_bool and returns 1: an object with no way to say otherwise is true. CPython’s PyObject_IsTrue() ends the same way, after also trying the length slots of sequences and mappings. tests/run/truth.py prints False for not int in both interpreters.

  5. A table on NoneType. NoneType’s table sets only nb_bool, and is_true() answers for None before it looks at any slot. What would change if NoneType had no table at all?

    Answer

    Nothing a minipy program can see. None is the only NoneType object, and is_true() returns 0 for it before reaching the slot; every number operator on None already finds NULL in the table and ends in the TypeError. CPython also gives NoneType a table with nb_bool, and PyObject_IsTrue() also checks for None first.

Sources

minipy, tag lesson-07.1: src/object.h, src/object.c, src/intobject.c, src/eval.c, src/otrace.c, tests/run/, tests/compare-run.py. Built with cc (Apple clang 21.0.0) on macOS; the outputs above were recorded with that build and Python 3.15.2.

CPython v3.15.2:

ls python-in-c/

Reading source

Objects

  • 06 Everything is an object draftThe object header, a reference count and a type pointer, and why a type is an object too.
  • 07 Operators through type slots draftHow a + b finds the code to run: function pointers on the type, like CPython's tp_ and nb_ slots.
  • 08 Integers of any size, and floats plannedInts as arrays of digits (30 bits each in CPython's default build), and floats as C doubles.
  • 09 Strings plannedImmutable text with a cached hash, and CPython's choice of one, two or four bytes per character.
  • 10 Lists and tuples plannedA growable array that over-allocates, and a fixed one.
  • 11 Dicts: a hash table that keeps order plannedOpen addressing over a small index table and a dense array of entries, the layout CPython has used since 3.6.
  • 12 The evaluator, on objects plannedThe tree-walker again, now with every value a pointer to an object.

Memory

  • 13 Reference counting plannedWho owns a reference, when to increment, when to decrement, and what happens at zero.
  • 14 Finding reference counting bugs plannedLeaks and use-after-free, caught by a debug mode that counts live references and by AddressSanitizer.
  • 15 What reference counting cannot free plannedA list that contains itself, and why its count never reaches zero.
  • 16 A cycle collector plannedFind unreachable cycles by subtracting the references objects hold to each other, as CPython's gc does with gc_refs.
  • 17 Generations plannedCollect young objects often and old ones rarely. CPython 3.14.0 to 3.14.4 shipped an incremental collector; 3.14.5 and 3.15 went back to generations.
  • 18 Small ints, interning and immortal objects plannedObjects made once and shared: CPython 3.15 preallocates the ints from -5 to 1024, interns strings, and since 3.12 has objects it never counts.
  • 19 A small-object allocator plannedPools and arenas for the many small blocks an interpreter asks for, after CPython's obmalloc.

Bytecode

  • 20 From trees to bytecode plannedWhy interpreters compile to a flat list of instructions, and the instruction set of a stack machine.
  • 21 The compiler plannedExpressions, assignments, jumps for if and while, and a code object to hold the result.
  • 22 The evaluation loop plannedA loop over instructions with a value stack. CPython generates its loop from Python/bytecodes.c.
  • 23 Functions, frames and calls plannedA frame per call, arguments on the stack, and returning a value.
  • 24 Scopes: locals, globals, builtins plannedA symbol table decides where each name lives before any code runs.
  • 25 Closures and cells plannedVariables that outlive the call that made them.
  • 26 Exceptions plannedRaising and unwinding, and the exception table CPython has used since 3.11, which costs nothing until something is raised.
  • 27 Generators plannedA frame that stops in the middle and resumes: yield, send and the generator object.
  • 28 Classes and instances plannedA class is an object that makes objects. minipy keeps instance attributes in a dict; CPython does something more compact.
  • 29 Attribute lookup plannedThe method resolution order, descriptors and bound methods: what obj.name does.

The C boundary and speed

  • 30 The C API boundary plannedBuiltin functions written in C, and what CPython's C API promises extension modules.
  • 31 Dispatch: switch, computed gotos, tail calls plannedHow the loop gets to the next instruction. CPython uses computed gotos where the compiler allows, and 3.14 added an opt-in tail-calling interpreter.
  • 32 Inline caches and specialization plannedRewriting instructions at run time for the types they meet, as CPython has done since 3.11, in a small version for minipy.
  • 33 minipy against CPython plannedMeasuring both on the same programs, and what accounts for the difference.