Skip to main content

strand

Easy creation of non-blocking tasks: run a function in a thread or a process and get on with your work.

pip install strand

Basic Usage

from strand import ThreadTaskrunner 

def handle_chunk(chunk):
    print(f'got a chunk: {chunk}')

def long_blocking_function(total_size, chunk_size):
    if total_size < chunk_size:
        total_size = chunk_size    
    big_list = range(total_size)
    return (big_list[chunk_size * n:chunk_size * (n + 1)] for n in range(total_size / chunk_size))

# instantiate the runner
runner = ThreadTaskrunner(long_blocking_function, on_iter=handle_chunk)

# call the runner with the arguments to pass to the function
# the function will run in a thread
runner(1e8, 1e3)

Warning

In order to use threads or multiprocessing safely, you need to understand the constraints of those features. A thorough discussion of how not to shoot yourself in the foot is outside the scope of this library. Future versions of this library may include strong input checks to prevent more common mistakes, with optional arguments to override checks if necessary. This version does not contain any safety controls yet.

Decorator syntax

from strand import as_task 

def handle_chunk(chunk):
    print(f'got a chunk: {chunk}')

@as_task(on_iter=handle_chunk)
def long_blocking_function(total_size, chunk_size):
    if total_size < chunk_size:
        total_size = chunk_size    
    big_list = range(total_size)
    return (big_list[chunk_size * n:chunk_size * (n + 1)] for n in range(total_size / chunk_size)) 

# the function will run in a thread
long_blocking_function(1e8, 1e3)

The as_task decorator takes a taskrunner target as its first argument. The argument may be a Taskrunner subclass or a string. The allowed values are:

  • 'thread' (default): ThreadTaskrunner
  • 'process': MultiprocessTaskrunner
  • 'coroutine': CoroutineTaskrunner
  • 'store': StoreTaskWriter
  • 'sync': Taskrunner (just runs the function and returns the value synchronously without any change of context)

Base API

class strand.Taskrunner(func: Callable, *init_args, on_iter: Optional[Callable] = None, on_end: Optional[Callable] = None, on_error: Optional[Callable] = None, **init_kwargs)

The base Taskrunner class and its subclasses take a callable as their first init argument. Taskrunners implement __call__ and pass arguments to their stored callable when called.

The init_args and init_kwargs are also passed to func when called (as func(*init_args, *args, **init_kwargs, **kwargs), allowing a Taskrunner instance to serve as a partial invocation of a function.

The optional arguments on_iter, on_end, and on_error are callbacks to be invoked when applicable.

  • If on_iter is provided and func returns an iterable, on_iter will be called with every item in the iterable after func returns.
  • If on_end is provided, it will be called with the return value of func. Otherwise, for most subclasses, the return value of func will be discarded.
  • If on_error is provided, it will be called with any exceptions thrown within Taskrunner.__call__. Otherwise, the taskrunner will re-throw exceptions after catching them.

Subclasses

ThreadTaskrunner

class strand.ThreadTaskrunner(func: Callable, *init_args, on_iter: Optional[Callable], on_end: Optional[Callable], on_error: Optional[Callable])

Runs func in a thread. Simple as that.

MultiprocessTaskrunner

class strand.MultiprocessTaskrunner(func: Callable, *init_args, on_iter: Optional[Callable], on_end: Optional[Callable], on_error: Optional[Callable], **init_kwargs)

Runs func in a new process. Has a separate set of caveats from multi-threading.

CoroutineTaskrunner

class strand.MultiprocessTaskrunner(func: Callable, *init_args, on_iter: Optional[Callable], on_end: Optional[Callable], on_error: Optional[Callable]), yield_on_iter: Optional[bool], **init_kwargs)

Runs func in a coroutine. Requires the calling context to already be within a coroutine in order to derive much benefit. Not fully fleshed out yet.

If yield_on_iter is True, adds await asyncio.sleep(0) between every iteration, to yield control back to the coroutine scheduler.

StoreTaskWriter

class strand.StoreTaskWriter(func: Callable, store: Mapping, *init_args, on_iter: Optional[Callable], on_end: Optional[Callable], on_error: Optional[Callable]), read_store=None, pickle_func=False, get_result=None, **init_kwargs)

When called, serializes func along with its arguments and passes them to store for storage, where it may then be found by a StoreTaskReader or any other consumer in another place and time.

The argument read_store takes a store that should expect to find values written in store and immediately instantiates a StoreTaskReader instance that starts polling read_store for items in a new thread.

If pickle_func is true, func will be serialized with dill for storage. Otherwise, only func.__name__ will be stored (which should be enough for most use cases where the store reader knows as much as it should about the writer).

StoreTaskReader (Not yet implemented)

class strand.StoreTaskReader(store: Mapping, get_task_func: Optional[Callable])

Accepts an argument store that should be a store of tasks to run.

The argument get_task_func should be a callable that resolves an item from the store into a function to call. If get_task_func is not present, the reader will assume that store[some_key]['func'] is a pickled callable and will automatically attempt to unpickle it with dill before calling it with *store[some_key]['args'], **store[some_key]['kwargs']

Calling the listen method on a StoreTaskReader instance will cause it to start an infinite loop in a new thread to poll the store for new tasks and execute them.

reader = StoreTaskReader(task_store)

reader.listen()

Future

  • Taskrunners that dispatch tasks to network targets (e.g. MQTT, RabbitMQ, Redis)
    • Could just be a special case of store reader/writer
  • Utilities for dispatching multiple tasks at once
  • More customizable serialization
  • Customize context for autogenerated StoreTaskReader when StoreTaskWriter is initialized with read_store
  • Thorough/correct handling of coroutines (could be a whole library unto itself)
  • Safety checking

Asynchronous computation with status tracking: see au

This README used to carry the documentation of a second framework, strand.au (decorator-based async computations with pluggable stores and backends, from strand.au import async_compute). That module is not part of strand: there is no strand/au. The framework lives on as its own package, au (from au import async_compute), which has its own documentation.

Process Management Utility

The run_process context manager allows you to launch a process for the duration of a context, with optional readiness checks and automatic cleanup. It is useful for ensuring a background service or worker is running for the duration of a test or script.

Example:

from strand.taskrunning.utils import run_process
import time

def my_worker():
    print("Worker started!")
    time.sleep(5)
    print("Worker exiting!")

with run_process(my_worker, process_name="my_worker", is_ready=0.2, timeout=5) as proc:
    print(f"Process running: {proc.is_alive()}")
    # Do work while the process is running
    time.sleep(1)
# After the context, the process is cleaned up

You can also use the process_already_running argument to avoid launching a process if an external check indicates it is already running:

def is_service_running():
    # Return True if the service is already running
    ...

with run_process(my_worker, process_already_running=is_service_running) as proc:
    if proc is None:
        print("Service was already running!")
    else:
        print("Launched new worker process!")

Metadata

Release files for strand 0.1.10

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

Source distribution (sdist)

Source distribution for strand 0.1.10
File Size Uploaded Provenance Actions
strand-0.1.10.tar.gz 15.4 kB Without provenance Details for strand-0.1.10.tar.gz

Built distribution (wheel)

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

Total release size: 34.3 kB

Release files / strand-0.1.10.tar.gz

Download URL strand-0.1.10.tar.gz
Size 15.4 kB
Tags Source
SHA-256 checksum
How to use checksums
cca591a47390c4a3b0bd16e02a4f7254e0431fda698f954c08400acecb498b6e
BLAKE2b-256 checksum
How to use checksums
4a4333e433fcae24b7a3077e21127b94709d3122f545490e6d565f354dd338e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / strand-0.1.10-py3-none-any.whl

Download URL strand-0.1.10-py3-none-any.whl
Size 19.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e9e7b42a9cb8354a3ee071bebde941142cd906cec4d40dfb3385d1bd5710155a
BLAKE2b-256 checksum
How to use checksums
e7415f532f50f474e0b59ce3d6d783e5e376cc64a4c8d426e9751de68c8b45ab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for strand 0.1.10

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