Skip to content

async-def-as-sync-callback (EFF115)

Family: Execution Effects (EFF) · Heuristic · Opt-in · Experimental · Severity error (a bug) · No automatic fix

Opt-in: an async def handed to a library call that calls it without awaiting what it returns (a thread's target, an executor's function, an atexit or signal handler, a filter predicate), so the call only creates a coroutine and the body does not run.

Heuristic

This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs only when select or extend-select names its code or name. It has not been measured yet. See Rule Precision.

Experimental

The development corpus has no report of it, so its precision is not measured, and its premises are not yet certified. Experimental features can still change in behavior or precision, or be removed, in any release, and each change is listed in the release notes. An opt-in rule that is not experimental is stable and only off by default. See Experimental Features.

What it does

Checks for an async def handed to a library call that calls it as a plain function and never awaits what it returns. Calling an async def only creates a coroutine: the call returns at once, the body does not run, and Python warns coroutine ... was never awaited when the coroutine is collected, if anyone sees the warning. A few of the calls test for a coroutine function and raise TypeError instead (sync_to_async, trio.to_thread.run_sync, and the event loop's scheduling methods in debug mode); the body does not run there either.

The library calls are the ecosystem catalog's (calls_unawaited), and the offloading APIs that run a callable on a worker thread (offloads_blocking_arg):

  • run the callable on another thread or process, or later: threading.Thread(target=f), threading.Timer(t, f), multiprocessing.Process(target=f), executor.submit(f), executor.map(f, xs), loop.run_in_executor(None, f), asyncio.to_thread(f), anyio.to_thread.run_sync(f), trio.to_thread.run_sync(f), run_in_threadpool(f), sync_to_async(f), loop.call_soon(f) (with call_soon_threadsafe, call_later, and call_at), atexit.register(f), signal.signal(sig, f), stack.callback(f) of an ExitStack or AsyncExitStack, and weakref.finalize(obj, f);
  • test what the callable returns for truth: filter(f, xs), itertools.filterfalse, itertools.takewhile, and itertools.dropwhile. A coroutine is always true, so every item passes the test (or none, for filterfalse).

The callable is the function itself, a bound method (self.flush), or a functools.partial of either. A report is worded as certain when every function the value calls is an async def without decorators other than staticmethod, classmethod, abstractmethod, override, or final; when a decorator replaces one, or another implementation of the method is a plain function, the report says the function may not create a coroutine.

It does not report:

  • map, itertools.starmap, or functools.reduce: they hand the coroutines on, and a caller may await them (await asyncio.gather(*map(fetch, urls)));
  • a sort key (sorted, min, max, list.sort): the coroutines are no comparable values, which the type checkers report;
  • a project function that takes a callable, whatever it does with it: a runner of the project may test inspect.iscoroutinefunction and drive the coroutine itself; so may a project subclass of threading.Thread, whose construction is the project's;
  • an async generator function, a class, or a lambda.

What a report states

A report states that the library call never awaits what the named function returns (the function itself, or what the value handed to it calls), and that the function is an async def: calling it only creates a coroutine, and the body of the function does not run there.

Its premises:

  • Unawaited call: the call is one the catalog says never awaits what the argument at the position or keyword it names returns. Established from the catalog.
  • Coroutine function: every function the handed value calls is an async def that no decorator replaces. Open when a decorator may replace it, or when another implementation of the method is a plain function.

Not part of the claim: whether a caller awaits the coroutine that an offloading API or an executor hands back (await (await asyncio.to_thread(f))), which runs the body on the event loop instead.

Why is this bad?

The work never happens, and nothing fails: a thread starts and ends at once, a cleanup handler does nothing, a signal handler ignores the signal, a filter keeps every item. Turning a function into an async def breaks every such caller of it without an error at the call.

Example

import atexit
import threading


async def flush_metrics() -> None:
    await client.flush()


def start() -> None:
    threading.Thread(target=flush_metrics, daemon=True).start()  # EFF115
    atexit.register(flush_metrics)  # EFF115

Use instead:

import asyncio
import atexit
import threading


async def flush_metrics() -> None:
    await client.flush()


def flush_now() -> None:
    asyncio.run(flush_metrics())


def start() -> None:
    threading.Thread(target=flush_now, daemon=True).start()
    atexit.register(flush_now)

Fix safety

No automatic fix.

Options

  • lint.extend-select = ["EFF115"] (or --extend-select EFF115) enables the rule. It is opt-in: selecting the EFF prefix does not enable it.