man python-in-c/pyobject

lesson 6 of 33 · Objects

Everything is an object

lib / Building a Python in C 18 mindraft

checked against: CPython 3.15.2, Apple clang 21.0.0

code: toothywalrus/minipy@lesson-06

In lesson 5 a value was an int64_t, and the evaluator passed values around by copying them. That was enough for arithmetic, but a Python value is more than a number: it has a type you can ask for, it can be None, and two names can refer to the same value, which is can tell apart from two equal ones. This lesson gives minipy values that are objects in memory, each with a header saying what it is and how many references point at it, the way CPython does.

The code is minipy at tag lesson-06. The objects are in src/object.h and src/object.c, src/eval.c now passes Object * everywhere, and src/htrace.c draws the figure below. make test runs 153 tests, among them each of the 37 programs in tests/run/ twice: once for its output, once with a check that no object is left behind. Every terminal output below was recorded from a run of the command shown with it.

A program with objects

The example for this lesson is examples/objects.py:

a = 300
b = a
c = 300
a = None
print(b is c, type(b))
$ ./minipy examples/objects.py; python3 - < examples/objects.py
False <class 'int'>
True <class 'int'>

The second half of that line agrees, and the first does not. Both are about objects: type(b) reads something stored in the object b refers to, and b is c asks whether two names refer to the same object. We come back to the disagreement at the end.

The header

Every object starts with the same two fields:

/* The header. */
typedef struct {
    int64_t refcnt;             /* references to this object */
    TypeObject *type;
} Object;

An int is that header followed by its value:

/* An int: the header, then the value. Still 64 bits until lesson 8. */
typedef struct {
    Object base;
    int64_t value;
} IntObject;

Because base comes first, a pointer to an IntObject is also a pointer to its header; C guarantees that a struct’s first member sits at its address. So code that holds an Object * can read refcnt and type without knowing what kind of object it has, and only code that has checked the type casts it to IntObject * to reach the value.

CPython’s header is struct _object, which the C API calls PyObject. In the default build on a 64-bit machine it looks like this (Include/object.h#L126-L149):

#elif !defined(Py_GIL_DISABLED)
struct _object {
    _Py_ANONYMOUS union {
#if SIZEOF_VOID_P > 4
        int64_t ob_refcnt_full; /* This field is needed for efficient initialization with Clang on ARM */
        struct {
#  if PY_BIG_ENDIAN
            uint16_t ob_flags;
            uint16_t ob_overflow;
            uint32_t ob_refcnt;
#  else
            uint32_t ob_refcnt;
            uint16_t ob_overflow;
            uint16_t ob_flags;
#  endif
        };
#else
        Py_ssize_t ob_refcnt;  // part of stable ABI; do not change
#endif
        _Py_ALIGNED_DEF(_PyObject_MIN_ALIGNMENT, char) _aligner;
    };

    PyTypeObject *ob_type;  // part of stable ABI; do not change
};

The shape is minipy’s: 8 bytes about the count, then the type pointer. CPython splits the first 8 bytes into a 32-bit count and two 16-bit fields, ob_overflow and ob_flags. Immortal objects (below) are told apart by their count; the flags record, among other things, which objects the C compiler laid out. The free-threaded build, where Py_GIL_DISABLED is defined, has a different header with a thread id and two counts (lines 156 to 167 of the same file, listed in the sources); minipy has one thread and follows the default build.

A type is an object too

A type in minipy is a struct with the same header, a name, and pointers to the functions that do what differs from type to type:

struct TypeObject {
    Object base;                /* a type is an object */
    const char *name;
    void (*dealloc)(Object *self);                  /* refcnt reached 0 */
    int (*repr)(Object *self, char *buf, size_t size);  /* like snprintf */
};

Since type(5) returns the int type, and a returned value is an Object *, the type has to be an object. And since every object has a type, a type has a type too. In Python that is type, and the type of type is type again. minipy’s type objects are laid out by the C compiler:

/* The type of every type, its own included. */
TypeObject Type_Type = { { 1, &Type_Type }, "type", static_dealloc, type_repr };

TypeObject Int_Type = { { 1, &Type_Type }, "int", int_dealloc, int_repr };
TypeObject Bool_Type = { { 1, &Type_Type }, "bool", static_dealloc, bool_repr };
TypeObject NoneType_Type = { { 1, &Type_Type }, "NoneType", static_dealloc, none_repr };

Object None_Object = { 1, &NoneType_Type };
IntObject True_Object = { { 1, &Bool_Type }, 1 };
IntObject False_Object = { { 1, &Bool_Type }, 0 };

Type_Type names itself in its own initializer, which C allows because the address of a variable is known before its value is. CPython does the same in Objects/typeobject.c#L7346-L7348:

PyTypeObject PyType_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "type",                                     /* tp_name */

True and False are IntObjects whose type is bool, which is how CPython has them too: bool is a subclass of int. None is a bare header. type(x) is then a matter of reading a pointer:

        /* type(x): the type of x, which is an object like any other. */
        a = eval(ev, e->v.Call.args.items[0]);
        if (!a)
            return NULL;
        r = incref(&a->type->base);
        decref(a);
        return r;

CPython’s unspecialized path for a call to type with one argument does the same, where Py_NewRef increments a count and returns its argument (Objects/typeobject.c#L5173-L5182):

type_vectorcall(PyObject *metatype, PyObject *const *args,
                 size_t nargsf, PyObject *kwnames)
{
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
    if (nargs == 1 && metatype == (PyObject *)&PyType_Type){
        if (!_PyArg_NoKwnames("type", kwnames)) {
            return NULL;
        }
        return Py_NewRef(Py_TYPE(args[0]));
    }

A call site that has run often enough is replaced with the specialized instruction CALL_TYPE_1, which reads the same pointer without making the call. Here a function returning type(x) has run 1,000 times:

$ python3 - < typecall.py
  3           RESUME_CHECK             0

  4           LOAD_GLOBAL_BUILTIN      1 (type + NULL)
              LOAD_FAST_BORROW         0 (x)
              CALL_TYPE_1              1
              RETURN_VALUE

Both interpreters print the same for tests/run/type-objects.py:

$ cat tests/run/type-objects.py; ./minipy tests/run/type-objects.py
# A type is an object, so it can be printed, compared and stored.
print(type(5), type(True), type(None))
print(type(type(5)), type(type(type(5))))
t = type(7)
print(t is int, type(True) is bool, type(int) is type, type(type) is type)
print(int, bool, type)
<class 'int'> <class 'bool'> <class 'NoneType'>
<class 'type'> <class 'type'>
True True True True
<class 'int'> <class 'bool'> <class 'type'>

With types as objects, an operator can check its operands’ types and refuse the wrong ones with CPython’s message:

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

At this lesson the evaluator does that check itself, with is_int(). Lesson 7 moves it onto the types.

Who holds a reference

An object made with malloc() has to be freed once nothing uses it, and the count in its header is how minipy knows when that is. The count is the number of references to the object: pointers to it held by something that will later say it is done. Two small functions keep it:

static inline Object *incref(Object *o)
{
    o->refcnt++;
    return o;
}

void object_dealloc(Object *o);

static inline void decref(Object *o)
{
    if (--o->refcnt == 0)
        object_dealloc(o);
}

At 0, object_dealloc() asks the type how to free the object:

/* The count reached 0: the type knows how to free its objects. */
void object_dealloc(Object *o)
{
    o->type->dealloc(o);
}

So a type’s dealloc slot frees that type’s instances, not the type: Int_Type.dealloc is int_dealloc(), which frees an int. The type objects themselves are never freed.

The counts are right only if every piece of code follows the same rules about who holds which reference. minipy’s are:

  • eval() returns a new reference: the caller holds it and must give it back with decref(), or hand it to something that will.
  • A variable holds a reference to its value. store() takes over the one it is given and gives back the one it held:
/* Bind name to value. The variable takes over the caller's reference, and
   gives back the one it held before. */
static void store(Eval *ev, const char *name, Object *value)
{
    Var *v = lookup(ev, name);
    if (!v) {
        if (ev->nvars == ev->cap) {
            ev->cap = ev->cap ? 2 * ev->cap : 16;
            ev->vars = realloc(ev->vars, sizeof *ev->vars * (size_t)ev->cap);
            if (!ev->vars) {
                perror("minipy");
                exit(2);
            }
        }
        v = &ev->vars[ev->nvars++];
        v->name = name;
        v->value = NULL;
    }
    Object *old = v->value;
    v->value = value;
    if (old)
        decref(old);
    step(ev, (EStep){ .kind = ESTEP_STORE, .name = name, .value = value, .old = old });
}
  • Reading a variable returns incref(var->value), a new reference, so the variable keeps its own.

Every case of eval() then gives back what it no longer needs, on the error paths too. Here is BinOp:

    case BinOp_kind:
        a = eval(ev, e->v.BinOp.left);
        if (!a)
            return NULL;
        b = eval(ev, e->v.BinOp.right);
        if (!b) {
            decref(a);
            return NULL;
        }
        r = binop(ev, e->pos, e->v.BinOp.op, false, a, b);
        decref(a);
        decref(b);
        return r;

The figure runs examples/objects.py with these rules. A frame is drawn after each expression gets its value, each assignment, and each variable released at the end; the caption lists the counts that changed since the frame before.

./minipy --trace-heap examples/objects.py, 20 frames. Watch the count of int #1 go from 1 to 2 at b = a and back at a = None, the int type’s count rise while type(b) holds a reference to it, and the two ints freed only when the variables are released at the end.

The same rules, with more on borrowed references and what holding one means across a call, are the subject of lesson 13.

Objects that are never freed

None, True, False and the four types are not made with malloc(), so they must never be freed. minipy gives each a count of 1 from the start, the reference the interpreter holds, and their dealloc slot is static_dealloc(), which stops the program if that count reaches 0 anyway:

static void static_dealloc(Object *self)
{
    char buf[64];
    object_repr(self, buf, sizeof buf);
    fprintf(stderr, "minipy: fatal: the reference count of %s reached 0\n", buf);
    abort();
}

The counts on these objects are still kept, so a mistake with None shows up like a mistake with an int.

CPython makes such objects immortal. On a 64-bit machine an object whose 32-bit count is 2312^{31} or more is immortal, and the objects laid out by the C compiler start at _Py_IMMORTAL_INITIAL_REFCNT (Include/refcount.h#L47):

#define _Py_IMMORTAL_INITIAL_REFCNT (3ULL << 30)

Py_DECREF in the default build checks for that before it touches the count (Include/refcount.h#L417-L429):

static inline Py_ALWAYS_INLINE void Py_DECREF(PyObject *op)
{
    // Non-limited C API and limited C API for Python 3.9 and older access
    // directly PyObject.ob_refcnt.
    if (_Py_IsImmortal(op)) {
        _Py_DECREF_IMMORTAL_STAT_INC();
        return;
    }
    _Py_DECREF_STAT_INC();
    if (--op->ob_refcnt == 0) {
        _Py_Dealloc(op);
    }
}

Py_INCREF checks too, and leaves a count of 3 << 30 or more alone, so the count of an object that starts there does not move:

$ python3 - < immortal.py
3221225472 3221225472 3221225472
3221225472
True True False

The first line is sys.getrefcount() of None, int and type, the second is 3 << 30, and the third asks sys._is_immortal() about None, int and 10 ** 30. Where minipy stops on a count that reaches 0, CPython’s bool_dealloc(), reached only if something has gone wrong, makes the object immortal again (Objects/boolobject.c#L159-L167):

static void
bool_dealloc(PyObject *boolean)
{
    /* This should never get called, but we also don't want to SEGV if
     * we accidentally decref Booleans out of existence. Instead,
     * since bools are immortal, re-set the reference count.
     */
    _Py_SetImmortal(boolean);
}

One more difference: an object in CPython holds a reference to its type. _PyObject_Init() takes it through the _Py_INCREF_TYPE macro, which is Py_INCREF in the default build (Include/internal/pycore_object.h#L484-L492):

static inline void
_PyObject_Init(PyObject *op, PyTypeObject *typeobj)
{
    assert(op != NULL);
    Py_SET_TYPE(op, typeobj);
    assert(_PyType_HasFeature(typeobj, Py_TPFLAGS_HEAPTYPE) || _Py_IsImmortal(typeobj));
    _Py_INCREF_TYPE(typeobj);
    _Py_NewReference(op);
}

For a type laid out in C that does nothing, since the type is immortal; it matters for classes made at run time, which can be freed. minipy has only static types, and its objects do not count their type.

Checking the counts

A count one too high keeps an object alive forever; one too low frees it while something still points at it. minipy --refs runs a program and then reports what is left:

$ ./minipy --refs examples/objects.py
False <class 'int'>
[refs] 0 objects alive: 2 made, 2 freed; static objects back to their starting counts

“Made” and “freed” count the heap objects that int_new() and int_dealloc() saw. tests/run.sh runs all 37 programs in tests/run/ this way, those that stop with an error included, and fails unless the line says 0 alive and every static object back to 1. make fuzz-eval runs its programs with --refs too:

$ make -s fuzz-eval
seed 1: 1000 expressions: 884 values, 24 ZeroDivisionError, 9 ValueError, 76 past 64 bits, 7 negative powers; 0 differ, 0 runs with objects left alive
seed 2: 1000 expressions: 876 values, 34 ZeroDivisionError, 14 ValueError, 74 past 64 bits, 2 negative powers; 0 differ, 0 runs with objects left alive
seed 3: 1000 expressions: 884 values, 40 ZeroDivisionError, 8 ValueError, 62 past 64 bits, 6 negative powers; 0 differ, 0 runs with objects left alive

That only shows something if a broken count would make it fail, so I broke three on purpose, each in a scratch copy of the tag. With the decref(b); in the BinOp case deleted, the right operand of every binary operator is never freed:

$ ./minipy --refs tests/run/identity.py; sh tests/run.sh ./minipy | tail -1
True False True
True False
[refs] 1 objects alive: 6 made, 5 freed; static objects back to their starting counts
135 passed, 18 failed

With the decref() of an expression statement’s value replaced by nothing, the None that print() returns keeps one count too many:

$ ./minipy --refs examples/objects.py
False <class 'int'>
[refs] 0 objects alive: 2 made, 2 freed; static objects changed: None 2

And with print() returning None without incref(), the count of None reaches 0:

$ ./minipy examples/objects.py; echo "exit status $?"
False <class 'int'>
minipy: fatal: the reference count of None reached 0
bash: line 1: 79610 Abort trap: 6           ./minipy examples/objects.py
exit status 134

make check runs the tests under AddressSanitizer as well, which would catch a freed object being used. It cannot report leaks here: Apple clang’s AddressSanitizer does not support leak detection on macOS, so the --refs counts are the tests’ only check for objects never freed.

CPython’s debug build keeps a similar total. Every Py_INCREF and Py_DECREF of an object that is not immortal adjusts it, and -X showrefcount prints it, with the number of memory blocks still allocated, when the interpreter has shut down:

$ ./python-debug -X showrefcount - < objects.py
True <class 'int'>
[0 refs, 0 blocks]

python-debug is a link to a debug build of v3.15.2, one with Py_REF_DEBUG. The count is of references, not objects, and it is taken after the interpreter has freed its own state, so it measures the whole run, not just the program. Lesson 14 is about finding the bugs these counts point to.

Same object or equal object

is compares the two pointers, and == the values. minipy makes a new int object for every literal and every result, so the two literals 300 in examples/objects.py are two objects and b is c is False. CPython says True, and the compiler is the reason here: the two equal constants become one entry in the code object’s constants, and both lines load it:

$ cat two.py; python3 -m dis < two.py
a = 300
b = 300
  0           RESUME                   0

  1           LOAD_CONST               0 (300)
              STORE_NAME               0 (a)

  2           LOAD_CONST               0 (300)
              STORE_NAME               1 (b)
              LOAD_COMMON_CONSTANT     7 (None)
              RETURN_VALUE

CPython also keeps one object for each int from -5 to 1024 (_PY_NSMALLPOSINTS is 1025 and _PY_NSMALLNEGINTS 5 in Include/internal/pycore_runtime_structs.h), so a result in that range is shared even when it is computed. 2000 separates the two:

$ cat identity2000.py; python3 - < identity2000.py
a = 2000
b = 2000
print(a is b)
n = 2000
m = n + 1 - 1
print(n == m, n is m)
n = 1000
m = n + 1 - 1
print(n == m, n is m)
True
True False
True True

Neither sharing is part of the language, which leaves is on ints up to the implementation. Lesson 18 adds small ints to minipy.

The constants also explain a number. sys.getrefcount() reports one more than the references the program holds, for its own argument, and for 10 ** 30 one more again:

$ cat getrefcount.py; python3 - < getrefcount.py
import sys
x = 10 ** 30
y = int("1" + "0" * 30)
print(sys.getrefcount(x), sys.getrefcount(y))
z = y
print(sys.getrefcount(y))
3 2
3

The compiler folds 10 ** 30 into a constant, and the code object’s constants hold a reference to it; a value made at run time, y, does not have that one. That reading is inferred from this run and from co_consts of the same line, which holds the folded number; I did not trace the count in a debugger.

Where minipy differs

  • Ints are still 64-bit, as in lesson 5, and every int is a new object: no shared constants and no small ints, so is on equal ints is False where CPython often says True.
  • Static objects have a count of 1 and stop the program if it reaches 0. CPython’s are immortal and their counts do not change.
  • Objects do not hold a reference to their type. In CPython they do, which matters only for types that can be freed.
  • The header has one 64-bit count. CPython’s default build keeps a 32-bit count beside flags, and its free-threaded build has two counts.
  • Operators check for ints in the evaluator, and bool has no operators of its own, so True & True is the int 1; CPython gives True. Lesson 7 fixes both.
  • Functions are not objects yet: print can only be called. type is the type object and can be printed or stored, but calling it takes exactly one argument, and assigning to either name is refused before running.

Try it yourself

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

  1. Counting objects. How many int objects does this program make, and when is each freed?

    x = 1 + 2 * 3
    print(x)
    
    Answer

    Five: one for each of the constants 1, 2 and 3, one for 2 * 3, and one for 1 + 6. The 2 and the 3 are freed as soon as 2 * 3 has its result, the 1 and the 6 as soon as the sum has its own, and the 7 when x is released at the end.

    $ ./minipy --refs ex1.py
    7
    [refs] 0 objects alive: 5 made, 5 freed; static objects back to their starting counts
    
  2. One reference too many. The Assign case hands eval()’s reference to the last name and gives each other name its own with incref(). Suppose it called incref() for every name, the last one included. What does --refs print for examples/objects.py?

    Answer

    Each assignment leaves one count too many on its value, so neither int is ever freed, and None, assigned once, ends at 2:

    $ ./minipy --refs examples/objects.py
    False <class 'int'>
    [refs] 2 objects alive: 2 made, 0 freed; static objects changed: None 2
    

    That is from a scratch copy with the change made.

  3. The type of type. In the figure, which arrow goes from an object back to itself, and what would type(type(type)) print?

    Answer

    The type pointer of type, because Type_Type is initialised with &Type_Type. So the chain stops there: type(type(type)) is type, and prints <class 'type'>, like type(type(type(5))) in tests/run/type-objects.py.

  4. Leak or crash. Two of the broken builds above lose a count on None. Why does one report a leak at exit while the other stops the program in the middle?

    Answer

    Skipping the decref() leaves the count one too high, so nothing goes wrong until the end, when --refs sees None at 2. Skipping the incref() leaves it one too low, so the next decref() that thinks it gives back a real reference brings it to 0, and static_dealloc() stops the program. Had None been made with malloc(), the second mistake would have freed it while the interpreter still pointed at it.

  5. Why 3221225472? sys.getrefcount(None) prints the same number however many references a program makes to None. Where does the number come from, and why does it not change?

    Answer

    It is _Py_IMMORTAL_INITIAL_REFCNT, 3 << 30, the count that statically laid out objects start at on a 64-bit build. Py_DECREF returns without touching the count of an immortal object, one whose 32-bit count is 2312^{31} or more, and Py_INCREF leaves alone a count of 3 << 30 or more, so a count that starts there stays there.

Sources

minipy, tag lesson-06: src/object.h, src/object.c, src/eval.c, src/htrace.c, src/main.c (--refs), tests/run.sh, tests/fuzz-eval.py. Built with cc (Apple clang 21.0.0) on macOS; the outputs above were recorded with that build, Python 3.15.2, and a debug build of v3.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.