Skip to content

Mixing sync and async functions in Python

Python splits functions into two kinds. A coroutine (async def) can only be awaited from another coroutine, and a plain function can't await anything. This is often called the function color problem, after Bob Nystrom's essay What Color Is Your Function?.

FlpIt's task runtime puts both kinds behind one type, Task. The practical rule is short: start in async def and await whatever you need. If something is a plain blocking function, put @task on it.

Await a blocking function

@task makes every call start immediately on a pooled worker thread and return a Task. A Task can be awaited, or run side by side with others in Task.when_all:

import time

from flpit.task import Task, task


@task                                      # a plain, blocking function...
def read_report(name: str) -> str:
    time.sleep(0.05)
    return f"report {name}"


async def main() -> list[str]:
    first = await read_report("a")         # ...that you can simply await
    rest = await Task.when_all([read_report("b"), read_report("c")])   # or run side by side
    return [first, *rest]


reports = Task.run(main).result()          # ["report a", "report b", "report c"]

Start many calls at once

Put @task on a function, sync or async def, and every call starts immediately and returns a Task. A query that selects such a function therefore has all its calls running before you wait for any of them. End the query in when_all() to get the results in input order:

from flpit import flp
from flpit.task import Task, task

links = [
    "https://httpbin.org/delay/3",         # slowest first
    "https://httpbin.org/delay/2",
    "https://httpbin.org/delay/1",
]


@task
def fetch(url: str) -> tuple[str, bytes]:
    return url, httpx.get(url, timeout=30).content        # plain, blocking httpx


pages = flp.it(links).select(fetch).when_all().result()   # all three at once, in order

To handle each result as soon as it is ready, end the query in when_each() instead. It is an async stream of the tasks in the order they finish, and each task is already done when you receive it.

async def crawl() -> None:
    async for done in flp.it(links).select(fetch).when_each():
        url, page = await done             # finished already, just unwrapping

To work with the values and not the tasks, add select_await(), which awaits each finished task, and then post-process with an ordinary select. The callback can be a plain function or an async def:

def parse(result: tuple[str, bytes]) -> tuple[str, int]:
    url, page = result
    return url, len(page)                  # any post-processing, a plain function or an async def


async def crawl_sizes() -> None:
    query = (
        flp.it(links)
        .select(fetch)      # one fetch task per link
        .when_each()        # yield the tasks in the order they finish
        .select_await()     # await each finished task to get its value
        .select(parse)      # post-process the value as it arrives
    )

    async for url, size in query:
        print(url, size)    # first finished, first served

Call an async function from sync code

Task.run starts a coroutine function (or a plain one) and returns the same Task. From synchronous code, wait for it with twait >>, the sync counterpart of await, or with .result():

from flpit.task import twait


async def double(n: int) -> int:           # an ordinary coroutine function
    await Task.delay(0.01)
    return n * 2


answer = twait >> Task.run(double, 21)     # 42, reads like `await`
same = Task.run(double, 21).result()       # 42, as a method call

Both block the calling thread until the task is done. The difference is a safety check: twait >> raises RuntimeError when it is written directly inside an async def, where blocking would tie up a pool worker. Use await there. The check looks only at the function that contains the expression, so it can't catch a plain helper that is called from async code.

Mix both in one query

AsyncFlpIt callbacks may be plain functions or async def functions. You don't have to pick one for the whole pipeline:

from flpit import flp
from flpit.task import CancellationToken


async def is_big(n: int, token: CancellationToken) -> bool:    # an async predicate
    return n > 2


# A plain lambda and an async function in the same query.
query = flp.ait(range(5)).select(lambda n: n * 2).where(is_big)
result = query.to_list().result()          # [4, 6, 8]

What still applies

  • await still needs async def. FlpIt removes the wrappers, not the keyword. A plain function either gets @task and is awaited, or is called through Task.run(...).result().
  • twait >> and .result() block the calling thread. Use them at the edge of your program or in plain threads, and prefer await inside a task.
  • Blocking work occupies a worker. @task functions run on the pool's threads. Data they share needs the usual care; see threading primitives.
  • Code that needs an asyncio event loop (such as httpx.AsyncClient) is a different case. See Using asyncio libraries.