GitHub

interpreter_pool

API reference for interpreter_pool.

Running pure functions in subinterpreters (Python 3.14's concurrent.interpreters), each with its own GIL.

Effect has nothing like it: JavaScript has no interpreters to spread work over (a Web Worker is closer to a ProcessWorker). On the GIL build, Python code in fx.blocking takes turns with every other thread; in a subinterpreter it runs on its own core, without the start-up and memory of a process.

Provide the pool with layer(size) and call a function with call::

total = yield from interpreter_pool.call(checksum, data)

program.pipe(fx.provide(interpreter_pool.layer(size=4)))

The function, its arguments and its result cross into another interpreter, and the function sees none of the caller's state. A function reading no globals and closing over nothing (a lambda too) crosses as its code; any other crosses by reference, so it must be a module-level function. Each subinterpreter starts with the program's sys.path and imports the function's module, and what that imports, the first time it runs something from it. For a function of the script you ran, that is the script itself, run again: without an if __name__ == "__main__": guard, its own fx.run_* dies there, and the call dies with MainScriptRerunError. Arguments and results must pickle.

A raised exception comes back as a defect (call) or a failure (try_call): the exception itself when it pickles, else the concurrent.interpreters.ExecutionFailed that summarises it. Python cannot stop a call that has started, so interrupting the fiber abandons it, as fx.blocking does: a call still queued is withdrawn, a running one goes on until it returns. Releasing the layer waits for every interpreter to close, an abandoned call's once that call returns, so no interpreter outlives its pool; it dies if one would not close (something else closed it).

concurrent.interpreters is new in Python 3.14: on 3.13 building the layer dies with InterpretersUnavailableError.

Re-exports

Classes

Functions

layer

layer(size=None) -> Layer[InterpreterPool]

A pool of up to size subinterpreters (one per CPU by default), each started on first need; releasing the layer closes them, waiting for abandoned calls to return. Dies with InterpretersUnavailableError before Python 3.14.

ParameterTypeDescription
sizeint | None = None

Returns Layer[InterpreterPool]

def layer(size: int | None = None) -> Layer[InterpreterPool]:
    """A pool of up to ``size`` subinterpreters (one per CPU by default),
    each started on first need; releasing the layer closes them, waiting
    for abandoned calls to return. Dies with
    ``InterpretersUnavailableError`` before Python 3.14."""
    if size is not None and size < 1:
        raise ValueError(f"an interpreter pool needs at least one interpreter, got {size}")
    count = size or os.cpu_count() or 1

    def make() -> InterpreterPoolService:
        return InterpreterPoolService(_Workers(_load(), count))

    def release(pool: InterpreterPoolService, _: Exit[Any, Any]) -> Effect[None]:
        def register(resume: Callable[[Effect[None]], None]) -> None:
            def quiet(defects: tuple[BaseException, ...]) -> None:
                if defects:
                    resume(fail_cause(reduce(operator.add, map(cause_.die, defects))))
                else:
                    resume(_VOID)

            pool._workers.close(quiet)

        return os_wait(register, waits_for="work")

    return layer_.effect(InterpreterPool, acquire_release(sync(make), release))

call

call[*Ts, A](fn, *args) -> Effect[A, Never, InterpreterPool]

fn(*args) on the provided pool; a raised exception is a defect.

ParameterTypeDescription
fnCallable[[*Ts], A]
args*Ts = ()

Returns Effect[A, Never, InterpreterPool]

def call[*Ts, A](fn: Callable[[*Ts], A], *args: *Ts) -> Effect[A, Never, InterpreterPool]:
    """``fn(*args)`` on the provided pool; a raised exception is a defect."""
    return InterpreterPool().flat_map(lambda pool: pool.call(fn, *args))

try_call

try_call[*Ts, A](fn: Callable[[*Ts], A], *args: *Ts = ()) -> Effect[A, UnknownError, InterpreterPool]
try_call[*Ts, A, E](fn: Callable[[*Ts], A], *args: *Ts = (), catch: Callable[[Exception], E]) -> Effect[A, E, InterpreterPool]

call on the provided pool, mapping a raised exception to a typed error with catch, or to an UnknownError.

ParameterTypeDescription
fn
args= ()
catch= None
@overload
def try_call[*Ts, A](
    fn: Callable[[*Ts], A], *args: *Ts
) -> Effect[A, UnknownError, InterpreterPool]: ...
@overload
def try_call[*Ts, A, E](
    fn: Callable[[*Ts], A], *args: *Ts, catch: Callable[[Exception], E]
) -> Effect[A, E, InterpreterPool]: ...
def try_call(
    fn: Callable[..., Any], *args: object, catch: Callable[[Exception], Any] | None = None
) -> Effect[Any, Any, InterpreterPool]:
    """``call`` on the provided pool, mapping a raised exception to a typed
    error with ``catch``, or to an ``UnknownError``."""
    if catch is None:
        return InterpreterPool().flat_map(lambda pool: pool.try_call(fn, *args))
    return InterpreterPool().flat_map(lambda pool: pool.try_call(fn, *args, catch=catch))