Subinterpreters with concurrent.interpreters

suggest change

A subinterpreter is a second, independent Python interpreter running inside the same process. Each one has its own sys.modules, its own __main__, its own builtins and, since Python 3.12 (PEP 684), its own GIL. Two subinterpreters running in two OS threads can therefore execute Python code in parallel on two CPU cores, even in the regular (GIL) build of CPython.

CPython has supported subinterpreters in its C API for decades, but Python code could only use them through private modules (_xxsubinterpreters in 3.12, _interpreters in 3.13). Python 3.14 adds the public concurrent.interpreters module (PEP 734) and concurrent.futures.InterpreterPoolExecutor on top of it.

Where they fit compared with the other options:

threads subinterpreters processes (multiprocessing)
CPU-bound Python code in parallel no (GIL build) yes yes
Memory shared by everyone one process, but objects are not shared separate address spaces
Isolation none: all globals shared separate modules, globals, sys state complete
Passing data any object, by reference copied (shareable types, or pickle) copied (pickle)
Start cost tiny about the same as a process (measured below) starting a process
C extensions all only those that support subinterpreters all

All examples were run with Python 3.14.4 on Linux (the regular GIL build). The scripts are meant to be saved to a file and run with python3.14 script.py; some of them depend on that, as explained below. For the classic tools see The threading module, The multiprocessing module and Python concurrency. The free-threaded build of CPython (no GIL at all) is a different approach to the same problem and is covered in its own article, "The free-threaded build (no GIL)".

Creating an interpreter and running code

interpreters.create() returns an Interpreter object. exec() runs source code in that interpreter's __main__ module, and close() destroys it:

from concurrent import interpreters

interp = interpreters.create()
print(interp)
print(interpreters.list_all())

interp.exec("x = 40")
interp.exec("x += 2; print('x in subinterpreter:', x)")

x = "main's x"
print("x in main:", x)

interp.close()
print(interpreters.list_all())
Interpreter(1)
[Interpreter(0), Interpreter(1)]
x in subinterpreter: 42
x in main: main's x
[Interpreter(0)]

Things to notice:

Besides a string, exec() also accepts a function that takes no arguments, or a code object:

from concurrent import interpreters

def hello():
    import sys
    print("hello from", sys.implementation.name)

interp = interpreters.create()
interp.exec(hello)                  # a function with no arguments
interp.exec(hello.__code__)         # or a code object
interp.close()
hello from cpython
hello from cpython

Each interpreter is isolated

A new interpreter starts from scratch: it hasn't imported what the main interpreter imported and has its own copy of sys. Changing sys in one interpreter doesn't affect the others:

import sys
from concurrent import interpreters

import json            # imported in main only
sys.path.append("/added/in/main")

interp = interpreters.create()
interp.exec("""
import sys
print("json loaded:", "json" in sys.modules)
print("path tail:", sys.path[-1])
sys.setrecursionlimit(50)
""")
print("main json loaded:", "json" in sys.modules)
print("main recursion limit:", sys.getrecursionlimit())
interp.close()
json loaded: False
path tail: /usr/lib/python3/dist-packages
main json loaded: True
main recursion limit: 1000

The subinterpreter computed its own sys.path (it doesn't see the entry appended in main), and its setrecursionlimit() call didn't change main's limit. Every module you need is imported again inside each interpreter, and module-level globals, caches and singletons exist once per interpreter.

What is shared is the process: file descriptors, the current directory, environment variables, signal handlers (only the main interpreter can install them) and memory. os.chdir() in one interpreter changes the directory for all of them.

Passing values with prepare_main

Objects can't simply be handed from one interpreter to another, because each interpreter has its own object allocator, its own reference counts and its own GIL. Values are passed by creating an equivalent object in the other interpreter. prepare_main() binds such values to names in the interpreter's __main__:

from concurrent import interpreters

interp = interpreters.create()
interp.prepare_main(name="report.csv", rows=3, sizes=(10, 20, 30))
interp.exec("print(name, rows, sum(sizes))")

try:
    interp.prepare_main(config={"debug": True})
except Exception as e:
    print(type(e).__name__, "-", e)
interp.close()
report.csv 3 60
NotShareableError - {'debug': True} does not support cross-interpreter data

prepare_main() only accepts shareable objects. interpreters.is_shareable() tells you whether an object is one:

from concurrent import interpreters

for v in [1, 2.5, "s", b"b", None, True, (1, "a"), [1], {"a": 1},
          memoryview(b"x"), interpreters.create_queue()]:
    print(f"{type(v).__name__:<10} {interpreters.is_shareable(v)}")
int        True
float      True
str        True
bytes      True
NoneType   True
bool       True
tuple      True
list       False
dict       False
memoryview True
Queue      True

Immutable built-in values (and tuples of them) are copied efficiently. memoryview and Queue are special: the other interpreter gets an object that refers to the same underlying buffer or queue. Lists, dicts and instances of your own classes aren't shareable; call() and queues fall back to pickling them, as shown below.

Errors: ExecutionFailed

An exception in the subinterpreter can't be raised as-is in the caller, since the exception object belongs to the other interpreter. Instead you get interpreters.ExecutionFailed, which carries a summary in excinfo:

from concurrent import interpreters

interp = interpreters.create()
try:
    interp.exec("""
def parse(s):
    return int(s)
parse("abc")
""")
except interpreters.ExecutionFailed as e:
    print("caught:", type(e).__name__)
    print("type:", e.excinfo.type.__name__)
    print("msg:", e.excinfo.msg)
    print("---")
    print(e)
interp.close()
caught: ExecutionFailed
type: ValueError
msg: invalid literal for int() with base 10: 'abc'
---
ValueError: invalid literal for int() with base 10: 'abc'

Uncaught in the interpreter:

Traceback (most recent call last):
  File "<script>", line 4, in <module>
  File "<script>", line 3, in parse
ValueError: invalid literal for int() with base 10: 'abc'

The interpreter itself is still usable after a failure; only that one exec() call failed.

Calling functions with call()

interp.call(func, *args, **kwargs) runs a function in the interpreter and returns its result. That's usually nicer than building source strings:

from concurrent import interpreters

def count_primes(limit):
    count = 0
    for n in range(2, limit):
        if all(n % d for d in range(2, int(n ** 0.5) + 1)):
            count += 1
    return count

def stats(values, scale):
    return {"min": min(values) * scale, "max": max(values) * scale}

interp = interpreters.create()
print(interp.call(count_primes, 10_000))
print(interp.call(stats, [3, 1, 4, 1, 5], scale=10))
print(interp.call(lambda x: x * 2, 21))
interp.close()
1229
{'min': 10, 'max': 50}
42

The list argument and the dict result aren't shareable, so they were pickled and unpickled on the other side. The functions themselves are sent in one of two ways:

  1. A stateless function is copied directly. Stateless means it uses only its arguments and builtins: no closure, no default argument values and no reads of module globals. All three functions above are stateless, and so is the lambda.
  2. Anything else is pickled, and pickle sends functions by reference: module name plus function name. The subinterpreter then imports that module and looks up the function.

The second case has an important consequence for functions defined in the script you run. To find __main__.my_func, the subinterpreter imports your script as a module, which runs its top-level code again, exactly like multiprocessing does with the spawn start method. So scripts that use subinterpreters need the if __name__ == "__main__": guard:

from concurrent import interpreters

print("module level runs in", interpreters.get_current())

counter = 0

def bump(step=1):          # default value + global: not "stateless"
    global counter
    counter += step
    return counter

if __name__ == "__main__":
    interp = interpreters.create()
    print(interp.call(bump), interp.call(bump), interp.call(bump, 10))
    print("main counter:", counter)
    interp.close()
module level runs in Interpreter(0)
module level runs in Interpreter(1)
1 2 12
main counter: 0

The top-level print() ran twice, once in each interpreter. The counter that bump() changes is the subinterpreter's own copy of the module global, which persists between calls (1, 2, 12) while main's counter stays 0.

Without the guard, the re-imported script would try to create interpreters itself; in practice the call fails with a confusing error ending in NotShareableError: object could not be unpickled caused by AttributeError: module '__main__' has no attribute 'bump'. The same rule applies to the InterpreterPoolExecutor examples below. Putting worker functions in a separate module avoids the problem entirely.

A closure can't be sent either way: interp.call(make_adder(5), 1) raises NotShareableError: only stateless functions are shareable.

Running in parallel: call_in_thread

exec() and call() block the calling thread. To run several interpreters at the same time, call them from several threads. call_in_thread() does this for you: it starts a threading.Thread that runs the function in the interpreter and returns the thread. The return value and any exception are discarded, so it's meant for workers that report back through a queue (next section).

Here's a CPU-bound benchmark: the same function four times, sequentially, in four threads of one interpreter, and in four threads with an interpreter each:

import os
import threading
import time
from concurrent import interpreters

def count_primes(limit):
    count = 0
    for n in range(2, limit):
        if all(n % d for d in range(2, int(n ** 0.5) + 1)):
            count += 1
    return count

def timed(label, fn):
    start = time.perf_counter()
    fn()
    print(f"{label:<26} {time.perf_counter() - start:.2f}s")

if __name__ == "__main__":
    print("cpu_count:", os.cpu_count())
    JOBS, LIMIT = 4, 200_000

    timed("sequential", lambda: [count_primes(LIMIT) for _ in range(JOBS)])

    def threads_one_interp():
        ts = [threading.Thread(target=count_primes, args=(LIMIT,))
              for _ in range(JOBS)]
        for t in ts: t.start()
        for t in ts: t.join()
    timed("4 threads, 1 interpreter", threads_one_interp)

    interps = [interpreters.create() for _ in range(JOBS)]
    def threads_many_interps():
        ts = [interp.call_in_thread(count_primes, LIMIT) for interp in interps]
        for t in ts: t.join()
    timed("4 threads, 4 interpreters", threads_many_interps)
    for interp in interps:
        interp.close()
cpu_count: 24
sequential                 1.40s
4 threads, 1 interpreter   2.06s
4 threads, 4 interpreters  0.57s

The numbers vary from run to run (this machine was busy with other work), but the pattern is stable: plain threads in one interpreter take as long as the sequential version or longer, because only one of them can hold the GIL at a time. With one interpreter per thread, each thread has its own GIL and the four jobs actually run in parallel.

Cross-interpreter queues

interpreters.create_queue() creates a queue that can be passed to other interpreters (through call() arguments, prepare_main() or another queue). Every interpreter that has it refers to the same queue. Its API is like queue.Queue: put(), get(), put_nowait(), get_nowait(), empty(), full(), qsize(), with timeouts.

A typical pattern is a long-lived worker interpreter that reads jobs from one queue and writes results to another, with None as a stop signal:

from concurrent import interpreters

def worker(tasks, results):
    while (word := tasks.get()) is not None:
        results.put((word, len(word), word.upper()))
    results.put(None)

if __name__ == "__main__":
    tasks = interpreters.create_queue()
    results = interpreters.create_queue()

    interp = interpreters.create()
    t = interp.call_in_thread(worker, tasks, results)

    for w in ["alpha", "beta", "gamma"]:
        tasks.put(w)
    tasks.put(None)

    while (item := results.get()) is not None:
        print(item)
    t.join()
    interp.close()
('alpha', 5, 'ALPHA')
('beta', 4, 'BETA')
('gamma', 5, 'GAMMA')

worker only uses its arguments, so it is a stateless function and is sent as is.

What you get out of a queue is a copy, except for the special shareable types. Non-shareable objects are pickled, and memoryview gives real shared memory:

from concurrent import interpreters

q = interpreters.create_queue()
data = {"user": "ann", "tags": ["a", "b"]}
q.put(data)              # not shareable: falls back to pickle
copy = q.get()
print(copy, copy == data, copy is data)

buf = bytearray(b"hello")
interp = interpreters.create()
interp.prepare_main(view=memoryview(buf))
interp.exec("view[0] = ord('J')")
print(buf)
interp.close()

try:
    q.get(timeout=0.1)
except interpreters.QueueEmpty:
    print("QueueEmpty after timeout")
{'user': 'ann', 'tags': ['a', 'b']} True False
bytearray(b'Jello')
QueueEmpty after timeout

The subinterpreter wrote into the main interpreter's bytearray through the memoryview. That's the cheapest way to move large binary data (images, arrays) between interpreters, but you are responsible for synchronizing access to the buffer, for example by handing it back and forth through a queue.

QueueEmpty and QueueFull are raised by the non-blocking calls and on timeout. If the interpreter that put an item is destroyed before the item is read, get() by default returns a placeholder instead (create_queue(unbounditems=...) and put(..., unbounditems=...) change this).

InterpreterPoolExecutor

For most "run this function on many inputs in parallel" jobs you don't need to manage interpreters yourself. concurrent.futures.InterpreterPoolExecutor (3.14) has the same API as ThreadPoolExecutor and ProcessPoolExecutor; each worker thread owns its own interpreter:

import os
import time
from concurrent.futures import (InterpreterPoolExecutor, ProcessPoolExecutor,
                                ThreadPoolExecutor)

def count_primes(limit):
    count = 0
    for n in range(2, limit):
        if all(n % d for d in range(2, int(n ** 0.5) + 1)):
            count += 1
    return count

if __name__ == "__main__":
    print("cpu_count:", os.cpu_count())
    limits = [200_000] * 8
    for cls in (ThreadPoolExecutor, InterpreterPoolExecutor, ProcessPoolExecutor):
        start = time.perf_counter()
        with cls(max_workers=4) as pool:
            results = list(pool.map(count_primes, limits))
        print(f"{cls.__name__:<24} {time.perf_counter() - start:.2f}s  {results[0]}")
cpu_count: 24
ThreadPoolExecutor       3.61s  17984
InterpreterPoolExecutor  1.21s  17984
ProcessPoolExecutor      1.58s  17984

Switching between the three is a one-word change. For CPU-bound pure Python code the interpreter pool and the process pool are in the same league (which one wins changed from run to run here), and both beat threads.

Exceptions are re-raised in the caller as the original exception type, with the ExecutionFailed as the cause, so except ValueError works as usual:

from concurrent.futures import InterpreterPoolExecutor
from concurrent import interpreters

PREFIX = ">> "                       # a global: the function isn't stateless

def label(word):
    return f"{PREFIX}{word} (interp {interpreters.get_current().id})"

def parse(s):
    return int(s)

if __name__ == "__main__":
    with InterpreterPoolExecutor(max_workers=2) as pool:
        for line in pool.map(label, ["a", "b", "c"]):
            print(line)
        fut = pool.submit(parse, "12x")
        try:
            fut.result()
        except ValueError as e:
            print(type(e).__name__, "-", e)
            print("cause:", type(e.__cause__).__name__)
>> a (interp 1)
>> b (interp 2)
>> c (interp 1)
ValueError - invalid literal for int() with base 10: '12x'
cause: ExecutionFailed

Which worker gets which item depends on timing.

initializer and per-interpreter state

initializer and initargs run a function once in each worker interpreter, typically to load configuration or open a resource. There's a trap here: the initializer must end up updating the same module the task functions read from. Put both in a module, and keep the state in a module-level container:

# greeter.py
from concurrent import interpreters

_state = {}

def setup(name):
    _state["greeting"] = f"hi from {name}"

def greet(n):
    return f"{_state['greeting']} #{n} in interp {interpreters.get_current().id}"
# main.py
from concurrent.futures import InterpreterPoolExecutor
import greeter

if __name__ == "__main__":
    with InterpreterPoolExecutor(max_workers=2, initializer=greeter.setup,
                                 initargs=("worker",)) as pool:
        for line in pool.map(greeter.greet, range(3)):
            print(line)
hi from worker #0 in interp 2
hi from worker #1 in interp 2
hi from worker #2 in interp 2

Why the dict instead of global greeting; greeting = ...? A setup() that only assigns a global (and reads nothing else) counts as stateless, so it is copied directly and runs against the subinterpreter's __main__ namespace. greet() reads a global, so it is pickled by reference and runs in the imported greeter module. They would see different globals, and greet() would find the value unset (None, or a NameError). Reading _state makes setup() non-stateless, so both functions run in greeter.

Startup cost

Creating an interpreter means initializing a fresh runtime state and importing the startup modules again. It's far more expensive than starting a thread:

import multiprocessing as mp
import threading
import time
from concurrent import interpreters

def noop():
    pass

def per_item(label, n, start_one):
    t = time.perf_counter()
    for _ in range(n):
        start_one()
    ms = (time.perf_counter() - t) / n * 1000
    print(f"{label:<28} {ms:7.2f} ms each")

def thread_once():
    t = threading.Thread(target=noop); t.start(); t.join()

def interp_once():
    interp = interpreters.create()
    interp.exec("pass")
    interp.close()

def process_once():
    p = mp.Process(target=noop); p.start(); p.join()

if __name__ == "__main__":
    print("start method:", mp.get_start_method())
    per_item("thread start + join", 200, thread_once)
    per_item("interpreter create + close", 50, interp_once)
    per_item("process start + join", 20, process_once)
start method: forkserver
thread start + join             0.16 ms each
interpreter create + close     11.94 ms each
process start + join           12.30 ms each

In 3.14 an interpreter costs about as much to create as a process started via the default forkserver method on Linux. Every module a task uses must also be imported in each interpreter. Create interpreters once and reuse them, as InterpreterPoolExecutor does, rather than one per task.

C extension modules

An extension module can only be imported in a subinterpreter if it declares support for it (multi-phase initialization from PEP 489, with a Py_mod_multiple_interpreters slot that allows a per-interpreter GIL). Most of the standard library does, but not all of it:

from concurrent import interpreters

interp = interpreters.create()
for mod in ["sqlite3", "decimal", "ssl", "zlib", "readline", "curses"]:
    try:
        interp.exec(f"import {mod}")
        print(f"{mod:<8} ok")
    except interpreters.ExecutionFailed as e:
        print(f"{mod:<8} {e.excinfo.type.__name__}: {e.excinfo.msg}")
interp.close()
sqlite3  ok
decimal  ok
ssl      ok
zlib     ok
readline ImportError: module readline does not support loading in subinterpreters
curses   ImportError: module _curses does not support loading in subinterpreters

Third-party extensions are a bigger problem: many popular packages with C code don't support subinterpreters yet. Check before you design around them: if the import fails in a subinterpreter, you need processes instead.

When to use subinterpreters

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents