Skip to content

Commit

Permalink
Rename to flake8 async (#206)
Browse files Browse the repository at this point in the history
* update docs, name of binary, and in general all changes possible without renaming files

* rename error codes to ASYNCxxx, introducing temp functions to pretend test files are renamed.

* rename Flake8TrioVisitor to Flake8AsyncVisitor
  • Loading branch information
jakkdl authored Feb 26, 2024
1 parent b00e77a commit 7748d40
Show file tree
Hide file tree
Showing 70 changed files with 689 additions and 638 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
name: flake8-trio CI
name: flake8-async CI

on:
push:
Expand Down
6 changes: 2 additions & 4 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ Contributions welcome! We'll expand this guide as we go.

## Development

When you wish to add a check to `flake8-trio` please ensure the following:
When you wish to add a check to `flake8-async` please ensure the following:

- `README.md` gets a one line about your new warning
- Add a CHANGELOG entry (see 'Releasing a new version' below)
- Unittests are added showing the check highlight where it should and shouldn't
(see flake8-bugbear for examples of good linter tests)

- A test in `tests/eval_files` is added for your check. See the "Test generator" heading below.
To run our test suite please use tox.

```console
Expand Down
106 changes: 54 additions & 52 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,66 @@
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/python-trio/flake8-trio/main.svg)](https://results.pre-commit.ci/latest/github/python-trio/flake8-trio/main)
[![Checked with pyright](https://microsoft.github.io/pyright/img/pyright_badge.svg)](https://microsoft.github.io/pyright/)
# flake8-trio
# flake8-async

A highly opinionated flake8 plugin for [Trio](https://github.com/python-trio/trio)-related problems.
A highly opinionated flake8 plugin for problems related to [Trio](https://github.com/python-trio/trio), [AnyIO](https://github.com/agronholm/anyio), or [asyncio](https://docs.python.org/3/library/asyncio.html).

This can include anything from outright bugs, to pointless/dead code,
to likely performance issues, to minor points of idiom that might signal
a misunderstanding.

It may well be too noisy for anyone with different opinions, that's OK.

It also supports the [anyio](https://github.com/agronholm/anyio) library.

Pairs well with flake8-bugbear.

Some checks are incorporated into [ruff](https://github.com/astral-sh/ruff).

This plugin was previously known as flake8-trio, and there was a separate small plugin known as flake8-async for asyncio. But this plugin was a superset of the checks in flake8-async, and support for anyio was added, so it's now named flake8-async to more properly convey its usage. At the same time all error codes were renamed from TRIOxxx to ASYNCxxx, as was previously used by the old flake8-async.

## Installation

```console
pip install flake8-trio
pip install flake8-async
```

## List of warnings

- **TRIO100**: A `with trio.fail_after(...):` or `with trio.move_on_after(...):`
- **ASYNC100**: A `with trio.fail_after(...):` or `with trio.move_on_after(...):`
context does not contain any `await` statements. This makes it pointless, as
the timeout can only be triggered by a checkpoint.
- **TRIO101**: `yield` inside a nursery or cancel scope is only safe when implementing a context manager - otherwise, it breaks exception handling.
- **TRIO102**: It's unsafe to await inside `finally:` or `except BaseException/trio.Cancelled` unless you use a shielded
- **ASYNC101**: `yield` inside a nursery or cancel scope is only safe when implementing a context manager - otherwise, it breaks exception handling.
- **ASYNC102**: It's unsafe to await inside `finally:` or `except BaseException/trio.Cancelled` unless you use a shielded
cancel scope with a timeout.
- **TRIO103**: `except BaseException`, `except trio.Cancelled` or a bare `except:` with a code path that doesn't re-raise. If you don't want to re-raise `BaseException`, add a separate handler for `trio.Cancelled` before.
- **TRIO104**: `Cancelled` and `BaseException` must be re-raised - when a user tries to `return` or `raise` a different exception.
- **TRIO105**: Calling a trio async function without immediately `await`ing it.
- **TRIO106**: `trio` must be imported with `import trio` for the linter to work.
- **TRIO109**: Async function definition with a `timeout` parameter - use `trio.[fail/move_on]_[after/at]` instead
- **TRIO110**: `while <condition>: await trio.sleep()` should be replaced by a `trio.Event`.
- **TRIO111**: Variable, from context manager opened inside nursery, passed to `start[_soon]` might be invalidly accessed while in use, due to context manager closing before the nursery. This is usually a bug, and nurseries should generally be the inner-most context manager.
- **TRIO112**: Nursery body with only a call to `nursery.start[_soon]` and not passing itself as a parameter can be replaced with a regular function call.
- **TRIO113**: Using `nursery.start_soon` in `__aenter__` doesn't wait for the task to begin. Consider replacing with `nursery.start`.
- **TRIO114**: Startable function (i.e. has a `task_status` keyword parameter) not in `--startable-in-context-manager` parameter list, please add it so TRIO113 can catch errors when using it.
- **TRIO115**: Replace `trio.sleep(0)` with the more suggestive `trio.lowlevel.checkpoint()`.
- **TRIO116**: `trio.sleep()` with >24 hour interval should usually be `trio.sleep_forever()`.
- **TRIO118**: Don't assign the value of `anyio.get_cancelled_exc_class()` to a variable, since that breaks linter checks and multi-backend programs.
- **ASYNC103**: `except BaseException`, `except trio.Cancelled` or a bare `except:` with a code path that doesn't re-raise. If you don't want to re-raise `BaseException`, add a separate handler for `trio.Cancelled` before.
- **ASYNC104**: `Cancelled` and `BaseException` must be re-raised - when a user tries to `return` or `raise` a different exception.
- **ASYNC105**: Calling a trio async function without immediately `await`ing it.
- **ASYNC106**: `trio`/`anyio` must be imported with `import trio`/`import anyio` for the linter to work.
- **ASYNC109**: Async function definition with a `timeout` parameter - use `trio.[fail/move_on]_[after/at]` instead
- **ASYNC110**: `while <condition>: await trio.sleep()` should be replaced by a `trio.Event`.
- **ASYNC111**: Variable, from context manager opened inside nursery, passed to `start[_soon]` might be invalidly accessed while in use, due to context manager closing before the nursery. This is usually a bug, and nurseries should generally be the inner-most context manager.
- **ASYNC112**: Nursery body with only a call to `nursery.start[_soon]` and not passing itself as a parameter can be replaced with a regular function call.
- **ASYNC113**: Using `nursery.start_soon` in `__aenter__` doesn't wait for the task to begin. Consider replacing with `nursery.start`.
- **ASYNC114**: Startable function (i.e. has a `task_status` keyword parameter) not in `--startable-in-context-manager` parameter list, please add it so ASYNC113 can catch errors when using it.
- **ASYNC115**: Replace `trio.sleep(0)` with the more suggestive `trio.lowlevel.checkpoint()`.
- **ASYNC116**: `trio.sleep()` with >24 hour interval should usually be `trio.sleep_forever()`.
- **ASYNC118**: Don't assign the value of `anyio.get_cancelled_exc_class()` to a variable, since that breaks linter checks and multi-backend programs.

### Warnings for blocking sync calls in async functions
- **TRIO200**: User-configured error for blocking sync calls in async functions. Does nothing by default, see [`trio200-blocking-calls`](#trio200-blocking-calls) for how to configure it.
- **TRIO210**: Sync HTTP call in async function, use `httpx.AsyncClient`.
- **TRIO211**: Likely sync HTTP call in async function, use `httpx.AsyncClient`. Looks for `urllib3` method calls on pool objects, but only matching on the method signature and not the object.
- **TRIO212**: Blocking sync HTTP call on httpx object, use httpx.AsyncClient.
- **TRIO220**: Sync process call in async function, use `await nursery.start(trio.run_process, ...)`.
- **TRIO221**: Sync process call in async function, use `await trio.run_process(...)`.
- **TRIO222**: Sync `os.*` call in async function, wrap in `await trio.to_thread.run_sync()`.
- **TRIO230**: Sync IO call in async function, use `trio.open_file(...)`.
- **TRIO231**: Sync IO call in async function, use `trio.wrap_file(...)`.
- **TRIO232**: Blocking sync call on file object, wrap the file object in `trio.wrap_file()` to get an async file object.
- **TRIO240**: Avoid using `os.path` in async functions, prefer using `trio.Path` objects.
- **ASYNC200**: User-configured error for blocking sync calls in async functions. Does nothing by default, see [`trio200-blocking-calls`](#trio200-blocking-calls) for how to configure it.
- **ASYNC210**: Sync HTTP call in async function, use `httpx.AsyncClient`.
- **ASYNC211**: Likely sync HTTP call in async function, use `httpx.AsyncClient`. Looks for `urllib3` method calls on pool objects, but only matching on the method signature and not the object.
- **ASYNC212**: Blocking sync HTTP call on httpx object, use httpx.AsyncClient.
- **ASYNC220**: Sync process call in async function, use `await nursery.start(trio.run_process, ...)`.
- **ASYNC221**: Sync process call in async function, use `await trio.run_process(...)`.
- **ASYNC222**: Sync `os.*` call in async function, wrap in `await trio.to_thread.run_sync()`.
- **ASYNC230**: Sync IO call in async function, use `trio.open_file(...)`.
- **ASYNC231**: Sync IO call in async function, use `trio.wrap_file(...)`.
- **ASYNC232**: Blocking sync call on file object, wrap the file object in `trio.wrap_file()` to get an async file object.
- **ASYNC240**: Avoid using `os.path` in async functions, prefer using `trio.Path` objects.

### Warnings disabled by default
- **TRIO900**: Async generator without `@asynccontextmanager` not allowed.
- **TRIO910**: Exit or `return` from async function with no guaranteed checkpoint or exception since function definition.
- **TRIO911**: Exit, `yield` or `return` from async iterable with no guaranteed checkpoint since possible function entry (yield or function definition)
- **ASYNC900**: Async generator without `@asynccontextmanager` not allowed.
- **ASYNC910**: Exit or `return` from async function with no guaranteed checkpoint or exception since function definition.
- **ASYNC911**: Exit, `yield` or `return` from async iterable with no guaranteed checkpoint since possible function entry (yield or function definition)
Checkpoints are `await`, `async for`, and `async with` (on one of enter/exit).

### Removed Warnings
Expand All @@ -69,55 +71,55 @@ pip install flake8-trio
## Examples
### install and run through flake8
```sh
pip install flake8 flake8-trio
pip install flake8 flake8-async
flake8 .
```
### install and run with pre-commit
If you use [pre-commit](https://pre-commit.com/), you can use it with flake8-trio by
If you use [pre-commit](https://pre-commit.com/), you can use it with flake8-async by
adding the following to your `.pre-commit-config.yaml`:

```yaml
minimum_pre_commit_version: '2.9.0'
repos:
- repo: https://github.com/Zac-HD/flake8-trio
- repo: https://github.com/python-trio/flake8-async
rev: 23.2.5
hooks:
- id: flake8-trio
# args: [--enable=TRIO, --disable=TRIO9, --autofix=TRIO]
- id: flake8-async
# args: [--enable=ASYNC, --disable=ASYNC9, --autofix=ASYNC]
```

This is often considerably faster for large projects, because `pre-commit`
can avoid running `flake8-trio` on unchanged files.
can avoid running `flake8-async` on unchanged files.


Afterwards, run
```sh
pip install pre-commit flake8-trio
pip install pre-commit flake8-async
pre-commit run .
```
### install and run as standalone
If inside a git repository, running without arguments will run it against all `*.py` files in the repository.
```sh
pip install flake8-trio
flake8-trio
pip install flake8-async
flake8-async
```
#### with autofixes
```sh
flake8-trio --autofix=TRIO
flake8-async --autofix=ASYNC
```
#### specifying source files
```sh
flake8-trio my_python_file.py
flake8-async my_python_file.py
```
##### zsh-only
```zsh
flake8-trio **/*.py
flake8-async **/*.py
```

## Configuration
[You can configure `flake8` with command-line options](https://flake8.pycqa.org/en/latest/user/configuration.html),
but we prefer using a config file. The file needs to start with a section marker `[flake8]` and the following options are then parsed using flake8's config parser, and can be used just like any other flake8 options.
Note that it's not currently possible to use a configuration file when running `flake8-trio` standalone.
Note that it's not currently possible to use a configuration file when running `flake8-async` standalone.

### `--enable`
Comma-separated list of error codes to enable, similar to flake8 --select but is additionally more performant as it will disable non-enabled visitors from running instead of just silencing their errors.
Expand All @@ -126,7 +128,7 @@ Comma-separated list of error codes to enable, similar to flake8 --select but is
Comma-separated list of error codes to disable, similar to flake8 --ignore but is additionally more performant as it will disable non-enabled visitors from running instead of just silencing their errors.

### `--autofix`
Comma-separated list of error-codes to enable autofixing for if implemented. Requires running as a standalone program. Pass `--autofix=TRIO` to enable all autofixes.
Comma-separated list of error-codes to enable autofixing for if implemented. Requires running as a standalone program. Pass `--autofix=ASYNC` to enable all autofixes.

### `--error-on-autofix`
Whether to also print an error message for autofixed errors.
Expand All @@ -135,7 +137,7 @@ Whether to also print an error message for autofixed errors.
Change the default library to be anyio instead of trio. If trio is imported it will assume both are available and print suggestions with [anyio|trio].

### `no-checkpoint-warning-decorators`
Comma-separated list of decorators to disable checkpointing checks for, turning off TRIO910 and TRIO911 warnings for functions decorated with any decorator matching any in the list. Matching is done with [fnmatch](https://docs.python.org/3/library/fnmatch.html). Defaults to disabling for `asynccontextmanager`.
Comma-separated list of decorators to disable checkpointing checks for, turning off ASYNC910 and ASYNC911 warnings for functions decorated with any decorator matching any in the list. Matching is done with [fnmatch](https://docs.python.org/3/library/fnmatch.html). Defaults to disabling for `asynccontextmanager`.

Decorators-to-match must be identifiers or dotted names only (not PEP-614 expressions), and will match against the name only - e.g. `foo.bar` matches `foo.bar`, `foo.bar()`, and `foo.bar(args, here)`, etc.

Expand All @@ -159,14 +161,14 @@ startable-in-context-manager =
myfun2,
```

### `trio200-blocking-calls`
### `async200-blocking-calls`
Comma-separated list of pairs of values separated by `->` (optional whitespace stripped), where the first is a pattern for a call that should raise an error if found inside an async function, and the second is what should be suggested to use instead. It uses fnmatch as per [`no-checkpoint-warning-decorators`](#no-checkpoint-warning-decorators) for matching. The part after `->` is not used by the checker other than when printing the error, so you could add extra info there if you want.

The format of the error message is `User-configured blocking sync call {0} in async function, consider replacing with {1}.`, where `{0}` is the pattern the call matches and `{1}` is the suggested replacement.

Example:
```ini
trio200-blocking-calls =
async200-blocking-calls =
my_blocking_call -> async.alternative,
module.block_call -> other_function_to_use,
common_error_call -> alternative(). But sometimes you should use other_function(). Ask joe if you're unsure which one,
Expand Down
23 changes: 13 additions & 10 deletions flake8_trio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

import libcst as cst

from .base import Options
from .base import Options, error_has_subidentifier
from .runner import Flake8TrioRunner, Flake8TrioRunner_cst
from .visitors import ERROR_CLASSES, ERROR_CLASSES_CST, default_disabled_error_codes

Expand Down Expand Up @@ -199,7 +199,7 @@ def add_options(option_manager: OptionManager | ArgumentParser):
)
else: # if run as a flake8 plugin
Plugin.standalone = False
# Disable TRIO9xx calls by default
# Disable ASYNC9xx calls by default
option_manager.extend_default_ignore(default_disabled_error_codes)
# add parameter to parse from flake8 config
add_argument = functools.partial( # type: ignore
Expand All @@ -209,7 +209,7 @@ def add_options(option_manager: OptionManager | ArgumentParser):
add_argument(
"--enable",
type=comma_separated_list,
default="TRIO",
default="ASYNC",
required=False,
help=(
"Comma-separated list of error codes to enable, similar to flake8"
Expand All @@ -221,7 +221,7 @@ def add_options(option_manager: OptionManager | ArgumentParser):
add_argument(
"--disable",
type=comma_separated_list,
default="TRIO9" if Plugin.standalone else "",
default="ASYNC9" if Plugin.standalone else "",
required=False,
help=(
"Comma-separated list of error codes to disable, similar to flake8"
Expand Down Expand Up @@ -253,7 +253,7 @@ def add_options(option_manager: OptionManager | ArgumentParser):
required=False,
type=comma_separated_list,
help=(
"Comma-separated list of decorators to disable TRIO910 & TRIO911 "
"Comma-separated list of decorators to disable ASYNC910 & ASYNC911 "
"checkpoint warnings for. "
"Decorators can be dotted or not, as well as support * as a wildcard. "
"For example, ``--no-checkpoint-warning-decorators=app.route,"
Expand All @@ -266,7 +266,7 @@ def add_options(option_manager: OptionManager | ArgumentParser):
default="",
required=False,
help=(
"Comma-separated list of method calls to additionally enable TRIO113 "
"Comma-separated list of method calls to additionally enable ASYNC113 "
"warnings for. Will also check for the pattern inside function calls. "
"Methods must be valid identifiers as per `str.isidientifier()` and "
"not reserved keywords. "
Expand All @@ -281,7 +281,7 @@ def add_options(option_manager: OptionManager | ArgumentParser):
required=False,
help=(
"Comma-separated list of key->value pairs, where key is a [dotted] "
"function that if found inside an async function will raise TRIO200, "
"function that if found inside an async function will raise ASYNC200, "
"suggesting it be replaced with {value}"
),
)
Expand Down Expand Up @@ -313,8 +313,9 @@ def get_matching_codes(
err_code
for err_class in (*ERROR_CLASSES, *ERROR_CLASSES_CST)
for err_code in err_class.error_codes # type: ignore[attr-defined]
if len(err_code) == 7 # exclude e.g. TRIO103_anyio_trio
if not error_has_subidentifier(err_code) # exclude e.g. ASYNC103_anyio_trio
}
assert all_codes

if options.autofix and not Plugin.standalone:
print("Cannot autofix when run as a flake8 plugin.", file=sys.stderr)
Expand All @@ -328,8 +329,10 @@ def get_matching_codes(
enabled_codes -= set(get_matching_codes(options.disable, enabled_codes))

# if disable has default value, re-enable explicitly enabled codes
if options.disable == ["TRIO9"]:
enabled_codes.update(code for code in options.enable if len(code) == 7)
if options.disable == ["ASYNC9"]:
enabled_codes.update(
code for code in options.enable if not error_has_subidentifier(code)
)

Plugin._options = Options(
enabled_codes=enabled_codes,
Expand Down
11 changes: 11 additions & 0 deletions flake8_trio/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@
from collections.abc import Collection


# strip the sub-identifier on error used to specify which message to print, when
# several different ones are used for the same code. Used in e.g. Visitor103
def strip_error_subidentifier(s: str) -> str:
"""Turn e.g. ASYNC103_anyio_trio => ASYNC103."""
return s.split("_")[0]


def error_has_subidentifier(s: str) -> bool:
return "_" in s


@dataclass
class Options:
# error codes to give errors for
Expand Down
Loading

0 comments on commit 7748d40

Please sign in to comment.