Every Python Call Is a C Call

Contents
In Python 3.7, a function that calls itself 22,000 times crashes the interpreter outright: no
exception, no traceback, just Segmentation fault and exit status 139. Python’s own recursion limit
stops that from happening, by default, at a depth of 1,000. That limit is not a rule of the language.
It’s a guess about the C stack, which CPython uses up at 384 bytes per Python call on this
build. Raise the limit far enough, or reach the C stack through a path the limit never counts, and
the guess runs out.
The reason is that CPython runs Python code with a C function, and when Python calls Python, that C function calls itself. A Python call stack is a C call stack, with all of a C call stack’s limits. This post measures that stack: what one Python call puts on it, what the recursion limit counts and what it misses, how much stack different kinds of recursion take, what happens in threads, and why generators are the one place where Python frames get off the C stack.
This is Part 3 of a series on the CPython runtime. Part 1
was about objects in memory, and Part 2 about the loop
that runs bytecode. Python 3.7.0 came out on 27 June, and everything here ran on it, built from the
v3.7.0 tag with Ubuntu 18.04’s gcc 7.3.0 and run on 18.04’s release userland. In the listings,
python3 is that build. The note at the end says exactly what ran where.
A Python call, seen from C
Part 2 ended inside _PyEval_EvalFrameDefault, the C function that executes a frame’s bytecode. When
that bytecode reaches CALL_FUNCTION and the thing being called is a Python function, the loop
doesn’t jump to the callee’s bytecode. It calls a C function that makes a new frame and calls
_PyEval_EvalFrameDefault again, from inside the first one. Here is a program that recurses three
times and then stops itself with a signal, so that gdb can show the C stack at the deepest point:
import os, signal
def f(n):
if n == 0:
os.kill(os.getpid(), signal.SIGTRAP) # stop here when run under gdb
return 0
return f(n - 1) + 1
f(3)
and a gdb script that walks the C frames, printing each function’s name and its stack pointer:
set pagination off
run
python
f = gdb.newest_frame()
rows = []
while f is not None:
rows.append((f.name() or "??", int(f.read_register("rsp"))))
f = f.older()
evals = [sp for name, sp in rows if name == "_PyEval_EvalFrameDefault"]
for i, (name, sp) in enumerate(rows[:24]):
print("#%-2d %-36s rsp=%#x" % (i, name, sp))
print("...")
print("_PyEval_EvalFrameDefault frames:", len(evals))
print("bytes between consecutive ones:", [b - a for a, b in zip(evals, evals[1:])][:4])
end
$ gdb -batch -x cframes.gdb --args $(which python3) depth.py
Program received signal SIGTRAP, Trace/breakpoint trap.
0x00007ffff683f187 in kill () from /lib/x86_64-linux-gnu/libc.so.6
#0 kill rsp=0x7fffffffdee8
#1 os_kill_impl rsp=0x7fffffffdef0
#2 os_kill rsp=0x7fffffffdef0
#3 _PyMethodDef_RawFastCallKeywords rsp=0x7fffffffdf20
#4 _PyCFunction_FastCallKeywords rsp=0x7fffffffdf20
#5 call_function rsp=0x7fffffffdf80
#6 _PyEval_EvalFrameDefault rsp=0x7fffffffdf80
#7 function_code_fastcall rsp=0x7fffffffe0c0
#8 _PyFunction_FastCallKeywords rsp=0x7fffffffe0f8
#9 call_function rsp=0x7fffffffe100
#10 _PyEval_EvalFrameDefault rsp=0x7fffffffe100
#11 function_code_fastcall rsp=0x7fffffffe240
#12 _PyFunction_FastCallKeywords rsp=0x7fffffffe278
#13 call_function rsp=0x7fffffffe280
#14 _PyEval_EvalFrameDefault rsp=0x7fffffffe280
#15 function_code_fastcall rsp=0x7fffffffe3c0
#16 _PyFunction_FastCallKeywords rsp=0x7fffffffe3f8
#17 call_function rsp=0x7fffffffe400
#18 _PyEval_EvalFrameDefault rsp=0x7fffffffe400
#19 function_code_fastcall rsp=0x7fffffffe540
#20 _PyFunction_FastCallKeywords rsp=0x7fffffffe578
#21 call_function rsp=0x7fffffffe580
#22 _PyEval_EvalFrameDefault rsp=0x7fffffffe580
#23 PyEval_EvalFrameEx rsp=0x7fffffffe6c0
...
_PyEval_EvalFrameDefault frames: 5
bytes between consecutive ones: [384, 384, 384, 384]
The stack grows downwards, so frame #0, the newest, has the lowest address. Reading upwards from
the bottom of the listing: frame #22 is the eval loop running the module’s code. It calls f(3),
and four C frames later, at #18, the eval loop is running again, this time on f’s bytecode. That
repeats for f(2), f(1) and f(0), and at the top f(0)’s eval loop calls the C function
os.kill, which calls kill() in the C library. Five eval-loop frames, one for the module and one
for each Python call, and each 384 bytes below the last.
The pattern of one Python call is always the same four C functions:
_PyEval_EvalFrameDefaultrunsCALL_FUNCTION, which callscall_function. That is astatichelper the compiler inlined into the loop, which is why gdb shows it at the same stack address as the loop itself._PyFunction_FastCallKeywordsinObjects/call.csees a plain Python function with positional arguments and takes the fast path tofunction_code_fastcall, which makes the new frame and copies the arguments into its locals:
f = _PyFrame_New_NoTrack(tstate, co, globals, NULL);
if (f == NULL) {
return NULL;
}
fastlocals = f->f_localsplus;
for (i = 0; i < nargs; i++) {
Py_INCREF(*args);
fastlocals[i] = *args++;
}
result = PyEval_EvalFrameEx(f,0);
PyEval_EvalFrameExis the public entry point for running a frame, and in 3.7 it is a single indirect call:
PyObject *
PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
{
PyThreadState *tstate = PyThreadState_GET();
return tstate->interp->eval_frame(f, throwflag);
}
The compiler turned that call into a jump (a tail call), so PyEval_EvalFrameEx leaves no frame
of its own in the middle of the chain. It shows up only at the very bottom, where something else
called it. eval_frame is a function pointer that normally points at _PyEval_EvalFrameDefault.
It has been there since 3.6 (PEP 523), so that a JIT compiler can replace the eval loop for a
whole interpreter.
The 384 bytes break down from the stack pointers. The eval loop’s own frame is 0xe0c0 − 0xdf80, 320
bytes: it is a 3,000-line function with a lot of local state. function_code_fastcall adds 56 and
_PyFunction_FastCallKeywords 8. The Python frame object, the one with the locals and the value
stack, is not on the C stack at all. It is on the heap, as Part 2 showed. What the C stack holds is
the C state of every eval loop that is waiting for a call to return: its registers, its stack
pointer into its own frame’s value stack, its position in the bytecode.
The C stack under f(3), by Python call
Every C frame between the module and kill(), drawn to scale. Newest at the top, as the stack grows downwards in memory.
Hover or focus a block for the C function, its size and its stack pointer.
Each group is the eval loop running one Python frame plus the calls it is making. Every Python call costs the same: a 320-byte eval loop, 56 bytes of function_code_fastcall and 8 of _PyFunction_FastCallKeywords. call_function is inlined, so it has no bytes of its own.
The guard: what RecursionError really counts
import sys
def f(n):
return f(n + 1) if n < 10**6 else n
depth = 0
def g():
global depth
depth += 1
g()
print("sys.getrecursionlimit() =", sys.getrecursionlimit())
try:
g()
except RecursionError as e:
print("RecursionError after", depth, "calls:", e)
$ python3 limit.py
sys.getrecursionlimit() = 1000
RecursionError after 999 calls: maximum recursion depth exceeded
(f is never called. It’s there to show that defining a deep recursion costs nothing; only running
it does.) The limit is 1,000, and g got 999 calls deep because the module’s own frame was the
first. The check is near the top of _PyEval_EvalFrameDefault:
if (Py_EnterRecursiveCall(""))
return NULL;
and Py_EnterRecursiveCall, a macro in Include/ceval.h, increments a per-thread counter,
tstate->recursion_depth, and calls _Py_CheckRecursiveCall when it passes the limit:
int
_Py_CheckRecursiveCall(const char *where)
{
PyThreadState *tstate = PyThreadState_GET();
int recursion_limit = _PyRuntime.ceval.recursion_limit;
...
if (tstate->recursion_critical)
/* Somebody asked that we don't check for recursion. */
return 0;
if (tstate->overflowed) {
if (tstate->recursion_depth > recursion_limit + 50) {
/* Overflowing while handling an overflow. Give up. */
Py_FatalError("Cannot recover from stack overflow.");
}
return 0;
}
if (tstate->recursion_depth > recursion_limit) {
--tstate->recursion_depth;
tstate->overflowed = 1;
PyErr_Format(PyExc_RecursionError,
"maximum recursion depth exceeded%s",
where);
return -1;
}
return 0;
}
So the recursion limit counts entries into C code that has opted in: every run of the eval loop,
plus a few C functions that call Py_EnterRecursiveCall themselves (PyObject_Repr passes
" while getting the repr of an object", and comparisons pass " in comparison"). It doesn’t
count bytes, and it can’t. C has no portable way to ask how much stack is left, so CPython counts
calls and relies on the default limit being far below what the stack can hold. The overflowed
flag gives the code that handles a RecursionError 50 more levels to work in, and if it goes past
those, the interpreter aborts with a fatal error rather than crash.
The C stack’s real size is a property of the process, set by the operating system. On Linux the
main thread’s stack is limited by RLIMIT_STACK, which ulimit -s shows:
$ ulimit -s
8192
8,192 KiB, 8 MiB. At 384 bytes per Python call that holds about 21,800 calls, so the default limit of 1,000, about 375 KiB of stack, uses less than a twentieth of it. The margin is deliberate. It has to cover recursion through C code that uses more stack per level than a plain call, platforms whose stacks are smaller, and threads.
Raising the limit
sys.setrecursionlimit changes the counter’s limit and nothing else. It can’t make the stack any
bigger:
import sys
sys.setrecursionlimit(10**6)
def f(n):
return 0 if n == 0 else f(n - 1) + 1
print(f(int(sys.argv[1])))
$ python3 crash.py 10000
10000
$ python3 crash.py 100000
Segmentation fault
$ echo $?
139
Ten thousand calls fit in 3.7 MiB of stack. A hundred thousand would need 37 MiB. The limit no longer stops them, and the process dies at about 21,800, where the stack runs out. The language promises an exception for unbounded recursion. This build delivered one for exactly as long as the counter was in charge, and a crash after that.
Programs raise the limit for good reasons: recursive descent parsers, tree walks over deep data, and naive solutions to recursive puzzles. Raising it is safe up to what the stack can hold, but that number depends on the C code that the recursion goes through, the platform, and whether it runs in the main thread. The next sections measure each of those.
Seeing the crash: faulthandler
A segfault in a Python program prints nothing useful by default, because the Python traceback
machinery never gets to run. The standard library’s faulthandler module, added in 3.3, installs C
signal handlers for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL, which print the Python
traceback of every thread before the process dies:
$ python3 -X faulthandler crash.py 100000
Fatal Python error: Segmentation fault
Current thread 0x0000736c96b5a080 (most recent call first):
File "crash.py", line 5 in f
File "crash.py", line 5 in f
...
File "crash.py", line 5 in f
File "crash.py", line 5 in f
...
Segmentation fault
The handler has two problems to solve, and how it solves them shows how much of the interpreter it
can’t trust. First, the stack has just overflowed, so a signal handler that runs on it would
overflow it again. faulthandler allocates a separate stack for signal handlers with
sigaltstack() (SIGSTKSZ bytes, 8 KiB here) and asks for its handlers to run there. Second, a
signal can arrive at any instruction, in the middle of malloc or with the interpreter’s state
half updated, so the handler can’t call into the interpreter or allocate memory. It walks the
frame list directly and writes each line with the raw write() system call. It stops after 100
frames (MAX_FRAME_DEPTH in Python/traceback.c) and prints .... Here the other 21,700 or so
frames were all the same line anyway.
Not all recursion is the same size
Plain Python calls are only one way to recurse. Any C function that calls itself, directly or
through other C functions, uses the C stack too, and each uses a different amount per level. To
measure them, this script builds structures of a given depth in a child process with
RLIMIT_STACK set, sees whether the child survives, and bisects for the deepest that does:
# Find, by bisection in child processes, the deepest nesting each kind of recursion survives
# under a given stack limit, with the recursion limit out of the way.
import resource, subprocess, sys
CHILD = r'''
import sys, json, pickle
sys.setrecursionlimit(10**7)
kind, n = sys.argv[1], int(sys.argv[2])
if kind == "python call":
def f(k):
return 0 if k == 0 else f(k - 1) + 1
f(n)
elif kind == "next(map chain)":
x = iter([1])
for _ in range(n):
x = map(abs, x)
next(x)
else:
x = []
for _ in range(n):
x = [x]
if kind == "repr(list)":
repr(x)
elif kind == "pickle.dumps":
pickle.dumps(x)
elif kind == "json.dumps":
json.dumps(x)
elif kind == "x == x2":
y = []
for _ in range(n):
y = [y]
x == y
'''
def survives(kind, n, stack):
def limit():
resource.setrlimit(resource.RLIMIT_STACK, (stack, stack))
r = subprocess.run([sys.executable, "-c", CHILD, kind, str(n)], preexec_fn=limit,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return r.returncode == 0
def deepest(kind, stack):
lo, hi = 1, 1
while survives(kind, hi, stack):
lo, hi = hi, hi * 2
while hi - lo > max(1, lo // 1000):
mid = (lo + hi) // 2
if survives(kind, mid, stack):
lo = mid
else:
hi = mid
return lo
stacks = [int(s) * 1024 for s in sys.argv[1:]] or [8 * 1024 * 1024]
for kind in ("python call", "repr(list)", "pickle.dumps", "json.dumps", "x == x2", "next(map chain)"):
for stack in stacks:
d = deepest(kind, stack)
print("%-12s stack %6d KiB: survives depth %8d -> %5.0f bytes of C stack per level"
% (kind, stack // 1024, d, stack / d))
$ python3 kinds.py 1024 8192 65536
python call stack 1024 KiB: survives depth 2712 -> 387 bytes of C stack per level
python call stack 8192 KiB: survives depth 21808 -> 385 bytes of C stack per level
python call stack 65536 KiB: survives depth 174720 -> 384 bytes of C stack per level
repr(list) stack 1024 KiB: survives depth 8120 -> 129 bytes of C stack per level
repr(list) stack 8192 KiB: survives depth 65408 -> 128 bytes of C stack per level
repr(list) stack 65536 KiB: survives depth 523776 -> 128 bytes of C stack per level
pickle.dumps stack 1024 KiB: survives depth 5008 -> 209 bytes of C stack per level
pickle.dumps stack 8192 KiB: survives depth 40288 -> 208 bytes of C stack per level
pickle.dumps stack 65536 KiB: survives depth 322560 -> 208 bytes of C stack per level
json.dumps stack 1024 KiB: survives depth 10848 -> 97 bytes of C stack per level
json.dumps stack 8192 KiB: survives depth 87232 -> 96 bytes of C stack per level
json.dumps stack 65536 KiB: survives depth 698880 -> 96 bytes of C stack per level
x == x2 stack 1024 KiB: survives depth 9288 -> 113 bytes of C stack per level
x == x2 stack 8192 KiB: survives depth 74752 -> 112 bytes of C stack per level
x == x2 stack 65536 KiB: survives depth 599040 -> 112 bytes of C stack per level
next(map chain) stack 1024 KiB: survives depth 9264 -> 113 bytes of C stack per level
next(map chain) stack 8192 KiB: survives depth 74816 -> 112 bytes of C stack per level
next(map chain) stack 65536 KiB: survives depth 599040 -> 112 bytes of C stack per level
Every kind scales linearly with the stack. Multiply the stack by eight and the depth goes up by eight, so each has a fixed cost per level, and the cost per level is a property of the C code it runs through. The plain Python call, the gdb measurement’s 384 bytes, is the most expensive. The others are C functions recursing into C functions, without an eval loop in between:
repr(list), 128 bytes:PyObject_Reprcalls the list’stp_repr, which callsPyObject_Repron each element.pickle.dumps, 208 bytes: the C pickler’ssave()calls itself through the list’s items.json.dumps, 96 bytes: the C encoder in_jsonrecurses throughencoder_listencode_obj.x == x2, 112 bytes: comparing two nested lists compares their first elements, which compares theirs, throughPyObject_RichCompare.next(map chain), 112 bytes: a chain ofmapobjects, each pulling its next value from the one inside it.
How much C stack recursion takes, and what resuming a generator chain costs
CPython 3.7.0. Left, bytes per level of nesting; right, the cost of one next() through a chain of yield from.
C stack per level, bytes
One next() through a yield-from chain, in microseconds
Hover or focus a bar or a point for details.
Left: the stack limit divided by the deepest nesting that survived it, from the 64 MiB runs; the 1 and 8 MiB runs agree to within two bytes. Right: one run of 20,000 calls per depth; a chain 1,000 deep cannot be resumed at all, because each link re-enters the eval loop and counts towards the recursion limit.
Every one of these went far past 1,000 levels, but only because the child process raised the
recursion limit to ten million. Without that, the first four stop with a RecursionError at
depth 1,000, because PyObject_Repr, the pickler, the JSON encoder and PyObject_RichCompare call
Py_EnterRecursiveCall. The fifth doesn’t.
The recursion the limit never sees
This is map’s __next__ in 3.7, map_next in Python/bltinmodule.c, cut to its essentials:
for (i=0; i < niters; i++) {
PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
PyObject *val = Py_TYPE(it)->tp_iternext(it);
if (val == NULL) {
goto exit;
}
stack[i] = val;
nargs++;
}
result = _PyObject_FastCall(lz->func, stack, nargs);
It calls the inner iterator’s tp_iternext directly, with no Py_EnterRecursiveCall around it.
If the inner iterator is another map, that’s a C function calling itself, and no counter goes up.
So the default recursion limit, which is still 1,000 here, doesn’t help:
import sys
mode, n = sys.argv[1], int(sys.argv[2])
x = iter([1])
for _ in range(n):
x = map(abs, x) # a chain of n map objects, each pulling from the next
if mode == "next":
print(next(x))
elif mode == "del":
del x
print("deleted")
$ python3 unchecked.py next 10000
1
$ python3 unchecked.py next 100000
Segmentation fault
$ python3 unchecked.py del 1000000
deleted
Ten thousand nested maps work, because 10,000 × 112 bytes fit easily in 8 MiB. A hundred
thousand crash the interpreter with the recursion limit at its default, and with no
setrecursionlimit anywhere in the program. Building the chain was legal and each step was
ordinary. Pure Python code, with no ctypes and no extension modules, segfaulted. filter_next
and zip_next, in the same file, call their inner iterators the same way, with no guard (I read
them, I didn’t crash them), and so can any C extension that recurses without the macro.
The guard is only as complete as the C code that remembers to call it.
Freeing deep structures: the trashcan
The last line above deleted a million-deep chain without trouble, and so does this:
x = []
for _ in range(10**6):
x = [x] # a list nested a million deep
del x # freeing it recurses through a million list_dealloc calls...
print("freed a million-deep list")
$ python3 trash.py
freed a million-deep list
Freeing is the most natural recursion of all. Dropping the outer list’s last reference calls
list_dealloc, which drops its reference to the inner list, which calls list_dealloc again, a
million times over. That should overflow the stack, and it doesn’t, because the deallocators of
containers are wrapped in the trashcan macros from Include/object.h:
#define PyTrash_UNWIND_LEVEL 50
#define Py_TRASHCAN_SAFE_BEGIN(op) \
do { \
PyThreadState *_tstate = PyThreadState_GET(); \
if (_tstate->trash_delete_nesting < PyTrash_UNWIND_LEVEL) { \
++_tstate->trash_delete_nesting;
/* The body of the deallocator is here. */
#define Py_TRASHCAN_SAFE_END(op) \
--_tstate->trash_delete_nesting; \
if (_tstate->trash_delete_later && _tstate->trash_delete_nesting <= 0) \
_PyTrash_thread_destroy_chain(); \
} \
...
Deallocations may nest 50 deep. The 51st doesn’t free its object. It puts it on a per-thread list
and returns, and when the nesting unwinds to the outermost deallocator, _PyTrash_thread_destroy_chain
frees the deferred objects, each starting a fresh nesting of at most 50. A million-deep free becomes
twenty thousand short ones, and the stack never holds more than 50 deallocators.
map_dealloc doesn’t use the trashcan. The million-deep map chain could still be freed because
each map holds its inner iterator inside a tuple, and tupledealloc does use it. An extension type
that holds references directly and frees them without the trashcan can still crash on del.
Threads have their own stacks
The 8 MiB ulimit -s applies to the main thread. Every other thread gets its own stack, allocated
when it starts, and its size is set separately:
import sys, threading
sys.setrecursionlimit(10**6)
results = {}
def f(n):
return 0 if n == 0 else f(n - 1) + 1
def run(n):
results[n] = f(n)
print("threading.stack_size() =", threading.stack_size())
threading.stack_size(int(sys.argv[1]) * 1024)
t = threading.Thread(target=run, args=(int(sys.argv[2]),))
t.start(); t.join()
print("thread finished:", results)
$ python3 -u threads.py 8192 15000
threading.stack_size() = 0
thread finished: {15000: 15000}
$ python3 -u threads.py 256 15000
threading.stack_size() = 0
Segmentation fault
$ python3 -u threads.py 256 600
threading.stack_size() = 0
thread finished: {600: 600}
threading.stack_size() returns 0, meaning “the platform’s default”. On Linux, glibc gives new
threads a stack the size of RLIMIT_STACK, so 8 MiB here, and an 8 MiB thread runs 15,000 calls as
well as the main thread does. With 256 KiB the same recursion crashes, and 600 calls (225 KiB) fit.
The -u matters. Without it, the first print sits in Python’s stdout buffer, and the segfault
kills the process before the buffer is flushed, so the program seems to crash before printing
anything. When a crash and its output disagree about what ran first, buffering is the first
suspect.
The default thread stack is a platform decision that leaks straight into Python behaviour. On macOS
a new thread’s default stack is only 512 KiB, small enough that ordinary programs crashed in threads
at depths the main thread handled easily, so CPython’s Python/thread_pthread.h overrides it:
#if defined(__APPLE__) && defined(THREAD_STACK_SIZE) && THREAD_STACK_SIZE == 0
#undef THREAD_STACK_SIZE
#define THREAD_STACK_SIZE 0x500000
#endif
That’s 5 MiB, and FreeBSD gets 4 MiB in the same way. The recursion limit is the same on every platform, and the stack under it is not.
Generators keep their frames off the stack
There is one place where CPython does decouple a Python frame from the C stack: generators. A
generator’s frame lives on the heap like every frame, but unlike a function’s, it stays alive
between calls, with its value stack and its position in the bytecode saved in the frame object.
When a generator yields, its eval loop returns. The C frames that were running it unwind, and
nothing of it is left on the C stack until the next next().
import sys, time, tracemalloc
def counter():
i = 0
while True:
yield i
i += 1
tracemalloc.start()
gens = [counter() for _ in range(100000)]
for g in gens:
next(g) # start every one, and leave it suspended
used = tracemalloc.get_traced_memory()[0]
print("100,000 suspended generators: %.1f MB, %d bytes each" % (used / 1e6, used / 100000))
del gens
def chain(depth):
g = counter()
for _ in range(depth):
g = (lambda inner: (yield from inner))(g)
return g
for depth in (1, 10, 100, 500, 900):
g = chain(depth)
next(g)
n = 20000
t = time.perf_counter()
for _ in range(n):
next(g)
dt = (time.perf_counter() - t) / n
print("yield from chain %4d deep: %8.0f ns per next()" % (depth, dt * 1e9))
g = chain(1000)
try:
next(g)
except RecursionError as e:
print("chain 1000 deep:", e)
$ python3 gens.py
100,000 suspended generators: 54.4 MB, 544 bytes each
yield from chain 1 deep: 171 ns per next()
yield from chain 10 deep: 259 ns per next()
yield from chain 100 deep: 1390 ns per next()
yield from chain 500 deep: 9195 ns per next()
yield from chain 900 deep: 17127 ns per next()
chain 1000 deep: maximum recursion depth exceeded
A hundred thousand generators, each paused in the middle of its loop, cost 544 bytes of heap apiece
(the generator object and its frame) and nothing on the C stack. A hundred thousand paused
function calls would need 37 MiB of stack, which the main thread doesn’t have. This is why
generator-based coroutines, and the asyncio built on them, can keep tens of thousands of tasks
waiting at once.
But resuming one puts it back on the stack. next(g) calls gen_send_ex in
Objects/genobject.c, which calls PyEval_EvalFrameEx on the saved frame: a new eval loop, with
the usual C frames under it. A generator that delegates with yield from is waiting, inside its own
eval loop, on the YIELD_FROM opcode, and resuming it resumes the inner generator from there:
TARGET(YIELD_FROM) {
PyObject *v = POP();
PyObject *receiver = TOP();
int err;
if (PyGen_CheckExact(receiver) || PyCoro_CheckExact(receiver)) {
retval = _PyGen_Send((PyGenObject *)receiver, v);
} else {
So next() on the outermost of a chain of yield froms re-enters every generator’s eval loop on
the way down, one C-level call per link, and then unwinds them all on the way back. That costs
about 19 nanoseconds per link on this machine, so the cost of one next() grows linearly with the
depth of the chain. And because each re-entry goes through _PyEval_EvalFrameDefault’s
Py_EnterRecursiveCall, a chain 1,000 deep can’t be resumed at all. Nothing in it is recursive in
the Python sense. It is just 1,000 generators, each waiting on the next, and resuming them takes
1,000 nested C calls.
What we covered
- A Python-to-Python call in CPython 3.7 is a C call: the eval loop calls
_PyFunction_FastCallKeywords, which callsfunction_code_fastcall, which runs the eval loop again on the new frame. On this build that’s 384 bytes of C stack per call, 320 of them the eval loop’s own frame. - The recursion limit counts entries into the eval loop and into the C functions that opt in with
Py_EnterRecursiveCall. It never measures the stack. The default of 1,000 uses about 375 KiB of an 8 MiB stack. - Raising the limit without raising the stack turns
RecursionErrorinto a segfault, here at about 21,800 calls.faulthandlercan still print the Python traceback, from an alternate signal stack, with nothing butwrite(). - C recursion costs 96 to 208 bytes per level depending on the code path, and every kind scales
linearly with the stack. Some C code, like
map’s__next__in 3.7, never calls the guard, and a chain of 100,000 maps crashes at the default limit. - Deallocation of deep structures is made safe by the trashcan, which defers frees beyond 50 levels. Types that don’t use it are only as safe as what they contain.
- Threads have their own stacks, set by the platform or by
threading.stack_size(), so the same recursion can work in one thread and crash in another. - Generators keep their frames on the heap and nothing on the C stack while suspended, but every
resume re-enters the eval loop, and a
yield fromchain re-enters it once per link.
The next post follows the first field of every object, ob_refcnt: when objects die, what the cycle
collector does about the ones that never reach zero, and why a forked child that only reads its
parent’s data still copies it.
A note on the evidence
What I ran, and where. Everything ran on CPython 3.7.0, built from the v3.7.0 tag with
Ubuntu 18.04’s gcc 7.3.0 and configure’s default flags (-O3 with debug symbols), in a minimal 18.04
userland built from the bionic release archive. gdb is 18.04’s 8.1. I ran it as a chroot on a
64-bit x86 machine, so the kernel was the host’s, not 18.04’s. Stack limits, guard pages and
SIGSEGV work the same way on any recent Linux kernel, but the exact depths at which things crash
depend on how much stack the process has already used when the recursion starts, and that varies a
little between systems. Each script was extracted from this page and run as shown.
The numbers. The 384 bytes per call come from the stack pointers in one gdb run. The
kinds.py depths are bisected to within a tenth of a percent. Each “survives” is one child process
that exited normally, and the bytes per level are the stack limit divided by that depth, so they
include the fixed amount the process used before recursing. That’s why the 1 MiB figures are a
byte or two higher than the 64 MiB ones. The generator timings are from a single run of gens.py
on an otherwise idle machine, with each figure averaged over 20,000 calls. Treat them as the shape
of the curve, not precise costs.
What I trimmed. The gdb listing drops gdb’s two lines about the thread debugging library, and
the faulthandler listing cuts 96 identical File "crash.py", line 5 in f lines at the ....
What I worked out rather than read. That call_function is inlined into the eval loop and that
PyEval_EvalFrameEx’s call became a jump are inferences from the gdb listing: frames at the same
stack pointer as their caller, and one function missing from the chain. I didn’t read the
disassembly. The breakdown of the 384 bytes is subtraction between consecutive stack pointers. That
the million-deep map chain is freed safely because of the tuple in each map is from reading
map_dealloc and tupledealloc, not from a debugger.
What I cited rather than ran. The C quoted here is from the v3.7.0 tag: Python/ceval.c
(_Py_CheckRecursiveCall, PyEval_EvalFrameEx, YIELD_FROM), Include/ceval.h, Objects/call.c,
Objects/genobject.c, Python/bltinmodule.c (map_next, map_dealloc), Objects/tupleobject.c,
Include/object.h (the trashcan), Python/thread_pthread.h, Modules/faulthandler.c and
Python/traceback.c. The macOS thread-stack behaviour is from that source, not from a run on a Mac.
PEP 523’s eval_frame hook is in 3.6 and 3.7. The Stackless and greenlet history is from their own
documentation.
What I’d still change. I measured one build on one machine. A build with different optimisation
or a different compiler gives the eval loop a different frame size, so 384 is this binary’s number,
not CPython’s. A debug build’s frames are much larger. I also only tested map for unguarded
recursion; a systematic search of the C code for recursion without Py_EnterRecursiveCall would
surely find more.
Every Python Call Is a C Call