Skip to content

Easy Async

py_simple.easy_async

easy_async is built to simplify asynchronous code execution.

EasyAsyncError

Bases: Exception

Raised when a py_simple async function fails to complete.

Wraps the underlying error (an exception raised inside one of the functions being run, a thread pool failure, etc.) so py_simple functions can fail with one consistent, easy-to-read exception instead of a random builtin one.

Parameters:

Name Type Description Default
message str

Human-readable description of what went wrong.

required

run_at_the_same_time_no_params(functions)

Runs multiple zero-argument functions at the same time and returns their results.

Raises EasyAsyncError if any function raises an exception while running.

Parameters:

Name Type Description Default
functions list

Functions to run, each taking no arguments.

required

Returns:

Name Type Description
list list

A list of (name, result) tuples, one per function.

Example
from py_simple import run_at_the_same_time

def add():
    return 1 + 1

def sub():
    return 4 - 2

run_at_the_same_time([add, sub])  # -> [("add", 2), ("sub", 2)]
from concurrent.futures import ThreadPoolExecutor

def add():
    return 1 + 1

def sub():
    return 4 - 2

functions = [add, sub]
results = []
with ThreadPoolExecutor() as executor:
    tickets = [
        (f.__name__, executor.submit(f)) for f in functions
    ]
    for name, ticket in tickets:
        results.append((name, ticket.result()))

run_at_the_same_time_with_params(functions_and_args)

Runs multiple functions at the same time, each with its own arguments, and returns their results.

Raises EasyAsyncError if any function raises an exception while running.

Parameters:

Name Type Description Default
functions_and_args list[tuple]

Functions to run, each given as a tuple where the first item is the function and the remaining items are the positional arguments to call it with, e.g. (func, arg1, arg2).

required

Returns:

Name Type Description
list list

A list of (name, result) tuples, one per function.

Example
from py_simple import run_at_the_same_time_with_params

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

run_at_the_same_time_with_params([
    (add, 1, 1),
    (sub, 4, 2),
])  # -> [("add", 2), ("sub", 2)]
from concurrent.futures import ThreadPoolExecutor

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

functions_and_args = [(add, 1, 1), (sub, 4, 2)]
results = []
with ThreadPoolExecutor() as executor:
    tickets = [
        (item[0].__name__, executor.submit(item[0], *item[1:]))
        for item in functions_and_args
    ]
    for name, ticket in tickets:
        results.append((name, ticket.result()))