Skip to content

blocking-path-method-in-async-function (ASYNC240)

Derived from the flake8-async linter.

This rule is unstable and in preview. The --preview flag is required for use.

What it does

Checks that async functions do not call blocking os.path or pathlib.Path methods.

Why is this bad?

Calling some os.path or pathlib.Path methods in an async function will block the entire event loop, preventing it from executing other tasks while waiting for the operation. This negates the benefits of asynchronous programming.

Instead, use the methods' async equivalents from trio.Path or anyio.Path.

Example

import os


async def func():
    path = "my_file.txt"
    file_exists = os.path.exists(path)

Use instead:

import trio


async def func():
    path = trio.Path("my_file.txt")
    file_exists = await path.exists()

Non-blocking methods are OK to use:

import pathlib


async def func():
    path = pathlib.Path("my_file.txt")
    file_dirname = path.dirname()
    new_path = os.path.join("/tmp/src/", path)