Skip to main content

Flexexecutor

Testing Package version Python

Flexexecutor provides executors that can automatically scale the number of workers up and down.

Overview

Flexexecutor implements several subclasses of concurrent.futures.Executor. Like the built-in ThreadPoolExecutor and ProcessPoolExecutor, they create multiple workers to execute tasks concurrently. Additionally, it can shut down idle workers to save resources. These subclasses are:

  • ThreadPoolExecutor - thread concurrency, same name as the built-in class and can be a in-place replacement.
  • AsyncPoolExecutor - coroutine concurrency. Note that in flexexecutor's implementation, all coroutines are executed in a dedicated worker thread.
  • ProcessPoolExecutor - process concurrency with idle-worker shutdown and max_tasks_per_child recycling, API-compatible with the built-in class.
  • InterpreterPoolExecutor - subinterpreter concurrency on Python 3.14+.

Features

  • Supports various concurrency modes: threads, processes and coroutines.
  • Automatically shut down idle workers to save resources.
  • Single file design, keeps the code clean and easy for hackers to directly take away and add more features.

Installation

Flexexecutor is available on PyPI:

pip install flexexecutor

Usage

ThreadPoolExecutor

from flexexecutor import ThreadPoolExecutor


def task(i):
    import time

    print(f"task {i} started")
    time.sleep(1)

if __name__ == "__main__":
    with ThreadPoolExecutor(
        # 1024 is the default value of max_workers, since workers are closed if they are
        # idle for some time, you can set it to a big value to get better short-term
        # performance.
        max_workers=1024,
        # Timeout for idle workers.
        idle_timeout=60.0,
        # These parameters are given for compatibility with the built-in
        # `ThreadPoolExecutor`, I don't use them very often, do you?
        thread_name_prefix="Task",
        initializer=None,
        initargs=(),
    ) as executor:
        for i in range(1024):
            executor.submit(task, i)

AsyncPoolExecutor

AsyncPoolExecutor runs all coroutines in a dedicated worker thread with its own event loop. Note that tasks are not executed in the thread where they are submitted — they are sent to the internal worker thread for execution.

from flexexecutor import AsyncPoolExecutor


async def task(i):
    import asyncio

    print(f"task {i} started")
    await asyncio.sleep(1)

if __name__ == "__main__":
    # AsyncPoolExecutor behaves just like ThreadPoolExecutor except it only accepts
    # coroutine functions.
    with AsyncPoolExecutor(
        # Default value of max_workers is huge, if you don't like it, set it smaller.
        max_workers=1024,
        # Idle timeout for the working thread.
        idle_timeout=60.0,
        # These parameters are given for compatibility with the built-in
        # `ThreadPoolExecutor`, I don't use them very often, do you?
        thread_name_prefix="Task",
        initializer=None,
        initargs=(),
    ) as executor:
        for i in range(1024):
            executor.submit(task, i)

ProcessPoolExecutor

Flexexecutor implements its own ProcessPoolExecutor, derived from CPython 3.15. It keeps the standard API and adds idle-worker shutdown.

from flexexecutor import ProcessPoolExecutor

if __name__ == "__main__":
    with ProcessPoolExecutor(
        # Maximum number of worker processes.
        max_workers=4,
        # Exit a worker after it has been idle for this many seconds.
        # None or a negative value disables idle shutdown.
        idle_timeout=60.0,
        # Replace a worker after it has completed this many tasks.
        # None means workers live until the executor is shut down.
        max_tasks_per_child=None,
    ) as executor:
        print(executor.submit(pow, 2, 10).result())

idle_timeout defaults to 60 seconds. To replace workers because of the workload rather than idleness, use max_tasks_per_child; the native default is None, which keeps workers alive for the lifetime of the executor.

When idle_timeout is active and mp_context is not supplied, flexexecutor selects a non-fork start method so that the manager thread can safely start a replacement worker: forkserver on Unix outside macOS, spawn on Windows and macOS. On Python 3.11-3.13 this differs from the standard library's default fork on Linux. Passing an explicit fork context together with an active idle_timeout raises ValueError; pass idle_timeout=None if you need fork. initializer and initargs must therefore be pickleable.

Workers are reused between tasks. Module-level state, globals and initializer state changed by one task stay in that worker for the next task; only task arguments and results are pickled. Set max_tasks_per_child=1 to get a fresh process for every task.

On Python 3.14+, the standard map(buffersize=...), terminate_workers() and kill_workers() APIs are also available.

InterpreterPoolExecutor

InterpreterPoolExecutor is available on Python 3.14+ and runs each worker in a subinterpreter, giving every worker its own GIL. It is useful for CPU-bound Python code without process startup or separate address spaces.

from flexexecutor import InterpreterPoolExecutor

if __name__ == "__main__":
    with InterpreterPoolExecutor(
        max_workers=4,
        idle_timeout=60.0,
        max_tasks_per_child=None,
    ) as executor:
        print(executor.submit(pow, 2, 10).result())

Tasks, arguments and return values are pickled across the interpreter boundary. Each interpreter has isolated modules and globals; an initializer runs once per worker interpreter. max_tasks_per_child and idle_timeout work the same way as in the process executor. C extensions must support subinterpreters; extensions that do not may fail or leak. Interpreters share the parent process address space, so a crash still crashes the process.

Nested executors

Executors can be nested. Each layer must create a new executor instance; do not submit from a worker back to the same executor, because that can deadlock.

The test suite covers all 84 ordered paths of T (thread), P (process), I (interpreter) and A (async), with an outer-to-inner path length from one to three. On Python 3.14+, all paths work except those where I appears before a P: IP, TIP, PIP, ITP, IPT, IPP, IPI, IPA, IIP, IAP and AIP. In those paths the inner ProcessPoolExecutor fails with BrokenProcessPool.

This is a CPython subinterpreter limitation, not an idle-worker issue. The standard library's ProcessPoolExecutor fails the same way: multiprocessing starts a daemon queue feeder thread on the first task, and subinterpreters disable daemon threads. The affected tests are marked as expected failures. On Python 3.11-3.13, InterpreterPoolExecutor is unavailable; the 39 thread, process and async paths still work.

Metadata

Release files for flexexecutor 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flexexecutor 0.1.0
File Size Uploaded Provenance Actions
flexexecutor-0.1.0.tar.gz 30.5 kB Without provenance Details for flexexecutor-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flexexecutor 0.1.0
File Interpreter ABI Platform Actions
flexexecutor-0.1.0-py3-none-any.whl Python 3 none any Details for flexexecutor-0.1.0-py3-none-any.whl

Total release size: 64.8 kB

Release files / flexexecutor-0.1.0.tar.gz

Download URL flexexecutor-0.1.0.tar.gz
Size 30.5 kB
Tags Source
SHA-256 checksum
How to use checksums
c487d9f10ea6f0a24796ad7bbf49a5d1cab410251150b39727377aea465f581b
BLAKE2b-256 checksum
How to use checksums
a9243acdb8d2db300f08e90effcc4ef1af7346003e3a75811fa0a6be91031c9b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via pdm/2.29.7 CPython/3.15.2 Linux/7.0.0-1020-azure

Release files / flexexecutor-0.1.0-py3-none-any.whl

Download URL flexexecutor-0.1.0-py3-none-any.whl
Size 34.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
76907e79c42186d4d2dd6335baf078d471459b3eb17d5612c44c0862eddf81a5
BLAKE2b-256 checksum
How to use checksums
c889aec945752103c9f3bbca8e1fa8e5c2e249de52121ad4f1e7aa976f665d9d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via pdm/2.29.7 CPython/3.15.2 Linux/7.0.0-1020-azure

Security for flexexecutor 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page