python-trio / python-trio/flake8-async

New asyncio rule: directly passing coroutine to `gather`, `shield`, `wait_for`, `wait`, or `as_completed`

Open
#319 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

new rule postponed
Dominant language
Python
Stars
26
Forks
10
PR merge metrics
No merged PRs in 30d

Description

Tasks without saved reference can be garbage collected, and several functions in asyncio automatically converts coroutines into tasks - which means it's ~impossible to save a strong reference to those tasks. See e.g. https://docs.python.org/3/library/asyncio-task.html#asyncio.shield

The rule implementation would be fairly straightforward, just check for calls in the parameter list: asyncio.shield(anything()). This will give false alarms if anything is not a coroutine, but instead a sync function that creates a task, saves it globally, and returns it, but I suspect that's a minority of cases. We could save the names of any sync funcs to reduce the false alarm rate, but that wouldn't work when the functions are imported from other files.

We could also use type-checking to catch

a = my_coro()
asyncio.wait_for(a)

On py311+ asyncio.wait errors if directly passed coroutines.

There appears to be movement in making the event loop save strong references, but that'll probably only affect py3.14/py3.15 or later https://github.com/python/cpython/pull/121264

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the existing asyncio rule implementations and their tests. Trace handling for direct coroutine arguments to gather, shield, wait_for, wait, and as_completed, then verify the expected behavior across Python versions, including wait on Python 3.11+. Done means the new rule catches the described direct calls while its false-positive trade-offs are covered by tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.