-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[flake8-async] Implement blocking-path-method (ASYNC240)
#20264
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ntBre
merged 7 commits into
astral-sh:main
from
PieterCK:add-rule-async-240-blocking-path-usage
Sep 23, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c2125ed
[flake8-async] Implement `blocking-path-method` (ASYNC240).
PieterCK c5b5f27
Update PathlibPathChecker to check nested annotation.
PieterCK 439fd2a
Create a new TypeChecker for ASYNC240.
PieterCK 2fa4dcb
Address code reviews.
PieterCK fc6a4ec
Address code reviews.
PieterCK f31d0b6
Address code review.
PieterCK 9c3dd35
Remove comment on PathlibPathChecker.
PieterCK File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
104 changes: 104 additions & 0 deletions
104
crates/ruff_linter/resources/test/fixtures/flake8_async/ASYNC240.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| import os | ||
| from typing import Optional | ||
| from pathlib import Path | ||
|
|
||
| ## Valid cases: | ||
|
|
||
| def os_path_in_foo(): | ||
| file = "file.txt" | ||
|
|
||
| os.path.abspath(file) # OK | ||
| os.path.exists(file) # OK | ||
| os.path.split() # OK | ||
|
|
||
| async def non_io_os_path_methods(): | ||
| os.path.split() # OK | ||
| os.path.dirname() # OK | ||
| os.path.basename() # OK | ||
| os.path.join() # OK | ||
|
|
||
| def pathlib_path_in_foo(): | ||
| path = Path("src/my_text.txt") # OK | ||
| path.exists() # OK | ||
| with path.open() as f: # OK | ||
| ... | ||
| path = Path("src/my_text.txt").open() # OK | ||
|
|
||
| async def non_io_pathlib_path_methods(): | ||
| path = Path("src/my_text.txt") | ||
| path.is_absolute() # OK | ||
| path.is_relative_to() # OK | ||
| path.as_posix() # OK | ||
| path.relative_to() # OK | ||
|
|
||
| def inline_path_method_call(): | ||
| Path("src/my_text.txt").open() # OK | ||
| Path("src/my_text.txt").open().flush() # OK | ||
| with Path("src/my_text.txt").open() as f: # OK | ||
| ... | ||
|
|
||
| async def trio_path_in_foo(): | ||
| from trio import Path | ||
|
|
||
| path = Path("src/my_text.txt") # OK | ||
| await path.absolute() # OK | ||
| await path.exists() # OK | ||
| with Path("src/my_text.txt").open() as f: # OK | ||
| ... | ||
|
|
||
| async def anyio_path_in_foo(): | ||
| from anyio import Path | ||
|
|
||
| path = Path("src/my_text.txt") # OK | ||
| await path.absolute() # OK | ||
| await path.exists() # OK | ||
| with Path("src/my_text.txt").open() as f: # OK | ||
| ... | ||
|
|
||
| async def path_open_in_foo(): | ||
| path = Path("src/my_text.txt") # OK | ||
| path.open() # OK, covered by ASYNC230 | ||
|
|
||
| ## Invalid cases: | ||
|
|
||
| async def os_path_in_foo(): | ||
| file = "file.txt" | ||
|
|
||
| os.path.abspath(file) # ASYNC240 | ||
| os.path.exists(file) # ASYNC240 | ||
|
|
||
| async def pathlib_path_in_foo(): | ||
| path = Path("src/my_text.txt") | ||
| path.exists() # ASYNC240 | ||
|
|
||
| async def pathlib_path_in_foo(): | ||
| import pathlib | ||
|
|
||
| path = pathlib.Path("src/my_text.txt") | ||
| path.exists() # ASYNC240 | ||
|
|
||
| async def inline_path_method_call(): | ||
| Path("src/my_text.txt").exists() # ASYNC240 | ||
| Path("src/my_text.txt").absolute().exists() # ASYNC240 | ||
|
|
||
| async def aliased_path_in_foo(): | ||
| from pathlib import Path as PathAlias | ||
|
|
||
| path = PathAlias("src/my_text.txt") | ||
| path.exists() # ASYNC240 | ||
|
|
||
| global_path = Path("src/my_text.txt") | ||
|
|
||
| async def global_path_in_foo(): | ||
| global_path.exists() # ASYNC240 | ||
|
|
||
| async def path_as_simple_parameter_type(path: Path): | ||
| path.exists() # ASYNC240 | ||
|
|
||
| async def path_as_union_parameter_type(path: Path | None): | ||
| path.exists() # ASYNC240 | ||
|
|
||
| async def path_as_optional_parameter_type(path: Optional[Path]): | ||
| path.exists() # ASYNC240 | ||
|
|
||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
246 changes: 246 additions & 0 deletions
246
crates/ruff_linter/src/rules/flake8_async/rules/blocking_path_methods.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,246 @@ | ||
| use crate::Violation; | ||
| use crate::checkers::ast::Checker; | ||
| use ruff_macros::{ViolationMetadata, derive_message_formats}; | ||
| use ruff_python_ast::{self as ast, Expr, ExprCall}; | ||
| use ruff_python_semantic::analyze::typing::{TypeChecker, check_type, traverse_union_and_optional}; | ||
| use ruff_text_size::Ranged; | ||
|
|
||
| /// ## 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 | ||
| /// ```python | ||
| /// import os | ||
| /// | ||
| /// | ||
| /// async def func(): | ||
| /// path = "my_file.txt" | ||
| /// file_exists = os.path.exists(path) | ||
| /// ``` | ||
| /// | ||
| /// Use instead: | ||
| /// ```python | ||
| /// import trio | ||
| /// | ||
| /// | ||
| /// async def func(): | ||
| /// path = trio.Path("my_file.txt") | ||
| /// file_exists = await path.exists() | ||
| /// ``` | ||
| /// | ||
| /// Non-blocking methods are OK to use: | ||
| /// ```python | ||
| /// import pathlib | ||
| /// | ||
| /// | ||
| /// async def func(): | ||
| /// path = pathlib.Path("my_file.txt") | ||
| /// file_dirname = path.dirname() | ||
| /// new_path = os.path.join("/tmp/src/", path) | ||
| /// ``` | ||
| #[derive(ViolationMetadata)] | ||
| pub(crate) struct BlockingPathMethodInAsyncFunction { | ||
| path_library: String, | ||
| } | ||
|
|
||
| impl Violation for BlockingPathMethodInAsyncFunction { | ||
| #[derive_message_formats] | ||
| fn message(&self) -> String { | ||
| format!( | ||
| "Async functions should not use {path_library} methods, use trio.Path or anyio.path", | ||
| path_library = self.path_library | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| /// ASYNC240 | ||
| pub(crate) fn blocking_os_path(checker: &Checker, call: &ExprCall) { | ||
| let semantic = checker.semantic(); | ||
| if !semantic.in_async_context() { | ||
| return; | ||
| } | ||
|
|
||
| // Check if an expression is calling I/O related os.path method. | ||
| // Just initializing pathlib.Path object is OK, we can return | ||
| // early in that scenario. | ||
| if let Some(qualified_name) = semantic.resolve_qualified_name(call.func.as_ref()) { | ||
| let segments = qualified_name.segments(); | ||
| if !matches!(segments, ["os", "path", _]) { | ||
| return; | ||
| } | ||
|
|
||
| let Some(os_path_method) = segments.last() else { | ||
| return; | ||
| }; | ||
|
|
||
| if maybe_calling_io_operation(os_path_method) { | ||
| checker.report_diagnostic( | ||
| BlockingPathMethodInAsyncFunction { | ||
| path_library: "os.path".to_string(), | ||
| }, | ||
| call.func.range(), | ||
| ); | ||
| } | ||
| return; | ||
| } | ||
|
|
||
| let Some(ast::ExprAttribute { value, attr, .. }) = call.func.as_attribute_expr() else { | ||
| return; | ||
| }; | ||
|
|
||
| if !maybe_calling_io_operation(attr.id.as_str()) { | ||
| return; | ||
| } | ||
|
|
||
| // Check if an expression is a pathlib.Path constructor that directly | ||
| // calls an I/O method. | ||
| if PathlibPathChecker::match_initializer(value, semantic) { | ||
| checker.report_diagnostic( | ||
| BlockingPathMethodInAsyncFunction { | ||
| path_library: "pathlib.Path".to_string(), | ||
| }, | ||
| call.func.range(), | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| // Lastly, check if a variable is a pathlib.Path instance and it's | ||
| // calling an I/O method. | ||
| let Some(name) = value.as_name_expr() else { | ||
| return; | ||
| }; | ||
|
|
||
| let Some(binding) = semantic.only_binding(name).map(|id| semantic.binding(id)) else { | ||
| return; | ||
| }; | ||
|
|
||
| if check_type::<PathlibPathChecker>(binding, semantic) { | ||
| checker.report_diagnostic( | ||
| BlockingPathMethodInAsyncFunction { | ||
| path_library: "pathlib.Path".to_string(), | ||
| }, | ||
| call.func.range(), | ||
| ); | ||
| } | ||
| } | ||
| struct PathlibPathChecker; | ||
|
|
||
| impl PathlibPathChecker { | ||
| fn is_pathlib_path_constructor( | ||
| semantic: &ruff_python_semantic::SemanticModel, | ||
| expr: &Expr, | ||
| ) -> bool { | ||
| let Some(qualified_name) = semantic.resolve_qualified_name(expr) else { | ||
| return false; | ||
| }; | ||
|
|
||
| matches!( | ||
| qualified_name.segments(), | ||
| [ | ||
| "pathlib", | ||
| "Path" | ||
| | "PosixPath" | ||
| | "PurePath" | ||
| | "PurePosixPath" | ||
| | "PureWindowsPath" | ||
| | "WindowsPath" | ||
| ] | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| impl TypeChecker for PathlibPathChecker { | ||
| fn match_annotation(annotation: &Expr, semantic: &ruff_python_semantic::SemanticModel) -> bool { | ||
| if Self::is_pathlib_path_constructor(semantic, annotation) { | ||
| return true; | ||
| } | ||
|
|
||
| let mut found = false; | ||
| traverse_union_and_optional( | ||
| &mut |inner_expr, _| { | ||
| if Self::is_pathlib_path_constructor(semantic, inner_expr) { | ||
| found = true; | ||
| } | ||
| }, | ||
| semantic, | ||
| annotation, | ||
| ); | ||
| found | ||
| } | ||
|
|
||
| fn match_initializer( | ||
| initializer: &Expr, | ||
| semantic: &ruff_python_semantic::SemanticModel, | ||
| ) -> bool { | ||
| let Expr::Call(ast::ExprCall { func, .. }) = initializer else { | ||
| return false; | ||
| }; | ||
|
|
||
| Self::is_pathlib_path_constructor(semantic, func) | ||
| } | ||
| } | ||
|
|
||
| fn maybe_calling_io_operation(attr: &str) -> bool { | ||
| // ".open()" is added to the allow list to let ASYNC 230 handle | ||
| // that case. | ||
| !matches!( | ||
| attr, | ||
| "ALLOW_MISSING" | ||
| | "altsep" | ||
| | "anchor" | ||
| | "as_posix" | ||
| | "as_uri" | ||
| | "basename" | ||
| | "commonpath" | ||
| | "commonprefix" | ||
| | "curdir" | ||
| | "defpath" | ||
| | "devnull" | ||
| | "dirname" | ||
| | "drive" | ||
| | "expandvars" | ||
| | "extsep" | ||
| | "genericpath" | ||
| | "is_absolute" | ||
| | "is_relative_to" | ||
| | "is_reserved" | ||
| | "isabs" | ||
| | "join" | ||
| | "joinpath" | ||
| | "match" | ||
| | "name" | ||
| | "normcase" | ||
| | "os" | ||
| | "open" | ||
| | "pardir" | ||
| | "parent" | ||
| | "parents" | ||
| | "parts" | ||
| | "pathsep" | ||
| | "relative_to" | ||
| | "root" | ||
| | "samestat" | ||
| | "sep" | ||
| | "split" | ||
| | "splitdrive" | ||
| | "splitext" | ||
| | "splitroot" | ||
| | "stem" | ||
| | "suffix" | ||
| | "suffixes" | ||
| | "supports_unicode_filenames" | ||
| | "sys" | ||
| | "with_name" | ||
| | "with_segments" | ||
| | "with_stem" | ||
| | "with_suffix" | ||
| ) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.