repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_basename.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_basename.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_basename_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.basename`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.name` can improve readability over the `os.path`
/// module's counterparts (e.g., `os.path.basename()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.path.basename(__file__)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path(__file__).name
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is always marked as unsafe because the replacement is not always semantically
/// equivalent to the original code. In particular, `pathlib` performs path normalization,
/// which can alter the result compared to `os.path.basename`. For example, this normalization:
///
/// - Collapses consecutive slashes (e.g., `"a//b"` β `"a/b"`).
/// - Removes trailing slashes (e.g., `"a/b/"` β `"a/b"`).
/// - Eliminates `"."` (e.g., `"a/./b"` β `"a/b"`).
///
/// As a result, code relying on the exact string returned by `os.path.basename`
/// may behave differently after the fix.
///
/// ## References
/// - [Python documentation: `PurePath.name`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.name)
/// - [Python documentation: `os.path.basename`](https://docs.python.org/3/library/os.path.html#os.path.basename)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathBasename;
impl Violation for OsPathBasename {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.basename()` should be replaced by `Path.name`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).name`".to_string())
}
}
/// PTH119
pub(crate) fn os_path_basename(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "basename"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"name",
"p",
is_fix_os_path_basename_enabled(checker.settings()),
OsPathBasename,
Applicability::Unsafe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_mkdir.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_mkdir.rs | use ruff_diagnostics::{Applicability, Edit, Fix};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::preview::is_fix_os_mkdir_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
has_unknown_keywords_or_starred_expr, is_keyword_only_argument_non_default,
is_pathlib_path_call,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.mkdir`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.mkdir()` can improve readability over the `os`
/// module's counterparts (e.g., `os.mkdir()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.mkdir("./directory/")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("./directory/").mkdir()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.mkdir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir)
/// - [Python documentation: `os.mkdir`](https://docs.python.org/3/library/os.html#os.mkdir)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsMkdir;
impl Violation for OsMkdir {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.mkdir()` should be replaced by `Path.mkdir()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).mkdir()`".to_string())
}
}
/// PTH102
pub(crate) fn os_mkdir(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "mkdir"] {
return;
}
// `dir_fd` is not supported by pathlib, so check if it's set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.mkdir)
// ```text
// 0 1 2
// os.mkdir(path, mode=0o777, *, dir_fd=None)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") {
return;
}
let range = call.range();
let mut diagnostic = checker.report_diagnostic(OsMkdir, call.func.range());
let Some(path) = call.arguments.find_argument_value("path", 0) else {
return;
};
if !is_fix_os_mkdir_enabled(checker.settings()) {
return;
}
if call.arguments.len() > 2 {
return;
}
if has_unknown_keywords_or_starred_expr(&call.arguments, &["path", "mode"]) {
return;
}
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
call.start(),
checker.semantic(),
)?;
let applicability = if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
let path_code = checker.locator().slice(path.range());
let mkdir_args = call
.arguments
.find_argument_value("mode", 1)
.map(|expr| format!("mode={}", checker.locator().slice(expr.range())))
.unwrap_or_default();
let replacement = if is_pathlib_path_call(checker, path) {
format!("{path_code}.mkdir({mkdir_args})")
} else {
format!("{binding}({path_code}).mkdir({mkdir_args})")
};
Ok(Fix::applicable_edits(
Edit::range_replacement(replacement, range),
[import_edit],
applicability,
))
});
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_rmdir.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_rmdir.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_rmdir_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
check_os_pathlib_single_arg_calls, is_keyword_only_argument_non_default,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.rmdir`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.rmdir()` can improve readability over the `os`
/// module's counterparts (e.g., `os.rmdir()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.rmdir("folder/")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("folder/").rmdir()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.rmdir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.rmdir)
/// - [Python documentation: `os.rmdir`](https://docs.python.org/3/library/os.html#os.rmdir)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsRmdir;
impl Violation for OsRmdir {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.rmdir()` should be replaced by `Path.rmdir()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).rmdir()`".to_string())
}
}
/// PTH106
pub(crate) fn os_rmdir(checker: &Checker, call: &ExprCall, segments: &[&str]) {
// `dir_fd` is not supported by pathlib, so check if it's set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.rmdir)
// ```text
// 0 1
// os.rmdir(path, *, dir_fd=None)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") {
return;
}
if segments != ["os", "rmdir"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"rmdir()",
"path",
is_fix_os_rmdir_enabled(checker.settings()),
OsRmdir,
Applicability::Safe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/replaceable_by_pathlib.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/replaceable_by_pathlib.rs | use ruff_python_ast::{Expr, ExprCall};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::rules::flake8_use_pathlib::helpers::{
is_file_descriptor, is_keyword_only_argument_non_default,
};
use crate::rules::flake8_use_pathlib::{
rules::Glob,
violations::{Joiner, OsListdir, OsPathJoin, OsPathSplitext, OsStat, PyPath},
};
pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) {
let Some(qualified_name) = checker.semantic().resolve_qualified_name(&call.func) else {
return;
};
let range = call.func.range();
match qualified_name.segments() {
// PTH116
["os", "stat"] => {
// `dir_fd` is not supported by pathlib, so check if it's set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.stat)
// ```text
// 0 1 2
// os.stat(path, *, dir_fd=None, follow_symlinks=True)
// ```
if call
.arguments
.find_argument_value("path", 0)
.is_some_and(|expr| is_file_descriptor(expr, checker.semantic()))
|| is_keyword_only_argument_non_default(&call.arguments, "dir_fd")
{
return;
}
checker.report_diagnostic_if_enabled(OsStat, range)
}
// PTH118
["os", "path", "join"] => checker.report_diagnostic_if_enabled(
OsPathJoin {
module: "path".to_string(),
joiner: if call.arguments.args.iter().any(Expr::is_starred_expr) {
Joiner::Joinpath
} else {
Joiner::Slash
},
},
range,
),
["os", "sep", "join"] => checker.report_diagnostic_if_enabled(
OsPathJoin {
module: "sep".to_string(),
joiner: if call.arguments.args.iter().any(Expr::is_starred_expr) {
Joiner::Joinpath
} else {
Joiner::Slash
},
},
range,
),
// PTH122
["os", "path", "splitext"] => checker.report_diagnostic_if_enabled(OsPathSplitext, range),
// PTH124
["py", "path", "local"] => checker.report_diagnostic_if_enabled(PyPath, range),
// PTH207
["glob", "glob"] => {
// `dir_fd` is not supported by pathlib, so check if it's set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/glob.html#glob.glob)
// ```text
// 0 1 2 3 4
// glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") {
return;
}
checker.report_diagnostic_if_enabled(
Glob {
function: "glob".to_string(),
},
range,
)
}
["glob", "iglob"] => {
// `dir_fd` is not supported by pathlib, so check if it's set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/glob.html#glob.iglob)
// ```text
// 0 1 2 3 4
// glob.iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") {
return;
}
checker.report_diagnostic_if_enabled(
Glob {
function: "iglob".to_string(),
},
range,
)
}
// PTH208
["os", "listdir"] => {
if call
.arguments
.find_argument_value("path", 0)
.is_some_and(|expr| is_file_descriptor(expr, checker.semantic()))
{
return;
}
checker.report_diagnostic_if_enabled(OsListdir, range)
}
_ => return,
};
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_rename.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_rename.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_rename_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
check_os_pathlib_two_arg_calls, has_unknown_keywords_or_starred_expr,
is_keyword_only_argument_non_default, is_top_level_expression_in_statement,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.rename`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.rename()` can improve readability over the `os`
/// module's counterparts (e.g., `os.rename()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.rename("old.py", "new.py")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("old.py").rename("new.py")
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
/// Additionally, the fix is marked as unsafe when the return value is used because the type changes
/// from `None` to a `Path` object.
///
/// ## References
/// - [Python documentation: `Path.rename`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.rename)
/// - [Python documentation: `os.rename`](https://docs.python.org/3/library/os.html#os.rename)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsRename;
impl Violation for OsRename {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.rename()` should be replaced by `Path.rename()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).rename(...)`".to_string())
}
}
/// PTH104
pub(crate) fn os_rename(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "rename"] {
return;
}
// `src_dir_fd` and `dst_dir_fd` are not supported by pathlib, so check if they are
// set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.rename)
// ```text
// 0 1 2 3
// os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "src_dir_fd")
|| is_keyword_only_argument_non_default(&call.arguments, "dst_dir_fd")
{
return;
}
let fix_enabled = is_fix_os_rename_enabled(checker.settings())
&& !has_unknown_keywords_or_starred_expr(
&call.arguments,
&["src", "dst", "src_dir_fd", "dst_dir_fd"],
);
// Unsafe when the fix would delete comments or change a used return value
let applicability = if !is_top_level_expression_in_statement(checker) {
// Unsafe because the return type changes (None -> Path)
Applicability::Unsafe
} else {
Applicability::Safe
};
check_os_pathlib_two_arg_calls(
checker,
call,
"rename",
"src",
"dst",
fix_enabled,
OsRename,
applicability,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/mod.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/mod.rs | pub(crate) use builtin_open::*;
pub(crate) use glob_rule::*;
pub(crate) use invalid_pathlib_with_suffix::*;
pub(crate) use os_chmod::*;
pub(crate) use os_getcwd::*;
pub(crate) use os_makedirs::*;
pub(crate) use os_mkdir::*;
pub(crate) use os_path_abspath::*;
pub(crate) use os_path_basename::*;
pub(crate) use os_path_dirname::*;
pub(crate) use os_path_exists::*;
pub(crate) use os_path_expanduser::*;
pub(crate) use os_path_getatime::*;
pub(crate) use os_path_getctime::*;
pub(crate) use os_path_getmtime::*;
pub(crate) use os_path_getsize::*;
pub(crate) use os_path_isabs::*;
pub(crate) use os_path_isdir::*;
pub(crate) use os_path_isfile::*;
pub(crate) use os_path_islink::*;
pub(crate) use os_path_samefile::*;
pub(crate) use os_readlink::*;
pub(crate) use os_remove::*;
pub(crate) use os_rename::*;
pub(crate) use os_replace::*;
pub(crate) use os_rmdir::*;
pub(crate) use os_sep_split::*;
pub(crate) use os_symlink::*;
pub(crate) use os_unlink::*;
pub(crate) use path_constructor_current_directory::*;
pub(crate) use replaceable_by_pathlib::*;
mod builtin_open;
mod glob_rule;
mod invalid_pathlib_with_suffix;
mod os_chmod;
mod os_getcwd;
mod os_makedirs;
mod os_mkdir;
mod os_path_abspath;
mod os_path_basename;
mod os_path_dirname;
mod os_path_exists;
mod os_path_expanduser;
mod os_path_getatime;
mod os_path_getctime;
mod os_path_getmtime;
mod os_path_getsize;
mod os_path_isabs;
mod os_path_isdir;
mod os_path_isfile;
mod os_path_islink;
mod os_path_samefile;
mod os_readlink;
mod os_remove;
mod os_rename;
mod os_replace;
mod os_rmdir;
mod os_sep_split;
mod os_symlink;
mod os_unlink;
mod path_constructor_current_directory;
mod replaceable_by_pathlib;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_getsize.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_getsize.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_getsize_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.getsize`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`.
///
/// When possible, using `Path` object methods such as `Path.stat()` can
/// improve readability over the `os.path` module's counterparts (e.g.,
/// `os.path.getsize()`).
///
/// ## Example
/// ```python
/// import os
///
/// os.path.getsize(__file__)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path(__file__).stat().st_size
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)
/// - [Python documentation: `os.path.getsize`](https://docs.python.org/3/library/os.path.html#os.path.getsize)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.279")]
pub(crate) struct OsPathGetsize;
impl Violation for OsPathGetsize {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.getsize` should be replaced by `Path.stat().st_size`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).stat().st_size`".to_string())
}
}
/// PTH202
pub(crate) fn os_path_getsize(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "getsize"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"stat().st_size",
"filename",
is_fix_os_path_getsize_enabled(checker.settings()),
OsPathGetsize,
Applicability::Safe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_replace.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_replace.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_replace_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
check_os_pathlib_two_arg_calls, has_unknown_keywords_or_starred_expr,
is_keyword_only_argument_non_default, is_top_level_expression_in_statement,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.replace`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.replace()` can improve readability over the `os`
/// module's counterparts (e.g., `os.replace()`).
///
/// Note that `os` functions may be preferable if performance is a concern,
/// e.g., in hot loops.
///
/// ## Examples
/// ```python
/// import os
///
/// os.replace("old.py", "new.py")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("old.py").replace("new.py")
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
/// Additionally, the fix is marked as unsafe when the return value is used because the type changes
/// from `None` to a `Path` object.
///
/// ## References
/// - [Python documentation: `Path.replace`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.replace)
/// - [Python documentation: `os.replace`](https://docs.python.org/3/library/os.html#os.replace)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsReplace;
impl Violation for OsReplace {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.replace()` should be replaced by `Path.replace()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).replace(...)`".to_string())
}
}
/// PTH105
pub(crate) fn os_replace(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "replace"] {
return;
}
// `src_dir_fd` and `dst_dir_fd` are not supported by pathlib, so check if they are
// set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.replace)
// ```text
// 0 1 2 3
// os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "src_dir_fd")
|| is_keyword_only_argument_non_default(&call.arguments, "dst_dir_fd")
{
return;
}
let fix_enabled = is_fix_os_replace_enabled(checker.settings())
&& !has_unknown_keywords_or_starred_expr(
&call.arguments,
&["src", "dst", "src_dir_fd", "dst_dir_fd"],
);
// Unsafe when the fix would delete comments or change a used return value
let applicability = if !is_top_level_expression_in_statement(checker) {
// Unsafe because the return type changes (None -> Path)
Applicability::Unsafe
} else {
Applicability::Safe
};
check_os_pathlib_two_arg_calls(
checker,
call,
"replace",
"src",
"dst",
fix_enabled,
OsReplace,
applicability,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/glob_rule.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/glob_rule.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::Violation;
/// ## What it does
/// Checks for the use of `glob.glob()` and `glob.iglob()`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os` and `glob`.
///
/// When possible, using `Path` object methods such as `Path.glob()` can
/// improve readability over their low-level counterparts (e.g.,
/// `glob.glob()`).
///
/// Note that `glob.glob()` and `Path.glob()` are not exact equivalents:
///
/// | | `glob`-module functions | `Path.glob()` |
/// |-------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------|
/// | Hidden files | Hidden files are excluded by default. On Python 3.11+, the `include_hidden` keyword can be used to include hidden directories. | Includes hidden files by default. |
/// | Eagerness | `glob.iglob()` returns a lazy iterator. Under the hood, `glob.glob()` simply converts the iterator to a list. | `Path.glob()` returns a lazy iterator. |
/// | Working directory | `glob.glob()` and `glob.iglob()` take a `root_dir` keyword to set the current working directory. | `Path.rglob()` can be used to return the relative path. |
/// | Globstar (`**`) | The `recursive` flag must be set to `True` for the `**` pattern to match any files and zero or more directories, subdirectories, and symbolic links. | The `**` pattern in `Path.glob()` means "this directory and all subdirectories, recursively". In other words, it enables recursive globbing. |
///
/// ## Example
/// ```python
/// import glob
/// import os
///
/// glob.glob(os.path.join("my_path", "requirements*.txt"))
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("my_path").glob("requirements*.txt")
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## References
/// - [Python documentation: `Path.glob`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob)
/// - [Python documentation: `Path.rglob`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob)
/// - [Python documentation: `glob.glob`](https://docs.python.org/3/library/glob.html#glob.glob)
/// - [Python documentation: `glob.iglob`](https://docs.python.org/3/library/glob.html#glob.iglob)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.281")]
pub(crate) struct Glob {
pub function: String,
}
impl Violation for Glob {
#[derive_message_formats]
fn message(&self) -> String {
let Glob { function } = self;
format!("Replace `{function}` with `Path.glob` or `Path.rglob`")
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_samefile.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_samefile.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_samefile_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
check_os_pathlib_two_arg_calls, has_unknown_keywords_or_starred_expr,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.samefile`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.samefile()` can improve readability over the `os.path`
/// module's counterparts (e.g., `os.path.samefile()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.path.samefile("f1.py", "f2.py")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("f1.py").samefile("f2.py")
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.samefile`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.samefile)
/// - [Python documentation: `os.path.samefile`](https://docs.python.org/3/library/os.path.html#os.path.samefile)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathSamefile;
impl Violation for OsPathSamefile {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.samefile()` should be replaced by `Path.samefile()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).samefile()`".to_string())
}
}
/// PTH121
pub(crate) fn os_path_samefile(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "samefile"] {
return;
}
let fix_enabled = is_fix_os_path_samefile_enabled(checker.settings())
&& !has_unknown_keywords_or_starred_expr(&call.arguments, &["f1", "f2"]);
check_os_pathlib_two_arg_calls(
checker,
call,
"samefile",
"f1",
"f2",
fix_enabled,
OsPathSamefile,
Applicability::Safe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_isdir.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_isdir.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_isdir_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.isdir`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.is_dir()` can improve readability over the `os.path`
/// module's counterparts (e.g., `os.path.isdir()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.path.isdir("docs")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("docs").is_dir()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.is_dir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_dir)
/// - [Python documentation: `os.path.isdir`](https://docs.python.org/3/library/os.path.html#os.path.isdir)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathIsdir;
impl Violation for OsPathIsdir {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.isdir()` should be replaced by `Path.is_dir()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).is_dir()`".to_string())
}
}
/// PTH112
pub(crate) fn os_path_isdir(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "isdir"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"is_dir()",
"s",
is_fix_os_path_isdir_enabled(checker.settings()),
OsPathIsdir,
Applicability::Safe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_sep_split.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_sep_split.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, ExprAttribute};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for uses of `.split(os.sep)`
///
/// ## Why is this bad?
/// The `pathlib` module in the standard library should be used for path
/// manipulation. It provides a high-level API with the functionality
/// needed for common operations on `Path` objects.
///
/// ## Example
/// If not all parts of the path are needed, then the `name` and `parent`
/// attributes of the `Path` object should be used. Otherwise, the `parts`
/// attribute can be used as shown in the last example.
/// ```python
/// import os
///
/// "path/to/file_name.txt".split(os.sep)[-1]
///
/// "path/to/file_name.txt".split(os.sep)[-2]
///
/// # Iterating over the path parts
/// if any(part in blocklist for part in "my/file/path".split(os.sep)):
/// ...
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("path/to/file_name.txt").name
///
/// Path("path/to/file_name.txt").parent.name
///
/// # Iterating over the path parts
/// if any(part in blocklist for part in Path("my/file/path").parts):
/// ...
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than working directly with strings,
/// especially on older versions of Python.
///
/// ## References
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.281")]
pub(crate) struct OsSepSplit;
impl Violation for OsSepSplit {
#[derive_message_formats]
fn message(&self) -> String {
"Replace `.split(os.sep)` with `Path.parts`".to_string()
}
}
/// PTH206
pub(crate) fn os_sep_split(checker: &Checker, call: &ast::ExprCall) {
if !checker.semantic().seen_module(Modules::OS) {
return;
}
let Expr::Attribute(ExprAttribute { attr, .. }) = call.func.as_ref() else {
return;
};
if attr.as_str() != "split" {
return;
}
// Match `.split(os.sep)` or `.split(sep=os.sep)`, but avoid cases in which a `maxsplit` is
// specified.
if call.arguments.len() != 1 {
return;
}
let Some(sep) = call.arguments.find_argument_value("sep", 0) else {
return;
};
if !checker
.semantic()
.resolve_qualified_name(sep)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["os", "sep"]))
{
return;
}
checker.report_diagnostic(OsSepSplit, attr.range());
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_getctime.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_getctime.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_getctime_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.getctime`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`.
///
/// When possible, using `Path` object methods such as `Path.stat()` can
/// improve readability over the `os.path` module's counterparts (e.g.,
/// `os.path.getctime()`).
///
/// ## Example
/// ```python
/// import os
///
/// os.path.getctime(__file__)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path(__file__).stat().st_ctime
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)
/// - [Python documentation: `os.path.getctime`](https://docs.python.org/3/library/os.path.html#os.path.getctime)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.279")]
pub(crate) struct OsPathGetctime;
impl Violation for OsPathGetctime {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.getctime` should be replaced by `Path.stat().st_ctime`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path.stat(...).st_ctime`".to_string())
}
}
/// PTH205
pub(crate) fn os_path_getctime(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "getctime"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"stat().st_ctime",
"filename",
is_fix_os_path_getctime_enabled(checker.settings()),
OsPathGetctime,
Applicability::Safe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_symlink.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_symlink.rs | use ruff_diagnostics::{Applicability, Edit, Fix};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::preview::is_fix_os_symlink_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
has_unknown_keywords_or_starred_expr, is_keyword_only_argument_non_default,
is_pathlib_path_call,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.symlink`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.symlink`.
///
/// ## Example
/// ```python
/// import os
///
/// os.symlink("usr/bin/python", "tmp/python", target_is_directory=False)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("tmp/python").symlink_to("usr/bin/python")
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.symlink_to`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.symlink_to)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.13.0")]
pub(crate) struct OsSymlink;
impl Violation for OsSymlink {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.symlink` should be replaced by `Path.symlink_to`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).symlink_to(...)`".to_string())
}
}
/// PTH211
pub(crate) fn os_symlink(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "symlink"] {
return;
}
// `dir_fd` is not supported by pathlib, so check if there are non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.symlink)
// ```text
// 0 1 2 3
// os.symlink(src, dst, target_is_directory=False, *, dir_fd=None)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") {
return;
}
let range = call.range();
let mut diagnostic = checker.report_diagnostic(OsSymlink, call.func.range());
if !is_fix_os_symlink_enabled(checker.settings()) {
return;
}
if call.arguments.len() > 3 {
return;
}
if has_unknown_keywords_or_starred_expr(
&call.arguments,
&["src", "dst", "target_is_directory", "dir_fd"],
) {
return;
}
let (Some(src), Some(dst)) = (
call.arguments.find_argument_value("src", 0),
call.arguments.find_argument_value("dst", 1),
) else {
return;
};
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
call.start(),
checker.semantic(),
)?;
let applicability = if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
let locator = checker.locator();
let src_code = locator.slice(src.range());
let dst_code = locator.slice(dst.range());
let target_is_directory = call
.arguments
.find_argument_value("target_is_directory", 2)
.and_then(|expr| {
let code = locator.slice(expr.range());
expr.as_boolean_literal_expr()
.is_none_or(|bl| bl.value)
.then_some(format!(", target_is_directory={code}"))
})
.unwrap_or_default();
let replacement = if is_pathlib_path_call(checker, dst) {
format!("{dst_code}.symlink_to({src_code}{target_is_directory})")
} else {
format!("{binding}({dst_code}).symlink_to({src_code}{target_is_directory})")
};
Ok(Fix::applicable_edits(
Edit::range_replacement(replacement, range),
[import_edit],
applicability,
))
});
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/builtin_open.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/builtin_open.rs | use ruff_diagnostics::{Applicability, Edit, Fix};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{ArgOrKeyword, Expr, ExprBooleanLiteral, ExprCall};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::preview::is_fix_builtin_open_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
has_unknown_keywords_or_starred_expr, is_argument_non_default, is_file_descriptor,
is_pathlib_path_call,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of the `open()` builtin.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation. When possible,
/// using `Path` object methods such as `Path.open()` can improve readability
/// over the `open` builtin.
///
/// ## Examples
/// ```python
/// with open("f1.py", "wb") as fp:
/// ...
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// with Path("f1.py").open("wb") as fp:
/// ...
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than working directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.open`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.open)
/// - [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct BuiltinOpen;
impl Violation for BuiltinOpen {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`open()` should be replaced by `Path.open()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path.open()`".to_string())
}
}
// PTH123
pub(crate) fn builtin_open(checker: &Checker, call: &ExprCall, segments: &[&str]) {
// `closefd` and `opener` are not supported by pathlib, so check if they
// are set to non-default values.
// https://github.com/astral-sh/ruff/issues/7620
// Signature as of Python 3.11 (https://docs.python.org/3/library/functions.html#open):
// ```text
// builtins.open(
// file, 0
// mode='r', 1
// buffering=-1, 2
// encoding=None, 3
// errors=None, 4
// newline=None, 5
// closefd=True, 6 <= not supported
// opener=None 7 <= not supported
// )
// ```
// For `pathlib` (https://docs.python.org/3/library/pathlib.html#pathlib.Path.open):
// ```text
// Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
// ```
let file_arg = call.arguments.find_argument_value("file", 0);
if call
.arguments
.find_argument_value("closefd", 6)
.is_some_and(|expr| {
!matches!(
expr,
Expr::BooleanLiteral(ExprBooleanLiteral { value: true, .. })
)
})
|| is_argument_non_default(&call.arguments, "opener", 7)
|| file_arg.is_some_and(|expr| is_file_descriptor(expr, checker.semantic()))
{
return;
}
if !matches!(segments, ["" | "builtins", "open"]) {
return;
}
let mut diagnostic = checker.report_diagnostic(BuiltinOpen, call.func.range());
if !is_fix_builtin_open_enabled(checker.settings()) {
return;
}
let Some(file) = file_arg else {
return;
};
if has_unknown_keywords_or_starred_expr(
&call.arguments,
&[
"file",
"mode",
"buffering",
"encoding",
"errors",
"newline",
"closefd",
"opener",
],
) {
return;
}
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
call.start(),
checker.semantic(),
)?;
let locator = checker.locator();
let file_code = locator.slice(file.range());
let args = |i: usize, arg: ArgOrKeyword| match arg {
ArgOrKeyword::Arg(expr) => {
if expr.range() == file.range() || i == 6 || i == 7 {
None
} else {
Some(locator.slice(expr.range()))
}
}
ArgOrKeyword::Keyword(kw) => match kw.arg.as_deref() {
Some("mode" | "buffering" | "encoding" | "errors" | "newline") => {
Some(locator.slice(kw))
}
_ => None,
},
};
let open_args = itertools::join(
call.arguments
.arguments_source_order()
.enumerate()
.filter_map(|(i, arg)| args(i, arg)),
", ",
);
let replacement = if is_pathlib_path_call(checker, file) {
format!("{file_code}.open({open_args})")
} else {
format!("{binding}({file_code}).open({open_args})")
};
let range = call.range();
let applicability = if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
Ok(Fix::applicable_edits(
Edit::range_replacement(replacement, range),
[import_edit],
applicability,
))
});
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_dirname.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_dirname.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_dirname_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.dirname`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.parent` can improve readability over the `os.path`
/// module's counterparts (e.g., `os.path.dirname()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.path.dirname(__file__)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path(__file__).parent
/// ```
///
/// ## Fix Safety
/// This rule's fix is always marked as unsafe because the replacement is not always semantically
/// equivalent to the original code. In particular, `pathlib` performs path normalization,
/// which can alter the result compared to `os.path.dirname`. For example, this normalization:
///
/// - Collapses consecutive slashes (e.g., `"a//b"` β `"a/b"`).
/// - Removes trailing slashes (e.g., `"a/b/"` β `"a/b"`).
/// - Eliminates `"."` (e.g., `"a/./b"` β `"a/b"`).
///
/// As a result, code relying on the exact string returned by `os.path.dirname`
/// may behave differently after the fix.
///
/// Additionally, the fix is marked as unsafe because `os.path.dirname()` returns `str` or `bytes` (`AnyStr`),
/// while `Path.parent` returns a `Path` object. This change in return type can break code that uses
/// the return value.
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## References
/// - [Python documentation: `PurePath.parent`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent)
/// - [Python documentation: `os.path.dirname`](https://docs.python.org/3/library/os.path.html#os.path.dirname)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathDirname;
impl Violation for OsPathDirname {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.dirname()` should be replaced by `Path.parent`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).parent`".to_string())
}
}
/// PTH120
pub(crate) fn os_path_dirname(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "dirname"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"parent",
"p",
is_fix_os_path_dirname_enabled(checker.settings()),
OsPathDirname,
Applicability::Unsafe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_unlink.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_unlink.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_unlink_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
check_os_pathlib_single_arg_calls, is_keyword_only_argument_non_default,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.unlink`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.unlink()` can improve readability over the `os`
/// module's counterparts (e.g., `os.unlink()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.unlink("file.py")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("file.py").unlink()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.unlink`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.unlink)
/// - [Python documentation: `os.unlink`](https://docs.python.org/3/library/os.html#os.unlink)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsUnlink;
impl Violation for OsUnlink {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.unlink()` should be replaced by `Path.unlink()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).unlink()`".to_string())
}
}
/// PTH108
pub(crate) fn os_unlink(checker: &Checker, call: &ExprCall, segments: &[&str]) {
// `dir_fd` is not supported by pathlib, so check if it's set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.unlink)
// ```text
// 0 1
// os.unlink(path, *, dir_fd=None)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") {
return;
}
if segments != ["os", "unlink"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"unlink()",
"path",
is_fix_os_unlink_enabled(checker.settings()),
OsUnlink,
Applicability::Safe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_abspath.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_abspath.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_abspath_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
check_os_pathlib_single_arg_calls, has_unknown_keywords_or_starred_expr,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.abspath`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.resolve()` can improve readability over the `os.path`
/// module's counterparts (e.g., `os.path.abspath()`).
///
/// ## Examples
/// ```python
/// import os
///
/// file_path = os.path.abspath("../path/to/file")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// file_path = Path("../path/to/file").resolve()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is always marked as unsafe because `Path.resolve()` resolves symlinks, while
/// `os.path.abspath()` does not. If resolving symlinks is important, you may need to use
/// `Path.absolute()`. However, `Path.absolute()` also does not remove any `..` components in a
/// path, unlike `os.path.abspath()` and `Path.resolve()`, so if that specific combination of
/// behaviors is required, there's no existing `pathlib` alternative. See CPython issue
/// [#69200](https://github.com/python/cpython/issues/69200).
///
/// Additionally, the fix is marked as unsafe because `os.path.abspath()` returns `str` or `bytes` (`AnyStr`),
/// while `Path.resolve()` returns a `Path` object. This change in return type can break code that uses
/// the return value.
///
/// ## References
/// - [Python documentation: `Path.resolve`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.resolve)
/// - [Python documentation: `os.path.abspath`](https://docs.python.org/3/library/os.path.html#os.path.abspath)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathAbspath;
impl Violation for OsPathAbspath {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.abspath()` should be replaced by `Path.resolve()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).resolve()`".to_string())
}
}
/// PTH100
pub(crate) fn os_path_abspath(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "abspath"] {
return;
}
if has_unknown_keywords_or_starred_expr(&call.arguments, &["path"]) {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"resolve()",
"path",
is_fix_os_path_abspath_enabled(checker.settings()),
OsPathAbspath,
Applicability::Unsafe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_exists.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_exists.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_exists_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.exists`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.exists()` can improve readability over the `os.path`
/// module's counterparts (e.g., `os.path.exists()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.path.exists("file.py")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("file.py").exists()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.exists`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.exists)
/// - [Python documentation: `os.path.exists`](https://docs.python.org/3/library/os.path.html#os.path.exists)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathExists;
impl Violation for OsPathExists {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.exists()` should be replaced by `Path.exists()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).exists()`".to_string())
}
}
/// PTH110
pub(crate) fn os_path_exists(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "exists"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"exists()",
"path",
is_fix_os_path_exists_enabled(checker.settings()),
OsPathExists,
Applicability::Safe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_getatime.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_getatime.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_getatime_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.getatime`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`.
///
/// When possible, using `Path` object methods such as `Path.stat()` can
/// improve readability over the `os.path` module's counterparts (e.g.,
/// `os.path.getatime()`).
///
/// ## Example
/// ```python
/// import os
///
/// os.path.getatime(__file__)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path(__file__).stat().st_atime
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)
/// - [Python documentation: `os.path.getatime`](https://docs.python.org/3/library/os.path.html#os.path.getatime)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.279")]
pub(crate) struct OsPathGetatime;
impl Violation for OsPathGetatime {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.getatime` should be replaced by `Path.stat().st_atime`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path.stat(...).st_atime`".to_string())
}
}
/// PTH203
pub(crate) fn os_path_getatime(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "getatime"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"stat().st_atime",
"filename",
is_fix_os_path_getatime_enabled(checker.settings()),
OsPathGetatime,
Applicability::Safe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/settings.rs | crates/ruff_linter/src/rules/flake8_comprehensions/settings.rs | //! Settings for the `flake8-comprehensions` plugin.
use crate::display_settings;
use ruff_macros::CacheKey;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, Default, CacheKey)]
pub struct Settings {
pub allow_dict_calls_with_keyword_arguments: bool,
}
impl Display for Settings {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.flake8_comprehensions",
fields = [
self.allow_dict_calls_with_keyword_arguments
]
}
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/helpers.rs | crates/ruff_linter/src/rules/flake8_comprehensions/helpers.rs | use ruff_python_ast::{Expr, Keyword};
pub(super) fn exactly_one_argument_with_matching_function<'a>(
name: &str,
func: &Expr,
args: &'a [Expr],
keywords: &[Keyword],
) -> Option<&'a Expr> {
let [arg] = args else {
return None;
};
if !keywords.is_empty() {
return None;
}
let func = func.as_name_expr()?;
if func.id != name {
return None;
}
Some(arg)
}
pub(super) fn first_argument_with_matching_function<'a>(
name: &str,
func: &Expr,
args: &'a [Expr],
) -> Option<&'a Expr> {
if func.as_name_expr().is_some_and(|func| func.id == name) {
args.first()
} else {
None
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/fixes.rs | crates/ruff_linter/src/rules/flake8_comprehensions/fixes.rs | use std::iter;
use anyhow::{Result, bail};
use itertools::Itertools;
use libcst_native::{
Arg, AssignEqual, AssignTargetExpression, Call, Comma, Comment, CompFor, Dict, DictComp,
DictElement, Element, EmptyLine, Expression, GeneratorExp, LeftCurlyBrace, LeftParen,
LeftSquareBracket, ListComp, Name, ParenthesizableWhitespace, ParenthesizedNode,
ParenthesizedWhitespace, RightCurlyBrace, RightParen, RightSquareBracket, SetComp,
SimpleString, SimpleWhitespace, TrailingWhitespace, Tuple,
};
use ruff_python_ast::{self as ast, Expr, ExprCall};
use ruff_python_codegen::Stylist;
use ruff_python_semantic::SemanticModel;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::cst::helpers::{negate, space};
use crate::fix::codemods::CodegenStylist;
use crate::fix::edits::pad;
use crate::rules::flake8_comprehensions::rules::ObjectType;
use crate::{Edit, Fix};
use crate::{
checkers::ast::Checker,
cst::matchers::{
match_arg, match_call, match_call_mut, match_expression, match_generator_exp, match_lambda,
match_list_comp, match_tuple,
},
};
/// (C402) Convert `dict((x, x) for x in range(3))` to `{x: x for x in
/// range(3)}`.
pub(crate) fn fix_unnecessary_generator_dict(expr: &Expr, checker: &Checker) -> Result<Edit> {
let locator = checker.locator();
let stylist = checker.stylist();
let module_text = locator.slice(expr);
let mut tree = match_expression(module_text)?;
let call = match_call_mut(&mut tree)?;
let arg = match_arg(call)?;
// Extract the (k, v) from `(k, v) for ...`.
let generator_exp = match_generator_exp(&arg.value)?;
let tuple = match_tuple(&generator_exp.elt)?;
let [
Element::Simple { value: key, .. },
Element::Simple { value, .. },
] = &tuple.elements[..]
else {
bail!("Expected tuple to contain two elements");
};
// Insert whitespace before the `for`, since we're removing parentheses, as in:
// ```python
// dict((x, x)for x in range(3))
// ```
let mut for_in = generator_exp.for_in.clone();
if for_in.whitespace_before == ParenthesizableWhitespace::default() {
for_in.whitespace_before =
ParenthesizableWhitespace::SimpleWhitespace(SimpleWhitespace(" "));
}
tree = Expression::DictComp(Box::new(DictComp {
key: Box::new(key.clone()),
value: Box::new(value.clone()),
for_in,
lbrace: LeftCurlyBrace {
whitespace_after: call.whitespace_before_args.clone(),
},
rbrace: RightCurlyBrace {
whitespace_before: arg.whitespace_after_arg.clone(),
},
lpar: vec![],
rpar: vec![],
whitespace_before_colon: ParenthesizableWhitespace::default(),
whitespace_after_colon: space(),
}));
Ok(Edit::range_replacement(
pad_expression(
tree.codegen_stylist(stylist),
expr.range(),
checker.locator(),
checker.semantic(),
),
expr.range(),
))
}
/// (C404) Convert `dict([(i, i) for i in range(3)])` to `{i: i for i in
/// range(3)}`.
pub(crate) fn fix_unnecessary_list_comprehension_dict(
expr: &Expr,
checker: &Checker,
) -> Result<Edit> {
let locator = checker.locator();
let stylist = checker.stylist();
let module_text = locator.slice(expr);
let mut tree = match_expression(module_text)?;
let call = match_call_mut(&mut tree)?;
let arg = match_arg(call)?;
let list_comp = match_list_comp(&arg.value)?;
let tuple = match_tuple(&list_comp.elt)?;
let [
Element::Simple { value: key, .. },
Element::Simple { value, .. },
] = &tuple.elements[..]
else {
bail!("Expected tuple with two elements");
};
// Insert whitespace before the `for`, since we're removing parentheses, as in:
// ```python
// dict((x, x)for x in range(3))
// ```
let mut for_in = list_comp.for_in.clone();
if for_in.whitespace_before == ParenthesizableWhitespace::default() {
for_in.whitespace_before =
ParenthesizableWhitespace::SimpleWhitespace(SimpleWhitespace(" "));
}
tree = Expression::DictComp(Box::new(DictComp {
key: Box::new(key.clone()),
value: Box::new(value.clone()),
for_in,
whitespace_before_colon: ParenthesizableWhitespace::default(),
whitespace_after_colon: space(),
lbrace: LeftCurlyBrace {
whitespace_after: call.whitespace_before_args.clone(),
},
rbrace: RightCurlyBrace {
whitespace_before: arg.whitespace_after_arg.clone(),
},
lpar: list_comp.lpar.clone(),
rpar: list_comp.rpar.clone(),
}));
Ok(Edit::range_replacement(
pad_expression(
tree.codegen_stylist(stylist),
expr.range(),
checker.locator(),
checker.semantic(),
),
expr.range(),
))
}
/// (C406) Convert `dict([(1, 2)])` to `{1: 2}`.
pub(crate) fn fix_unnecessary_literal_dict(expr: &Expr, checker: &Checker) -> Result<Edit> {
let locator = checker.locator();
let stylist = checker.stylist();
// Expr(Call(List|Tuple)))) -> Expr(Dict)))
let module_text = locator.slice(expr);
let mut tree = match_expression(module_text)?;
let call = match_call_mut(&mut tree)?;
let arg = match_arg(call)?;
let elements = match &arg.value {
Expression::Tuple(inner) => &inner.elements,
Expression::List(inner) => &inner.elements,
_ => {
bail!("Expected Expression::Tuple | Expression::List");
}
};
let elements: Vec<DictElement> = elements
.iter()
.map(|element| {
if let Element::Simple {
value: Expression::Tuple(tuple),
comma,
} = element
{
if let Some(Element::Simple { value: key, .. }) = tuple.elements.first() {
if let Some(Element::Simple { value, .. }) = tuple.elements.get(1) {
return Ok(DictElement::Simple {
key: key.clone(),
value: value.clone(),
comma: comma.clone(),
whitespace_before_colon: ParenthesizableWhitespace::default(),
whitespace_after_colon: ParenthesizableWhitespace::SimpleWhitespace(
SimpleWhitespace(" "),
),
});
}
}
}
bail!("Expected each argument to be a tuple of length two")
})
.collect::<Result<Vec<DictElement>>>()?;
tree = Expression::Dict(Box::new(Dict {
elements,
lbrace: LeftCurlyBrace {
whitespace_after: call.whitespace_before_args.clone(),
},
rbrace: RightCurlyBrace {
whitespace_before: arg.whitespace_after_arg.clone(),
},
lpar: vec![],
rpar: vec![],
}));
Ok(Edit::range_replacement(
pad_expression(
tree.codegen_stylist(stylist),
expr.range(),
checker.locator(),
checker.semantic(),
),
expr.range(),
))
}
/// (C408) Convert `dict(a=1, b=2)` to `{"a": 1, "b": 2}`.
pub(crate) fn fix_unnecessary_collection_call(
expr: &ast::ExprCall,
checker: &Checker,
) -> Result<Edit> {
let locator = checker.locator();
let stylist = checker.stylist();
// Expr(Call("dict")))) -> Expr(Dict)
let module_text = locator.slice(expr);
let mut tree = match_expression(module_text)?;
let call = match_call(&tree)?;
// Arena allocator used to create formatted strings of sufficient lifetime,
// below.
let mut arena: Vec<String> = vec![];
let quote = checker
.interpolated_string_quote_style()
.unwrap_or(stylist.quote());
// Quote each argument.
for arg in &call.args {
let quoted = format!(
"{}{}{}",
quote,
arg.keyword
.as_ref()
.expect("Expected dictionary argument to be kwarg")
.value,
quote,
);
arena.push(quoted);
}
let elements = call
.args
.iter()
.enumerate()
.map(|(i, arg)| DictElement::Simple {
key: Expression::SimpleString(Box::new(SimpleString {
value: &arena[i],
lpar: vec![],
rpar: vec![],
})),
value: arg.value.clone(),
comma: arg.comma.clone(),
whitespace_before_colon: ParenthesizableWhitespace::default(),
whitespace_after_colon: ParenthesizableWhitespace::SimpleWhitespace(SimpleWhitespace(
" ",
)),
})
.collect();
tree = Expression::Dict(Box::new(Dict {
elements,
lbrace: LeftCurlyBrace {
whitespace_after: call.whitespace_before_args.clone(),
},
rbrace: RightCurlyBrace {
whitespace_before: call
.args
.last()
.expect("Arguments should be non-empty")
.whitespace_after_arg
.clone(),
},
lpar: vec![],
rpar: vec![],
}));
Ok(Edit::range_replacement(
pad_expression(
tree.codegen_stylist(stylist),
expr.range(),
checker.locator(),
checker.semantic(),
),
expr.range(),
))
}
/// Re-formats the given expression for use within a formatted string.
///
/// For example, when converting a `dict()` call to a dictionary literal within
/// a formatted string, we might naively generate the following code:
///
/// ```python
/// f"{{'a': 1, 'b': 2}}"
/// ```
///
/// However, this is a syntax error under the f-string grammar. As such,
/// this method will pad the start and end of an expression as needed to
/// avoid producing invalid syntax.
pub(crate) fn pad_expression(
content: String,
range: TextRange,
locator: &Locator,
semantic: &SemanticModel,
) -> String {
if !semantic.in_interpolated_string() {
return content;
}
// If the expression is immediately preceded by an opening brace, then
// we need to add a space before the expression.
let prefix = locator.up_to(range.start());
let left_pad = matches!(prefix.chars().next_back(), Some('{'));
// If the expression is immediately preceded by an opening brace, then
// we need to add a space before the expression.
let suffix = locator.after(range.end());
let right_pad = matches!(suffix.chars().next(), Some('}'));
if left_pad && right_pad {
format!(" {content} ")
} else if left_pad {
format!(" {content}")
} else if right_pad {
format!("{content} ")
} else {
content
}
}
/// Like [`pad_expression`], but only pads the start of the expression.
pub(crate) fn pad_start(
content: &str,
range: TextRange,
locator: &Locator,
semantic: &SemanticModel,
) -> String {
if !semantic.in_interpolated_string() {
return content.into();
}
// If the expression is immediately preceded by an opening brace, then
// we need to add a space before the expression.
let prefix = locator.up_to(range.start());
if matches!(prefix.chars().next_back(), Some('{')) {
format!(" {content}")
} else {
content.into()
}
}
/// Like [`pad_expression`], but only pads the end of the expression.
pub(crate) fn pad_end(
content: &str,
range: TextRange,
locator: &Locator,
semantic: &SemanticModel,
) -> String {
if !semantic.in_interpolated_string() {
return content.into();
}
// If the expression is immediately preceded by an opening brace, then
// we need to add a space before the expression.
let suffix = locator.after(range.end());
if matches!(suffix.chars().next(), Some('}')) {
format!("{content} ")
} else {
content.into()
}
}
/// (C411) Convert `list([i * i for i in x])` to `[i * i for i in x]`.
pub(crate) fn fix_unnecessary_list_call(
expr: &Expr,
locator: &Locator,
stylist: &Stylist,
) -> Result<Edit> {
// Expr(Call(List|Tuple)))) -> Expr(List|Tuple)))
let module_text = locator.slice(expr);
let mut tree = match_expression(module_text)?;
let call = match_call_mut(&mut tree)?;
let arg = match_arg(call)?;
tree = arg.value.clone();
Ok(Edit::range_replacement(
tree.codegen_stylist(stylist),
expr.range(),
))
}
/// (C413) Convert `list(sorted([2, 3, 1]))` to `sorted([2, 3, 1])`.
/// (C413) Convert `reversed(sorted([2, 3, 1]))` to `sorted([2, 3, 1],
/// reverse=True)`.
pub(crate) fn fix_unnecessary_call_around_sorted(
expr: &Expr,
locator: &Locator,
stylist: &Stylist,
) -> Result<Edit> {
let module_text = locator.slice(expr);
let mut tree = match_expression(module_text)?;
let outer_call = match_call_mut(&mut tree)?;
let inner_call = match &outer_call.args[..] {
[arg] => match_call(&arg.value)?,
_ => {
bail!("Expected one argument in outer function call");
}
};
let inner_needs_parens = matches!(
inner_call.whitespace_after_func,
ParenthesizableWhitespace::ParenthesizedWhitespace(_)
);
if let Expression::Name(outer_name) = &*outer_call.func {
if outer_name.value == "list" {
tree = Expression::Call(Box::new((*inner_call).clone()));
if inner_needs_parens {
tree = tree.with_parens(LeftParen::default(), RightParen::default());
}
} else {
// If the `reverse` argument is used...
let args = if inner_call.args.iter().any(|arg| {
matches!(
arg.keyword,
Some(Name {
value: "reverse",
..
})
)
}) {
// Negate the `reverse` argument.
inner_call
.args
.clone()
.into_iter()
.map(|mut arg| {
if matches!(
arg.keyword,
Some(Name {
value: "reverse",
..
})
) {
arg.value = negate(&arg.value);
}
arg
})
.collect_vec()
} else {
let mut args = inner_call.args.clone();
// If necessary, parenthesize a generator expression, as a generator expression must
// be parenthesized if it's not a solitary argument. For example, given:
// ```python
// reversed(sorted(i for i in range(42)))
// ```
// Rewrite as:
// ```python
// sorted((i for i in range(42)), reverse=True)
// ```
if let [arg] = args.as_mut_slice() {
if matches!(arg.value, Expression::GeneratorExp(_)) {
if arg.value.lpar().is_empty() && arg.value.rpar().is_empty() {
arg.value = arg
.value
.clone()
.with_parens(LeftParen::default(), RightParen::default());
}
}
}
// Add the `reverse=True` argument.
args.push(Arg {
value: Expression::Name(Box::new(Name {
value: "True",
lpar: vec![],
rpar: vec![],
})),
keyword: Some(Name {
value: "reverse",
lpar: vec![],
rpar: vec![],
}),
equal: Some(AssignEqual {
whitespace_before: ParenthesizableWhitespace::default(),
whitespace_after: ParenthesizableWhitespace::default(),
}),
comma: None,
star: "",
whitespace_after_star: ParenthesizableWhitespace::default(),
whitespace_after_arg: ParenthesizableWhitespace::default(),
});
args
};
tree = Expression::Call(Box::new(Call {
func: inner_call.func.clone(),
args,
lpar: inner_call.lpar.clone(),
rpar: inner_call.rpar.clone(),
whitespace_after_func: inner_call.whitespace_after_func.clone(),
whitespace_before_args: inner_call.whitespace_before_args.clone(),
}));
if inner_needs_parens {
tree = tree.with_parens(LeftParen::default(), RightParen::default());
}
}
}
Ok(Edit::range_replacement(
tree.codegen_stylist(stylist),
expr.range(),
))
}
/// (C414) Convert `sorted(list(foo))` to `sorted(foo)`
pub(crate) fn fix_unnecessary_double_cast_or_process(
expr: &Expr,
locator: &Locator,
stylist: &Stylist,
) -> Result<Edit> {
let module_text = locator.slice(expr);
let mut tree = match_expression(module_text)?;
let outer_call = match_call_mut(&mut tree)?;
outer_call.args = match outer_call.args.split_first() {
Some((first, rest)) => {
let inner_call = match_call(&first.value)?;
if let Some(arg) = inner_call
.args
.iter()
.find(|argument| argument.keyword.is_none())
{
let mut arg = arg.clone();
arg.comma.clone_from(&first.comma);
arg.whitespace_after_arg = first.whitespace_after_arg.clone();
iter::once(arg)
.chain(rest.iter().cloned())
.collect::<Vec<_>>()
} else {
rest.to_vec()
}
}
None => bail!("Expected at least one argument in outer function call"),
};
Ok(Edit::range_replacement(
tree.codegen_stylist(stylist),
expr.range(),
))
}
/// (C416) Convert `[i for i in x]` to `list(x)`.
pub(crate) fn fix_unnecessary_comprehension(
expr: &Expr,
locator: &Locator,
stylist: &Stylist,
) -> Result<Edit> {
let module_text = locator.slice(expr);
let mut tree = match_expression(module_text)?;
match &tree {
Expression::ListComp(inner) => {
tree = Expression::Call(Box::new(Call {
func: Box::new(Expression::Name(Box::new(Name {
value: "list",
lpar: vec![],
rpar: vec![],
}))),
args: vec![Arg {
value: inner.for_in.iter.clone(),
keyword: None,
equal: None,
comma: None,
star: "",
whitespace_after_star: ParenthesizableWhitespace::default(),
whitespace_after_arg: ParenthesizableWhitespace::default(),
}],
lpar: vec![],
rpar: vec![],
whitespace_after_func: ParenthesizableWhitespace::default(),
whitespace_before_args: ParenthesizableWhitespace::default(),
}));
}
Expression::SetComp(inner) => {
tree = Expression::Call(Box::new(Call {
func: Box::new(Expression::Name(Box::new(Name {
value: "set",
lpar: vec![],
rpar: vec![],
}))),
args: vec![Arg {
value: inner.for_in.iter.clone(),
keyword: None,
equal: None,
comma: None,
star: "",
whitespace_after_star: ParenthesizableWhitespace::default(),
whitespace_after_arg: ParenthesizableWhitespace::default(),
}],
lpar: vec![],
rpar: vec![],
whitespace_after_func: ParenthesizableWhitespace::default(),
whitespace_before_args: ParenthesizableWhitespace::default(),
}));
}
Expression::DictComp(inner) => {
tree = Expression::Call(Box::new(Call {
func: Box::new(Expression::Name(Box::new(Name {
value: "dict",
lpar: vec![],
rpar: vec![],
}))),
args: vec![Arg {
value: inner.for_in.iter.clone(),
keyword: None,
equal: None,
comma: None,
star: "",
whitespace_after_star: ParenthesizableWhitespace::default(),
whitespace_after_arg: ParenthesizableWhitespace::default(),
}],
lpar: vec![],
rpar: vec![],
whitespace_after_func: ParenthesizableWhitespace::default(),
whitespace_before_args: ParenthesizableWhitespace::default(),
}));
}
_ => {
bail!("Expected Expression::ListComp | Expression:SetComp | Expression:DictComp");
}
}
Ok(Edit::range_replacement(
pad(tree.codegen_stylist(stylist), expr.range(), locator),
expr.range(),
))
}
/// (C417) Convert `map(lambda x: x * 2, bar)` to `(x * 2 for x in bar)`.
pub(crate) fn fix_unnecessary_map(
call_ast_node: &ExprCall,
parent: Option<&Expr>,
object_type: ObjectType,
locator: &Locator,
stylist: &Stylist,
) -> Result<Edit> {
let module_text = locator.slice(call_ast_node);
let mut tree = match_expression(module_text)?;
let call = match_call_mut(&mut tree)?;
let (lambda, iter) = match call.args.as_slice() {
[call] => {
let call = match_call(&call.value)?;
let [lambda, iter] = call.args.as_slice() else {
bail!("Expected two arguments");
};
let lambda = match_lambda(&lambda.value)?;
let iter = &iter.value;
(lambda, iter)
}
[lambda, iter] => {
let lambda = match_lambda(&lambda.value)?;
let iter = &iter.value;
(lambda, iter)
}
_ => bail!("Expected a call or lambda"),
};
// Format the lambda target.
let target = match lambda.params.params.as_slice() {
// Ex) `lambda: x`
[] => AssignTargetExpression::Name(Box::new(Name {
value: "_",
lpar: vec![],
rpar: vec![],
})),
// Ex) `lambda x: y`
[param] => AssignTargetExpression::Name(Box::new(param.name.clone())),
// Ex) `lambda x, y: z`
params => AssignTargetExpression::Tuple(Box::new(Tuple {
elements: params
.iter()
.map(|param| Element::Simple {
value: Expression::Name(Box::new(param.name.clone())),
comma: None,
})
.collect(),
lpar: vec![],
rpar: vec![],
})),
};
// Parenthesize the iterator, if necessary, as in:
// ```python
// map(lambda x: x, y if y else z)
// ```
let iter = iter.clone();
let iter = if iter.lpar().is_empty()
&& iter.rpar().is_empty()
&& matches!(iter, Expression::IfExp(_) | Expression::Lambda(_))
{
iter.with_parens(LeftParen::default(), RightParen::default())
} else {
iter
};
let compfor = Box::new(CompFor {
target,
iter,
ifs: vec![],
inner_for_in: None,
asynchronous: None,
whitespace_before: space(),
whitespace_after_for: space(),
whitespace_before_in: space(),
whitespace_after_in: space(),
});
match object_type {
ObjectType::Generator => {
tree = Expression::GeneratorExp(Box::new(GeneratorExp {
elt: lambda.body.clone(),
for_in: compfor,
lpar: vec![LeftParen::default()],
rpar: vec![RightParen::default()],
}));
}
ObjectType::List => {
tree = Expression::ListComp(Box::new(ListComp {
elt: lambda.body.clone(),
for_in: compfor,
lbracket: LeftSquareBracket::default(),
rbracket: RightSquareBracket::default(),
lpar: vec![],
rpar: vec![],
}));
}
ObjectType::Set => {
tree = Expression::SetComp(Box::new(SetComp {
elt: lambda.body.clone(),
for_in: compfor,
lpar: vec![],
rpar: vec![],
lbrace: LeftCurlyBrace::default(),
rbrace: RightCurlyBrace::default(),
}));
}
ObjectType::Dict => {
let elements = match lambda.body.as_ref() {
Expression::Tuple(tuple) => &tuple.elements,
Expression::List(list) => &list.elements,
_ => {
bail!("Expected tuple or list for dictionary comprehension")
}
};
let [key, value] = elements.as_slice() else {
bail!("Expected container to include two elements");
};
let Element::Simple { value: key, .. } = key else {
bail!("Expected container to use a key as the first element");
};
let Element::Simple { value, .. } = value else {
bail!("Expected container to use a value as the second element");
};
tree = Expression::DictComp(Box::new(DictComp {
for_in: compfor,
lpar: vec![],
rpar: vec![],
key: Box::new(key.clone()),
value: Box::new(value.clone()),
lbrace: LeftCurlyBrace::default(),
rbrace: RightCurlyBrace::default(),
whitespace_before_colon: ParenthesizableWhitespace::default(),
whitespace_after_colon: ParenthesizableWhitespace::SimpleWhitespace(
SimpleWhitespace(" "),
),
}));
}
}
let mut content = tree.codegen_stylist(stylist);
// If the expression is embedded in an interpolated string, surround it with spaces to avoid
// syntax errors.
if matches!(object_type, ObjectType::Set | ObjectType::Dict) {
if parent.is_some_and(|expr| expr.is_f_string_expr() || expr.is_t_string_expr()) {
content = format!(" {content} ");
}
}
Ok(Edit::range_replacement(content, call_ast_node.range()))
}
/// (C419) Convert `[i for i in a]` into `i for i in a`
pub(crate) fn fix_unnecessary_comprehension_in_call(
expr: &Expr,
locator: &Locator,
stylist: &Stylist,
) -> Result<Fix> {
// Expr(ListComp) -> Expr(GeneratorExp)
let module_text = locator.slice(expr);
let mut tree = match_expression(module_text)?;
let call = match_call_mut(&mut tree)?;
let (whitespace_after, whitespace_before, elt, for_in, lpar, rpar) = match &call.args[0].value {
Expression::ListComp(list_comp) => (
&list_comp.lbracket.whitespace_after,
&list_comp.rbracket.whitespace_before,
&list_comp.elt,
&list_comp.for_in,
&list_comp.lpar,
&list_comp.rpar,
),
Expression::SetComp(set_comp) => (
&set_comp.lbrace.whitespace_after,
&set_comp.rbrace.whitespace_before,
&set_comp.elt,
&set_comp.for_in,
&set_comp.lpar,
&set_comp.rpar,
),
_ => {
bail!("Expected Expression::ListComp | Expression::SetComp");
}
};
let mut new_empty_lines = vec![];
if let ParenthesizableWhitespace::ParenthesizedWhitespace(ParenthesizedWhitespace {
first_line,
empty_lines,
..
}) = &whitespace_after
{
// If there's a comment on the line after the opening bracket, we need
// to preserve it. The way we do this is by adding a new empty line
// with the same comment.
//
// Example:
// ```python
// any(
// [ # comment
// ...
// ]
// )
//
// # The above code will be converted to:
// any(
// # comment
// ...
// )
// ```
if let TrailingWhitespace {
comment: Some(comment),
..
} = first_line
{
// The indentation should be same as that of the opening bracket,
// but we don't have that information here. This will be addressed
// before adding these new nodes.
new_empty_lines.push(EmptyLine {
comment: Some(comment.clone()),
..EmptyLine::default()
});
}
if !empty_lines.is_empty() {
new_empty_lines.extend(empty_lines.clone());
}
}
if !new_empty_lines.is_empty() {
call.whitespace_before_args = match &call.whitespace_before_args {
ParenthesizableWhitespace::ParenthesizedWhitespace(ParenthesizedWhitespace {
first_line,
indent,
last_line,
..
}) => {
// Add the indentation of the opening bracket to all the new
// empty lines.
for empty_line in &mut new_empty_lines {
empty_line.whitespace = last_line.clone();
}
ParenthesizableWhitespace::ParenthesizedWhitespace(ParenthesizedWhitespace {
first_line: first_line.clone(),
empty_lines: new_empty_lines,
indent: *indent,
last_line: last_line.clone(),
})
}
// This is a rare case, but it can happen if the opening bracket
// is on the same line as the function call.
//
// Example:
// ```python
// any([
// ...
// ]
// )
// ```
ParenthesizableWhitespace::SimpleWhitespace(whitespace) => {
for empty_line in &mut new_empty_lines {
empty_line.whitespace = whitespace.clone();
}
ParenthesizableWhitespace::ParenthesizedWhitespace(ParenthesizedWhitespace {
empty_lines: new_empty_lines,
..ParenthesizedWhitespace::default()
})
}
}
}
let rbracket_comment =
if let ParenthesizableWhitespace::ParenthesizedWhitespace(ParenthesizedWhitespace {
first_line:
TrailingWhitespace {
whitespace,
comment: Some(comment),
..
},
..
}) = &whitespace_before
{
Some(format!("{}{}", whitespace.0, comment.0))
} else {
None
};
call.args[0].value = Expression::GeneratorExp(Box::new(GeneratorExp {
elt: elt.clone(),
for_in: for_in.clone(),
lpar: lpar.clone(),
rpar: rpar.clone(),
}));
let whitespace_after_arg = match &call.args[0].comma {
Some(comma) => {
let whitespace_after_comma = comma.whitespace_after.clone();
call.args[0].comma = Some(Comma {
whitespace_after: ParenthesizableWhitespace::default(),
..comma.clone()
});
whitespace_after_comma
}
_ => call.args[0].whitespace_after_arg.clone(),
};
let new_comment;
call.args[0].whitespace_after_arg = match rbracket_comment {
Some(existing_comment) => {
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | true |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/mod.rs | crates/ruff_linter/src/rules/flake8_comprehensions/mod.rs | //! Rules from [flake8-comprehensions](https://pypi.org/project/flake8-comprehensions/).
mod fixes;
mod helpers;
pub(crate) mod rules;
pub mod settings;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::assert_diagnostics;
use crate::registry::Rule;
use crate::settings::LinterSettings;
use crate::settings::types::PreviewMode;
use crate::test::test_path;
#[test_case(Rule::UnnecessaryCallAroundSorted, Path::new("C413.py"))]
#[test_case(Rule::UnnecessaryCollectionCall, Path::new("C408.py"))]
#[test_case(Rule::UnnecessaryComprehension, Path::new("C416.py"))]
#[test_case(Rule::UnnecessaryComprehensionInCall, Path::new("C419.py"))]
#[test_case(Rule::UnnecessaryComprehensionInCall, Path::new("C419_2.py"))]
#[test_case(Rule::UnnecessaryDictComprehensionForIterable, Path::new("C420.py"))]
#[test_case(Rule::UnnecessaryDictComprehensionForIterable, Path::new("C420_1.py"))]
#[test_case(Rule::UnnecessaryDictComprehensionForIterable, Path::new("C420_2.py"))]
#[test_case(Rule::UnnecessaryDictComprehensionForIterable, Path::new("C420_3.py"))]
#[test_case(Rule::UnnecessaryDoubleCastOrProcess, Path::new("C414.py"))]
#[test_case(Rule::UnnecessaryGeneratorDict, Path::new("C402.py"))]
#[test_case(Rule::UnnecessaryGeneratorList, Path::new("C400.py"))]
#[test_case(Rule::UnnecessaryGeneratorSet, Path::new("C401.py"))]
#[test_case(Rule::UnnecessaryListCall, Path::new("C411.py"))]
#[test_case(Rule::UnnecessaryListComprehensionDict, Path::new("C404.py"))]
#[test_case(Rule::UnnecessaryListComprehensionSet, Path::new("C403.py"))]
#[test_case(Rule::UnnecessaryLiteralDict, Path::new("C406.py"))]
#[test_case(Rule::UnnecessaryLiteralSet, Path::new("C405.py"))]
#[test_case(Rule::UnnecessaryLiteralWithinDictCall, Path::new("C418.py"))]
#[test_case(Rule::UnnecessaryLiteralWithinListCall, Path::new("C410.py"))]
#[test_case(Rule::UnnecessaryLiteralWithinTupleCall, Path::new("C409.py"))]
#[test_case(Rule::UnnecessaryMap, Path::new("C417.py"))]
#[test_case(Rule::UnnecessaryMap, Path::new("C417_1.py"))]
#[test_case(Rule::UnnecessarySubscriptReversal, Path::new("C415.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("flake8_comprehensions").join(path).as_path(),
&LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::UnnecessaryLiteralWithinTupleCall, Path::new("C409.py"))]
#[test_case(Rule::UnnecessaryComprehensionInCall, Path::new("C419_1.py"))]
fn preview_rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"preview__{}_{}",
rule_code.noqa_code(),
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("flake8_comprehensions").join(path).as_path(),
&LinterSettings {
preview: PreviewMode::Enabled,
..LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::UnnecessaryCollectionCall, Path::new("C408.py"))]
fn allow_dict_calls_with_keyword_arguments(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"{}_{}_allow_dict_calls_with_keyword_arguments",
rule_code.noqa_code(),
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("flake8_comprehensions").join(path).as_path(),
&LinterSettings {
flake8_comprehensions: super::settings::Settings {
allow_dict_calls_with_keyword_arguments: true,
},
..LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::any_over_expr;
use ruff_python_ast::{self as ast, Expr};
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::preview::is_check_comprehensions_in_tuple_call_enabled;
use crate::rules::flake8_comprehensions::fixes;
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for `tuple` calls that take unnecessary list or tuple literals as
/// arguments. In [preview], this also includes unnecessary list comprehensions
/// within tuple calls.
///
/// ## Why is this bad?
/// It's unnecessary to use a list or tuple literal within a `tuple()` call,
/// since there is a literal syntax for these types.
///
/// If a list literal was passed, then it should be rewritten as a `tuple`
/// literal. Otherwise, if a tuple literal was passed, then the outer call
/// to `tuple()` should be removed.
///
/// In [preview], this rule also checks for list comprehensions within `tuple()`
/// calls. If a list comprehension is found, it should be rewritten as a
/// generator expression.
///
/// ## Example
/// ```python
/// tuple([1, 2])
/// tuple((1, 2))
/// tuple([x for x in range(10)])
/// ```
///
/// Use instead:
/// ```python
/// (1, 2)
/// (1, 2)
/// tuple(x for x in range(10))
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.66")]
pub(crate) struct UnnecessaryLiteralWithinTupleCall {
literal_kind: TupleLiteralKind,
}
impl AlwaysFixableViolation for UnnecessaryLiteralWithinTupleCall {
#[derive_message_formats]
fn message(&self) -> String {
match self.literal_kind {
TupleLiteralKind::List => {
"Unnecessary list literal passed to `tuple()` (rewrite as a tuple literal)"
.to_string()
}
TupleLiteralKind::Tuple => {
"Unnecessary tuple literal passed to `tuple()` (remove the outer call to `tuple()`)"
.to_string()
}
TupleLiteralKind::ListComp => {
"Unnecessary list comprehension passed to `tuple()` (rewrite as a generator)"
.to_string()
}
}
}
fn fix_title(&self) -> String {
let title = match self.literal_kind {
TupleLiteralKind::List => "Rewrite as a tuple literal",
TupleLiteralKind::Tuple => "Remove the outer call to `tuple()`",
TupleLiteralKind::ListComp => "Rewrite as a generator",
};
title.to_string()
}
}
/// C409
pub(crate) fn unnecessary_literal_within_tuple_call(
checker: &Checker,
expr: &Expr,
call: &ast::ExprCall,
) {
if !call.arguments.keywords.is_empty() {
return;
}
let Some(argument) = helpers::exactly_one_argument_with_matching_function(
"tuple",
&call.func,
&call.arguments.args,
&call.arguments.keywords,
) else {
return;
};
let argument_kind = match argument {
Expr::Tuple(_) => TupleLiteralKind::Tuple,
Expr::List(_) => TupleLiteralKind::List,
Expr::ListComp(_) if is_check_comprehensions_in_tuple_call_enabled(checker.settings()) => {
TupleLiteralKind::ListComp
}
_ => return,
};
if !checker.semantic().has_builtin_binding("tuple") {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryLiteralWithinTupleCall {
literal_kind: argument_kind,
},
call.range(),
);
match argument {
Expr::List(ast::ExprList { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. }) => {
// Convert `tuple([1, 2])` to `(1, 2)`
diagnostic.set_fix({
let needs_trailing_comma = if let [item] = elts.as_slice() {
SimpleTokenizer::new(
checker.locator().contents(),
TextRange::new(item.end(), argument.end()),
)
.all(|token| token.kind != SimpleTokenKind::Comma)
} else {
false
};
// Replace `[` with `(`.
let elt_start = Edit::replacement(
"(".into(),
call.start(),
argument.start() + TextSize::from(1),
);
// Replace `]` with `)` or `,)`.
let elt_end = Edit::replacement(
if needs_trailing_comma {
",)".into()
} else {
")".into()
},
argument.end() - TextSize::from(1),
call.end(),
);
Fix::unsafe_edits(elt_start, [elt_end])
});
}
Expr::ListComp(ast::ExprListComp { elt, .. }) => {
if any_over_expr(elt, &Expr::is_await_expr) {
return;
}
// Convert `tuple([x for x in range(10)])` to `tuple(x for x in range(10))`
diagnostic.try_set_fix(|| {
fixes::fix_unnecessary_comprehension_in_call(
expr,
checker.locator(),
checker.stylist(),
)
});
}
_ => (),
}
}
#[derive(Debug, PartialEq, Eq)]
enum TupleLiteralKind {
List,
Tuple,
ListComp,
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs | use ruff_python_ast::{Arguments, Expr, ExprCall};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::rules::flake8_comprehensions::fixes;
use crate::{AlwaysFixableViolation, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for unnecessary `list()` calls around list comprehensions.
///
/// ## Why is this bad?
/// It is redundant to use a `list()` call around a list comprehension.
///
/// ## Example
/// ```python
/// list([f(x) for x in foo])
/// ```
///
/// Use instead
/// ```python
/// [f(x) for x in foo]
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.73")]
pub(crate) struct UnnecessaryListCall;
impl AlwaysFixableViolation for UnnecessaryListCall {
#[derive_message_formats]
fn message(&self) -> String {
"Unnecessary `list()` call (remove the outer call to `list()`)".to_string()
}
fn fix_title(&self) -> String {
"Remove outer `list()` call".to_string()
}
}
/// C411
pub(crate) fn unnecessary_list_call(checker: &Checker, expr: &Expr, call: &ExprCall) {
let ExprCall {
func,
arguments,
range: _,
node_index: _,
} = call;
if !arguments.keywords.is_empty() {
return;
}
if arguments.args.len() > 1 {
return;
}
let Arguments {
range: _,
node_index: _,
args,
keywords: _,
} = arguments;
let Some(argument) = helpers::first_argument_with_matching_function("list", func, args) else {
return;
};
if !argument.is_list_comp_expr() {
return;
}
if !checker.semantic().has_builtin_binding("list") {
return;
}
let mut diagnostic = checker.report_diagnostic(UnnecessaryListCall, expr.range());
diagnostic.try_set_fix(|| {
fixes::fix_unnecessary_list_call(expr, checker.locator(), checker.stylist())
.map(Fix::unsafe_edit)
});
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::token::TokenKind;
use ruff_python_ast::token::parenthesized_range;
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::rules::flake8_comprehensions::fixes::{pad_end, pad_start};
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for unnecessary list comprehensions.
///
/// ## Why is this bad?
/// It's unnecessary to use a list comprehension inside a call to `set()`,
/// since there is an equivalent comprehension for this type.
///
/// ## Example
/// ```python
/// set([f(x) for x in foo])
/// ```
///
/// Use instead:
/// ```python
/// {f(x) for x in foo}
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.58")]
pub(crate) struct UnnecessaryListComprehensionSet;
impl AlwaysFixableViolation for UnnecessaryListComprehensionSet {
#[derive_message_formats]
fn message(&self) -> String {
"Unnecessary list comprehension (rewrite as a set comprehension)".to_string()
}
fn fix_title(&self) -> String {
"Rewrite as a set comprehension".to_string()
}
}
/// C403 (`set([...])`)
pub(crate) fn unnecessary_list_comprehension_set(checker: &Checker, call: &ast::ExprCall) {
let Some(argument) = helpers::exactly_one_argument_with_matching_function(
"set",
&call.func,
&call.arguments.args,
&call.arguments.keywords,
) else {
return;
};
if !checker.semantic().has_builtin_binding("set") {
return;
}
if !argument.is_list_comp_expr() {
return;
}
let mut diagnostic = checker.report_diagnostic(UnnecessaryListComprehensionSet, call.range());
let one = TextSize::from(1);
// Replace `set(` with `{`.
let call_start = Edit::replacement(
pad_start("{", call.range(), checker.locator(), checker.semantic()),
call.start(),
call.arguments.start() + one,
);
// Replace `)` with `}`.
// Place `}` at argument's end or at trailing comma if present
let after_arg_tokens = checker
.tokens()
.in_range(TextRange::new(argument.end(), call.end()));
let right_brace_loc = after_arg_tokens
.iter()
.find(|token| token.kind() == TokenKind::Comma)
.map_or(call.arguments.end() - one, |comma| comma.end() - one);
let call_end = Edit::replacement(
pad_end("}", call.range(), checker.locator(), checker.semantic()),
right_brace_loc,
call.end(),
);
// If the list comprehension is parenthesized, remove the parentheses in addition to
// removing the brackets.
let replacement_range =
parenthesized_range(argument.into(), (&call.arguments).into(), checker.tokens())
.unwrap_or_else(|| argument.range());
let span = argument.range().add_start(one).sub_end(one);
let replacement =
Edit::range_replacement(checker.source()[span].to_string(), replacement_range);
let fix = Fix::unsafe_edits(call_start, [call_end, replacement]);
diagnostic.set_fix(fix);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, Keyword};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Fix};
use crate::rules::flake8_comprehensions::fixes;
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for unnecessary generators that can be rewritten as dict
/// comprehensions.
///
/// ## Why is this bad?
/// It is unnecessary to use `dict()` around a generator expression, since
/// there are equivalent comprehensions for these types. Using a
/// comprehension is clearer and more idiomatic.
///
/// ## Example
/// ```python
/// dict((x, f(x)) for x in foo)
/// ```
///
/// Use instead:
/// ```python
/// {x: f(x) for x in foo}
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.61")]
pub(crate) struct UnnecessaryGeneratorDict;
impl AlwaysFixableViolation for UnnecessaryGeneratorDict {
#[derive_message_formats]
fn message(&self) -> String {
"Unnecessary generator (rewrite as a dict comprehension)".to_string()
}
fn fix_title(&self) -> String {
"Rewrite as a dict comprehension".to_string()
}
}
/// C402 (`dict((x, y) for x, y in iterable)`)
pub(crate) fn unnecessary_generator_dict(
checker: &Checker,
expr: &Expr,
func: &Expr,
args: &[Expr],
keywords: &[Keyword],
) {
let Some(argument) =
helpers::exactly_one_argument_with_matching_function("dict", func, args, keywords)
else {
return;
};
let Expr::Generator(ast::ExprGenerator { elt, .. }) = argument else {
return;
};
let Expr::Tuple(tuple) = &**elt else {
return;
};
if tuple.len() != 2 {
return;
}
if tuple.iter().any(Expr::is_starred_expr) {
return;
}
let mut diagnostic = checker.report_diagnostic(UnnecessaryGeneratorDict, expr.range());
diagnostic
.try_set_fix(|| fixes::fix_unnecessary_generator_dict(expr, checker).map(Fix::unsafe_edit));
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableKeyword;
use ruff_python_ast::{self as ast, Arguments, Expr, Keyword};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Fix};
use crate::rules::flake8_comprehensions::fixes;
/// ## What it does
/// Checks for unnecessary `list()`, `reversed()`, `set()`, `sorted()`, and
/// `tuple()` call within `list()`, `set()`, `sorted()`, and `tuple()` calls.
///
/// ## Why is this bad?
/// It's unnecessary to double-cast or double-process iterables by wrapping
/// the listed functions within an additional `list()`, `set()`, `sorted()`, or
/// `tuple()` call. Doing so is redundant and can be confusing for readers.
///
/// ## Example
/// ```python
/// list(tuple(iterable))
/// ```
///
/// Use instead:
/// ```python
/// list(iterable)
/// ```
///
/// This rule applies to a variety of functions, including `list()`, `reversed()`,
/// `set()`, `sorted()`, and `tuple()`. For example:
///
/// - Instead of `list(list(iterable))`, use `list(iterable)`.
/// - Instead of `list(tuple(iterable))`, use `list(iterable)`.
/// - Instead of `tuple(list(iterable))`, use `tuple(iterable)`.
/// - Instead of `tuple(tuple(iterable))`, use `tuple(iterable)`.
/// - Instead of `set(set(iterable))`, use `set(iterable)`.
/// - Instead of `set(list(iterable))`, use `set(iterable)`.
/// - Instead of `set(tuple(iterable))`, use `set(iterable)`.
/// - Instead of `set(sorted(iterable))`, use `set(iterable)`.
/// - Instead of `set(reversed(iterable))`, use `set(iterable)`.
/// - Instead of `sorted(list(iterable))`, use `sorted(iterable)`.
/// - Instead of `sorted(tuple(iterable))`, use `sorted(iterable)`.
/// - Instead of `sorted(sorted(iterable))`, use `sorted(iterable)`.
/// - Instead of `sorted(reversed(iterable))`, use `sorted(iterable)`.
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.70")]
pub(crate) struct UnnecessaryDoubleCastOrProcess {
inner: String,
outer: String,
}
impl AlwaysFixableViolation for UnnecessaryDoubleCastOrProcess {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryDoubleCastOrProcess { inner, outer } = self;
format!("Unnecessary `{inner}()` call within `{outer}()`")
}
fn fix_title(&self) -> String {
let UnnecessaryDoubleCastOrProcess { inner, .. } = self;
format!("Remove the inner `{inner}()` call")
}
}
/// C414
pub(crate) fn unnecessary_double_cast_or_process(
checker: &Checker,
expr: &Expr,
outer_func: &Expr,
args: &[Expr],
outer_kw: &[Keyword],
) {
let Some(arg) = args.first() else {
return;
};
let Expr::Call(ast::ExprCall {
func: inner_func,
arguments: Arguments {
keywords: inner_kw, ..
},
..
}) = arg
else {
return;
};
let semantic = checker.semantic();
let Some(outer_func_name) = semantic.resolve_builtin_symbol(outer_func) else {
return;
};
if !matches!(
outer_func_name,
"list" | "tuple" | "set" | "reversed" | "sorted"
) {
return;
}
let Some(inner_func_name) = semantic.resolve_builtin_symbol(inner_func) else {
return;
};
// Avoid collapsing nested `sorted` calls with non-identical keyword arguments
// (i.e., `key`, `reverse`).
if inner_func_name == "sorted" && outer_func_name == "sorted" {
if inner_kw.len() != outer_kw.len() {
return;
}
if !inner_kw.iter().all(|inner| {
outer_kw
.iter()
.any(|outer| ComparableKeyword::from(inner) == ComparableKeyword::from(outer))
}) {
return;
}
}
// Ex) `set(tuple(...))`
// Ex) `list(tuple(...))`
// Ex) `set(set(...))`
if matches!(
(outer_func_name, inner_func_name),
("set" | "sorted", "list" | "tuple" | "reversed" | "sorted")
| ("set", "set")
| ("list" | "tuple", "list" | "tuple")
) {
let mut diagnostic = checker.report_diagnostic(
UnnecessaryDoubleCastOrProcess {
inner: inner_func_name.to_string(),
outer: outer_func_name.to_string(),
},
expr.range(),
);
diagnostic.try_set_fix(|| {
fixes::fix_unnecessary_double_cast_or_process(
expr,
checker.locator(),
checker.stylist(),
)
.map(Fix::unsafe_edit)
});
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_map.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_map.rs | use std::fmt;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::any_over_expr;
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{self as ast, Expr, ExprContext, Parameters, Stmt};
use ruff_python_ast::{ExprLambda, visitor};
use ruff_python_semantic::SemanticModel;
use crate::Fix;
use crate::checkers::ast::Checker;
use crate::rules::flake8_comprehensions::fixes;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for unnecessary `map()` calls with lambda functions.
///
/// ## Why is this bad?
/// Using `map(func, iterable)` when `func` is a lambda is slower than
/// using a generator expression or a comprehension, as the latter approach
/// avoids the function call overhead, in addition to being more readable.
///
/// This rule also applies to `map()` calls within `list()`, `set()`, and
/// `dict()` calls. For example:
///
/// - Instead of `list(map(lambda num: num * 2, nums))`, use
/// `[num * 2 for num in nums]`.
/// - Instead of `set(map(lambda num: num % 2 == 0, nums))`, use
/// `{num % 2 == 0 for num in nums}`.
/// - Instead of `dict(map(lambda v: (v, v ** 2), values))`, use
/// `{v: v ** 2 for v in values}`.
///
/// ## Example
/// ```python
/// map(lambda x: x + 1, iterable)
/// ```
///
/// Use instead:
/// ```python
/// (x + 1 for x in iterable)
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.74")]
pub(crate) struct UnnecessaryMap {
object_type: ObjectType,
}
impl Violation for UnnecessaryMap {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryMap { object_type } = self;
format!("Unnecessary `map()` usage (rewrite using a {object_type})")
}
fn fix_title(&self) -> Option<String> {
let UnnecessaryMap { object_type } = self;
Some(format!("Replace `map()` with a {object_type}"))
}
}
/// C417
pub(crate) fn unnecessary_map(checker: &Checker, call: &ast::ExprCall) {
let semantic = checker.semantic();
let (func, arguments) = (&call.func, &call.arguments);
if !arguments.keywords.is_empty() {
return;
}
let Some(object_type) = ObjectType::from(func, semantic) else {
return;
};
let parent = semantic.current_expression_parent();
let (lambda, iterables) = match object_type {
ObjectType::Generator => {
let parent_call_func = match parent {
Some(Expr::Call(call)) => Some(&call.func),
_ => None,
};
// Exclude the parent if already matched by other arms.
if parent_call_func.is_some_and(|func| is_list_set_or_dict(func, semantic)) {
return;
}
let Some(result) = map_lambda_and_iterables(call, semantic) else {
return;
};
result
}
ObjectType::List | ObjectType::Set | ObjectType::Dict => {
let [Expr::Call(inner_call)] = arguments.args.as_ref() else {
return;
};
let Some((lambda, iterables)) = map_lambda_and_iterables(inner_call, semantic) else {
return;
};
if object_type == ObjectType::Dict {
let (Expr::Tuple(ast::ExprTuple { elts, .. })
| Expr::List(ast::ExprList { elts, .. })) = &*lambda.body
else {
return;
};
if elts.len() != 2 {
return;
}
}
(lambda, iterables)
}
};
// If the lambda body contains a `yield` or `yield from`, rewriting `map(lambda ...)` to a
// generator expression or any comprehension is invalid Python syntax
// (e.g., `yield` is not allowed inside generator or comprehension expressions). In such cases, skip.
if lambda_contains_yield(&lambda.body) {
return;
}
for iterable in iterables {
// For example, (x+1 for x in (c:=a)) is invalid syntax
// so we can't suggest it.
if any_over_expr(iterable, &|expr| expr.is_named_expr()) {
return;
}
if iterable.is_starred_expr() {
return;
}
}
if !lambda_has_expected_arity(lambda) {
return;
}
let mut diagnostic = checker.report_diagnostic(UnnecessaryMap { object_type }, call.range);
diagnostic.try_set_fix(|| {
fixes::fix_unnecessary_map(
call,
parent,
object_type,
checker.locator(),
checker.stylist(),
)
.map(Fix::unsafe_edit)
});
}
fn is_list_set_or_dict(func: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["" | "builtins", "list" | "set" | "dict"]
)
})
}
fn map_lambda_and_iterables<'a>(
call: &'a ast::ExprCall,
semantic: &'a SemanticModel,
) -> Option<(&'a ExprLambda, &'a [Expr])> {
if !semantic.match_builtin_expr(&call.func, "map") {
return None;
}
let arguments = &call.arguments;
if !arguments.keywords.is_empty() {
return None;
}
let Some((Expr::Lambda(lambda), iterables)) = arguments.args.split_first() else {
return None;
};
Some((lambda, iterables))
}
/// Returns true if the expression tree contains a `yield` or `yield from` expression.
fn lambda_contains_yield(expr: &Expr) -> bool {
any_over_expr(expr, &|expr| {
matches!(expr, Expr::Yield(_) | Expr::YieldFrom(_))
})
}
/// A lambda as the first argument to `map()` has the "expected" arity when:
///
/// * It has exactly one parameter
/// * That parameter is not variadic
/// * That parameter does not have a default value
fn lambda_has_expected_arity(lambda: &ExprLambda) -> bool {
let Some(parameters) = lambda.parameters.as_deref() else {
return false;
};
let [parameter] = &*parameters.args else {
return false;
};
if parameter.default.is_some() {
return false;
}
if parameters.vararg.is_some() || parameters.kwarg.is_some() {
return false;
}
if late_binding(parameters, &lambda.body) {
return false;
}
true
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum ObjectType {
Generator,
List,
Set,
Dict,
}
impl ObjectType {
fn from(func: &Expr, semantic: &SemanticModel) -> Option<Self> {
match semantic.resolve_builtin_symbol(func) {
Some("map") => Some(Self::Generator),
Some("list") => Some(Self::List),
Some("set") => Some(Self::Set),
Some("dict") => Some(Self::Dict),
_ => None,
}
}
}
impl fmt::Display for ObjectType {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
ObjectType::Generator => fmt.write_str("generator expression"),
ObjectType::List => fmt.write_str("list comprehension"),
ObjectType::Set => fmt.write_str("set comprehension"),
ObjectType::Dict => fmt.write_str("dict comprehension"),
}
}
}
/// Returns `true` if the lambda defined by the given parameters and body contains any names that
/// are late-bound within nested lambdas.
///
/// For example, given:
///
/// ```python
/// map(lambda x: lambda: x, range(4)) # (0, 1, 2, 3)
/// ```
///
/// The `x` in the inner lambda is "late-bound". Specifically, rewriting the above as:
///
/// ```python
/// (lambda: x for x in range(4)) # (3, 3, 3, 3)
/// ```
///
/// Would yield an incorrect result, as the `x` in the inner lambda would be bound to the last
/// value of `x` in the comprehension.
fn late_binding(parameters: &Parameters, body: &Expr) -> bool {
let mut visitor = LateBindingVisitor::new(parameters);
visitor.visit_expr(body);
visitor.late_bound
}
#[derive(Debug)]
struct LateBindingVisitor<'a> {
/// The arguments to the current lambda.
parameters: &'a Parameters,
/// The arguments to any lambdas within the current lambda body.
lambdas: Vec<Option<&'a Parameters>>,
/// Whether any names within the current lambda body are late-bound within nested lambdas.
late_bound: bool,
}
impl<'a> LateBindingVisitor<'a> {
fn new(parameters: &'a Parameters) -> Self {
Self {
parameters,
lambdas: Vec::new(),
late_bound: false,
}
}
}
impl<'a> Visitor<'a> for LateBindingVisitor<'a> {
fn visit_stmt(&mut self, _stmt: &'a Stmt) {}
fn visit_expr(&mut self, expr: &'a Expr) {
match expr {
Expr::Lambda(ast::ExprLambda { parameters, .. }) => {
self.lambdas.push(parameters.as_deref());
visitor::walk_expr(self, expr);
self.lambdas.pop();
}
Expr::Name(ast::ExprName {
id,
ctx: ExprContext::Load,
..
}) => {
// If we're within a nested lambda...
if !self.lambdas.is_empty() {
// If the name is defined in the current lambda...
if self.parameters.includes(id) {
// And isn't overridden by any nested lambdas...
if !self.lambdas.iter().any(|parameters| {
parameters
.as_ref()
.is_some_and(|parameters| parameters.includes(id))
}) {
// Then it's late-bound.
self.late_bound = true;
}
}
}
}
_ => visitor::walk_expr(self, expr),
}
}
fn visit_body(&mut self, _body: &'a [Stmt]) {}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::ExprGenerator;
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::token::TokenKind;
use ruff_python_ast::token::parenthesized_range;
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::rules::flake8_comprehensions::fixes::{pad_end, pad_start};
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for unnecessary generators that can be rewritten as set
/// comprehensions (or with `set()` directly).
///
/// ## Why is this bad?
/// It is unnecessary to use `set` around a generator expression, since
/// there are equivalent comprehensions for these types. Using a
/// comprehension is clearer and more idiomatic.
///
/// Further, if the comprehension can be removed entirely, as in the case of
/// `set(x for x in foo)`, it's better to use `set(foo)` directly, since it's
/// even more direct.
///
/// ## Example
/// ```python
/// set(f(x) for x in foo)
/// set(x for x in foo)
/// set((x for x in foo))
/// ```
///
/// Use instead:
/// ```python
/// {f(x) for x in foo}
/// set(foo)
/// set(foo)
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.61")]
pub(crate) struct UnnecessaryGeneratorSet {
short_circuit: bool,
}
impl AlwaysFixableViolation for UnnecessaryGeneratorSet {
#[derive_message_formats]
fn message(&self) -> String {
if self.short_circuit {
"Unnecessary generator (rewrite using `set()`)".to_string()
} else {
"Unnecessary generator (rewrite as a set comprehension)".to_string()
}
}
fn fix_title(&self) -> String {
if self.short_circuit {
"Rewrite using `set()`".to_string()
} else {
"Rewrite as a set comprehension".to_string()
}
}
}
/// C401 (`set(generator)`)
pub(crate) fn unnecessary_generator_set(checker: &Checker, call: &ast::ExprCall) {
let Some(argument) = helpers::exactly_one_argument_with_matching_function(
"set",
&call.func,
&call.arguments.args,
&call.arguments.keywords,
) else {
return;
};
let ast::Expr::Generator(ExprGenerator {
elt,
generators,
parenthesized,
..
}) = argument
else {
return;
};
if !checker.semantic().has_builtin_binding("set") {
return;
}
// Short-circuit: given `set(x for x in y)`, generate `set(y)` (in lieu of `{x for x in y}`).
if let [generator] = generators.as_slice() {
if generator.ifs.is_empty() && !generator.is_async {
if ComparableExpr::from(elt) == ComparableExpr::from(&generator.target) {
let mut diagnostic = checker.report_diagnostic(
UnnecessaryGeneratorSet {
short_circuit: true,
},
call.range(),
);
let iterator = format!("set({})", checker.locator().slice(generator.iter.range()));
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
iterator,
call.range(),
)));
return;
}
}
}
// Convert `set(f(x) for x in y)` to `{f(x) for x in y}`.
let mut diagnostic = checker.report_diagnostic(
UnnecessaryGeneratorSet {
short_circuit: false,
},
call.range(),
);
let fix = {
// Replace `set(` with `}`.
let call_start = Edit::replacement(
pad_start("{", call.range(), checker.locator(), checker.semantic()),
call.start(),
call.arguments.start() + TextSize::from(1),
);
// Replace `)` with `}`.
// Place `}` at argument's end or at trailing comma if present
let after_arg_tokens = checker
.tokens()
.in_range(TextRange::new(argument.end(), call.end()));
let right_brace_loc = after_arg_tokens
.iter()
.find(|token| token.kind() == TokenKind::Comma)
.map_or(call.arguments.end(), Ranged::end)
- TextSize::from(1);
let call_end = Edit::replacement(
pad_end("}", call.range(), checker.locator(), checker.semantic()),
right_brace_loc,
call.end(),
);
// Remove the inner parentheses, if the expression is a generator. The easiest way to do
// this reliably is to use the printer.
if *parenthesized {
// The generator's range will include the innermost parentheses, but it could be
// surrounded by additional parentheses.
let range =
parenthesized_range(argument.into(), (&call.arguments).into(), checker.tokens())
.unwrap_or(argument.range());
// The generator always parenthesizes the expression; trim the parentheses.
let generator = checker.generator().expr(argument);
let generator = generator[1..generator.len() - 1].to_string();
let replacement = Edit::range_replacement(generator, range);
Fix::unsafe_edits(call_start, [call_end, replacement])
} else {
Fix::unsafe_edits(call_start, [call_end])
}
};
diagnostic.set_fix(fix);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/mod.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/mod.rs | pub(crate) use unnecessary_call_around_sorted::*;
pub(crate) use unnecessary_collection_call::*;
pub(crate) use unnecessary_comprehension::*;
pub(crate) use unnecessary_comprehension_in_call::*;
pub(crate) use unnecessary_dict_comprehension_for_iterable::*;
pub(crate) use unnecessary_double_cast_or_process::*;
pub(crate) use unnecessary_generator_dict::*;
pub(crate) use unnecessary_generator_list::*;
pub(crate) use unnecessary_generator_set::*;
pub(crate) use unnecessary_list_call::*;
pub(crate) use unnecessary_list_comprehension_dict::*;
pub(crate) use unnecessary_list_comprehension_set::*;
pub(crate) use unnecessary_literal_dict::*;
pub(crate) use unnecessary_literal_set::*;
pub(crate) use unnecessary_literal_within_dict_call::*;
pub(crate) use unnecessary_literal_within_list_call::*;
pub(crate) use unnecessary_literal_within_tuple_call::*;
pub(crate) use unnecessary_map::*;
pub(crate) use unnecessary_subscript_reversal::*;
mod unnecessary_call_around_sorted;
mod unnecessary_collection_call;
mod unnecessary_comprehension;
mod unnecessary_comprehension_in_call;
mod unnecessary_dict_comprehension_for_iterable;
mod unnecessary_double_cast_or_process;
mod unnecessary_generator_dict;
mod unnecessary_generator_list;
mod unnecessary_generator_set;
mod unnecessary_list_call;
mod unnecessary_list_comprehension_dict;
mod unnecessary_list_comprehension_set;
mod unnecessary_literal_dict;
mod unnecessary_literal_set;
mod unnecessary_literal_within_dict_call;
mod unnecessary_literal_within_list_call;
mod unnecessary_literal_within_tuple_call;
mod unnecessary_map;
mod unnecessary_subscript_reversal;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, UnaryOp};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for unnecessary subscript reversal of iterable.
///
/// ## Why is this bad?
/// It's unnecessary to reverse the order of an iterable when passing it
/// into `reversed()`, `set()` or `sorted()` functions as they will change
/// the order of the elements again.
///
/// ## Example
/// ```python
/// sorted(iterable[::-1])
/// set(iterable[::-1])
/// reversed(iterable[::-1])
/// ```
///
/// Use instead:
/// ```python
/// sorted(iterable)
/// set(iterable)
/// iterable
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.64")]
pub(crate) struct UnnecessarySubscriptReversal {
func: String,
}
impl Violation for UnnecessarySubscriptReversal {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessarySubscriptReversal { func } = self;
format!("Unnecessary subscript reversal of iterable within `{func}()`")
}
}
/// C415
pub(crate) fn unnecessary_subscript_reversal(checker: &Checker, call: &ast::ExprCall) {
let Some(first_arg) = call.arguments.args.first() else {
return;
};
let Expr::Subscript(ast::ExprSubscript { slice, .. }) = first_arg else {
return;
};
let Expr::Slice(ast::ExprSlice {
lower,
upper,
step,
range: _,
node_index: _,
}) = slice.as_ref()
else {
return;
};
if lower.is_some() || upper.is_some() {
return;
}
let Some(step) = step.as_ref() else {
return;
};
let Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::USub,
operand,
range: _,
node_index: _,
}) = step.as_ref()
else {
return;
};
let Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(val),
..
}) = operand.as_ref()
else {
return;
};
if *val != 1 {
return;
}
let Some(function_name) = checker.semantic().resolve_builtin_symbol(&call.func) else {
return;
};
if !matches!(function_name, "reversed" | "set" | "sorted") {
return;
}
checker.report_diagnostic(
UnnecessarySubscriptReversal {
func: function_name.to_string(),
},
call.range(),
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, Keyword};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::rules::flake8_comprehensions::fixes;
use crate::{AlwaysFixableViolation, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for unnecessary list comprehensions.
///
/// ## Why is this bad?
/// It's unnecessary to use a list comprehension inside a call to `dict()`,
/// since there is an equivalent comprehension for this type.
///
/// ## Example
/// ```python
/// dict([(x, f(x)) for x in foo])
/// ```
///
/// Use instead:
/// ```python
/// {x: f(x) for x in foo}
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.58")]
pub(crate) struct UnnecessaryListComprehensionDict;
impl AlwaysFixableViolation for UnnecessaryListComprehensionDict {
#[derive_message_formats]
fn message(&self) -> String {
"Unnecessary list comprehension (rewrite as a dict comprehension)".to_string()
}
fn fix_title(&self) -> String {
"Rewrite as a dict comprehension".to_string()
}
}
/// C404 (`dict([...])`)
pub(crate) fn unnecessary_list_comprehension_dict(
checker: &Checker,
expr: &Expr,
func: &Expr,
args: &[Expr],
keywords: &[Keyword],
) {
let Some(argument) =
helpers::exactly_one_argument_with_matching_function("dict", func, args, keywords)
else {
return;
};
let Expr::ListComp(ast::ExprListComp { elt, .. }) = argument else {
return;
};
let Expr::Tuple(tuple) = &**elt else {
return;
};
if tuple.len() != 2 {
return;
}
if !checker.semantic().has_builtin_binding("dict") {
return;
}
let mut diagnostic = checker.report_diagnostic(UnnecessaryListComprehensionDict, expr.range());
diagnostic.try_set_fix(|| {
fixes::fix_unnecessary_list_comprehension_dict(expr, checker).map(Fix::unsafe_edit)
});
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs | use std::fmt;
use ruff_python_ast::{self as ast, Expr};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for `dict()` calls that take unnecessary dict literals or dict
/// comprehensions as arguments.
///
/// ## Why is this bad?
/// It's unnecessary to wrap a dict literal or comprehension within a `dict()`
/// call, since the literal or comprehension syntax already returns a
/// dictionary.
///
/// ## Example
/// ```python
/// dict({})
/// dict({"a": 1})
/// ```
///
/// Use instead:
/// ```python
/// {}
/// {"a": 1}
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.262")]
pub(crate) struct UnnecessaryLiteralWithinDictCall {
kind: DictKind,
}
impl AlwaysFixableViolation for UnnecessaryLiteralWithinDictCall {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryLiteralWithinDictCall { kind } = self;
format!("Unnecessary dict {kind} passed to `dict()` (remove the outer call to `dict()`)")
}
fn fix_title(&self) -> String {
"Remove outer `dict()` call".to_string()
}
}
/// C418
pub(crate) fn unnecessary_literal_within_dict_call(checker: &Checker, call: &ast::ExprCall) {
if !call.arguments.keywords.is_empty() {
return;
}
if call.arguments.args.len() > 1 {
return;
}
let Some(argument) =
helpers::first_argument_with_matching_function("dict", &call.func, &call.arguments.args)
else {
return;
};
let Some(argument_kind) = DictKind::try_from_expr(argument) else {
return;
};
if !checker.semantic().has_builtin_binding("dict") {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryLiteralWithinDictCall {
kind: argument_kind,
},
call.range(),
);
// Convert `dict({"a": 1})` to `{"a": 1}`
diagnostic.set_fix({
// Delete from the start of the call to the start of the argument.
let call_start = Edit::deletion(call.start(), argument.start());
// Delete from the end of the argument to the end of the call.
let call_end = Edit::deletion(argument.end(), call.end());
Fix::unsafe_edits(call_start, [call_end])
});
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum DictKind {
Literal,
Comprehension,
}
impl DictKind {
const fn as_str(self) -> &'static str {
match self {
Self::Literal => "literal",
Self::Comprehension => "comprehension",
}
}
const fn try_from_expr(expr: &Expr) -> Option<Self> {
match expr {
Expr::Dict(_) => Some(Self::Literal),
Expr::DictComp(_) => Some(Self::Comprehension),
_ => None,
}
}
}
impl fmt::Display for DictKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.as_str())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_text_size::{Ranged, TextSize};
use crate::checkers::ast::Checker;
use crate::rules::flake8_comprehensions::fixes;
use crate::rules::flake8_comprehensions::fixes::{pad_end, pad_start};
use crate::rules::flake8_comprehensions::settings::Settings;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for unnecessary `dict()`, `list()` or `tuple()` calls that can be
/// rewritten as empty literals.
///
/// ## Why is this bad?
/// It's unnecessary to call, e.g., `dict()` as opposed to using an empty
/// literal (`{}`). The former is slower because the name `dict` must be
/// looked up in the global scope in case it has been rebound.
///
/// ## Example
/// ```python
/// dict()
/// dict(a=1, b=2)
/// list()
/// tuple()
/// ```
///
/// Use instead:
/// ```python
/// {}
/// {"a": 1, "b": 2}
/// []
/// ()
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
///
/// ## Options
/// - `lint.flake8-comprehensions.allow-dict-calls-with-keyword-arguments`
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.61")]
pub(crate) struct UnnecessaryCollectionCall {
kind: Collection,
}
impl AlwaysFixableViolation for UnnecessaryCollectionCall {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryCollectionCall { kind } = self;
format!("Unnecessary `{kind}()` call (rewrite as a literal)")
}
fn fix_title(&self) -> String {
"Rewrite as a literal".to_string()
}
}
/// C408
pub(crate) fn unnecessary_collection_call(
checker: &Checker,
call: &ast::ExprCall,
settings: &Settings,
) {
if !call.arguments.args.is_empty() {
return;
}
let Some(builtin) = checker.semantic().resolve_builtin_symbol(&call.func) else {
return;
};
let collection = match builtin {
"dict"
if call.arguments.keywords.is_empty()
|| (!settings.allow_dict_calls_with_keyword_arguments
&& call.arguments.keywords.iter().all(|kw| kw.arg.is_some())) =>
{
// `dict()` or `dict(a=1)` (as opposed to `dict(**a)`)
Collection::Dict
}
"list" if call.arguments.keywords.is_empty() => {
// `list()
Collection::List
}
"tuple" if call.arguments.keywords.is_empty() => {
// `tuple()`
Collection::Tuple
}
_ => return,
};
let mut diagnostic =
checker.report_diagnostic(UnnecessaryCollectionCall { kind: collection }, call.range());
// Convert `dict()` to `{}`.
if call.arguments.keywords.is_empty() {
diagnostic.set_fix({
// Replace from the start of the call to the start of the argument.
let call_start = Edit::replacement(
match collection {
Collection::Dict => {
pad_start("{", call.range(), checker.locator(), checker.semantic())
}
Collection::List => "[".to_string(),
Collection::Tuple => "(".to_string(),
},
call.start(),
call.arguments.start() + TextSize::from(1),
);
// Replace from the end of the inner list or tuple to the end of the call with `}`.
let call_end = Edit::replacement(
match collection {
Collection::Dict => {
pad_end("}", call.range(), checker.locator(), checker.semantic())
}
Collection::List => "]".to_string(),
Collection::Tuple => ")".to_string(),
},
call.arguments.end() - TextSize::from(1),
call.end(),
);
Fix::unsafe_edits(call_start, [call_end])
});
} else {
// Convert `dict(a=1, b=2)` to `{"a": 1, "b": 2}`.
diagnostic.try_set_fix(|| {
fixes::fix_unnecessary_collection_call(call, checker).map(Fix::unsafe_edit)
});
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Collection {
Tuple,
List,
Dict,
}
impl Collection {
const fn as_str(self) -> &'static str {
match self {
Self::Dict => "dict",
Self::List => "list",
Self::Tuple => "tuple",
}
}
}
impl std::fmt::Display for Collection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::{Ranged, TextSize};
use crate::checkers::ast::Checker;
use crate::rules::flake8_comprehensions::fixes::{pad_end, pad_start};
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for `set()` calls that take unnecessary list or tuple literals
/// as arguments.
///
/// ## Why is this bad?
/// It's unnecessary to use a list or tuple literal within a call to `set()`.
/// Instead, the expression can be rewritten as a set literal.
///
/// ## Example
/// ```python
/// set([1, 2])
/// set((1, 2))
/// set([])
/// ```
///
/// Use instead:
/// ```python
/// {1, 2}
/// {1, 2}
/// set()
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.61")]
pub(crate) struct UnnecessaryLiteralSet {
kind: UnnecessaryLiteral,
}
impl AlwaysFixableViolation for UnnecessaryLiteralSet {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryLiteralSet { kind } = self;
format!("Unnecessary {kind} literal (rewrite as a set literal)")
}
fn fix_title(&self) -> String {
"Rewrite as a set literal".to_string()
}
}
/// C405 (`set([1, 2])`)
pub(crate) fn unnecessary_literal_set(checker: &Checker, call: &ast::ExprCall) {
let Some(argument) = helpers::exactly_one_argument_with_matching_function(
"set",
&call.func,
&call.arguments.args,
&call.arguments.keywords,
) else {
return;
};
let Some(kind) = UnnecessaryLiteral::try_from_expr(argument) else {
return;
};
if !checker.semantic().has_builtin_binding("set") {
return;
}
let mut diagnostic = checker.report_diagnostic(UnnecessaryLiteralSet { kind }, call.range());
// Convert `set((1, 2))` to `{1, 2}`.
diagnostic.set_fix({
let elts = match &argument {
Expr::List(ast::ExprList { elts, .. }) => elts,
Expr::Tuple(ast::ExprTuple { elts, .. }) => elts,
_ => unreachable!(),
};
match elts.as_slice() {
// If the list or tuple is empty, replace the entire call with `set()`.
[] => Fix::unsafe_edit(Edit::range_replacement("set()".to_string(), call.range())),
// If it's a single-element tuple (with no whitespace around it), remove the trailing
// comma.
[elt]
if argument.is_tuple_expr()
// The element must start right after the `(`.
&& elt.start() == argument.start() + TextSize::new(1)
// The element must be followed by exactly one comma and a closing `)`.
&& elt.end() + TextSize::new(2) == argument.end() =>
{
// Replace from the start of the call to the start of the inner element.
let call_start = Edit::replacement(
pad_start("{", call.range(), checker.locator(), checker.semantic()),
call.start(),
elt.start(),
);
// Replace from the end of the inner element to the end of the call with `}`.
let call_end = Edit::replacement(
pad_end("}", call.range(), checker.locator(), checker.semantic()),
elt.end(),
call.end(),
);
Fix::unsafe_edits(call_start, [call_end])
}
_ => {
// Replace from the start of the call to the start of the inner list or tuple with `{`.
let call_start = Edit::replacement(
pad_start("{", call.range(), checker.locator(), checker.semantic()),
call.start(),
argument.start() + TextSize::from(1),
);
// Replace from the end of the inner list or tuple to the end of the call with `}`.
let call_end = Edit::replacement(
pad_end("}", call.range(), checker.locator(), checker.semantic()),
argument.end() - TextSize::from(1),
call.end(),
);
Fix::unsafe_edits(call_start, [call_end])
}
}
});
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UnnecessaryLiteral {
List,
Tuple,
}
impl UnnecessaryLiteral {
const fn try_from_expr(expr: &Expr) -> Option<Self> {
match expr {
Expr::List(_) => Some(Self::List),
Expr::Tuple(_) => Some(Self::Tuple),
_ => None,
}
}
const fn as_str(self) -> &'static str {
match self {
Self::Tuple => "tuple",
Self::List => "list",
}
}
}
impl std::fmt::Display for UnnecessaryLiteral {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Applicability, Fix};
use crate::rules::flake8_comprehensions::fixes;
/// ## What it does
/// Checks for unnecessary `list()` or `reversed()` calls around `sorted()`
/// calls.
///
/// ## Why is this bad?
/// It is unnecessary to use `list()` around `sorted()`, as the latter already
/// returns a list.
///
/// It is also unnecessary to use `reversed()` around `sorted()`, as the latter
/// has a `reverse` argument that can be used in lieu of an additional
/// `reversed()` call.
///
/// In both cases, it's clearer and more efficient to avoid the redundant call.
///
/// ## Example
/// ```python
/// reversed(sorted(iterable))
/// ```
///
/// Use instead:
/// ```python
/// sorted(iterable, reverse=True)
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe for `reversed()` cases, as `reversed()`
/// and `reverse=True` will yield different results in the event of custom sort
/// keys or equality functions. Specifically, `reversed()` will reverse the order
/// of the collection, while `sorted()` with `reverse=True` will perform a stable
/// reverse sort, which will preserve the order of elements that compare as
/// equal.
///
/// The fix is marked as safe for `list()` cases, as removing `list()` around
/// `sorted()` does not change the behavior.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.73")]
pub(crate) struct UnnecessaryCallAroundSorted {
func: UnnecessaryFunction,
}
impl AlwaysFixableViolation for UnnecessaryCallAroundSorted {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryCallAroundSorted { func } = self;
format!("Unnecessary `{func}()` call around `sorted()`")
}
fn fix_title(&self) -> String {
let UnnecessaryCallAroundSorted { func } = self;
format!("Remove unnecessary `{func}()` call")
}
}
/// C413
pub(crate) fn unnecessary_call_around_sorted(
checker: &Checker,
expr: &Expr,
outer_func: &Expr,
args: &[Expr],
) {
let Some(Expr::Call(ast::ExprCall {
func: inner_func, ..
})) = args.first()
else {
return;
};
let semantic = checker.semantic();
let Some(outer_func_name) = semantic.resolve_builtin_symbol(outer_func) else {
return;
};
let Some(unnecessary_function) = UnnecessaryFunction::try_from_str(outer_func_name) else {
return;
};
if !semantic.match_builtin_expr(inner_func, "sorted") {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryCallAroundSorted {
func: unnecessary_function,
},
expr.range(),
);
diagnostic.try_set_fix(|| {
let edit =
fixes::fix_unnecessary_call_around_sorted(expr, checker.locator(), checker.stylist())?;
let applicability = match unnecessary_function {
UnnecessaryFunction::List => Applicability::Safe,
UnnecessaryFunction::Reversed => Applicability::Unsafe,
};
Ok(Fix::applicable_edit(edit, applicability))
});
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum UnnecessaryFunction {
List,
Reversed,
}
impl UnnecessaryFunction {
fn try_from_str(name: &str) -> Option<Self> {
match name {
"list" => Some(Self::List),
"reversed" => Some(Self::Reversed),
_ => None,
}
}
const fn as_str(self) -> &'static str {
match self {
Self::List => "list",
Self::Reversed => "reversed",
}
}
}
impl std::fmt::Display for UnnecessaryFunction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, Keyword};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::rules::flake8_comprehensions::fixes;
use crate::{AlwaysFixableViolation, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for unnecessary list or tuple literals.
///
/// ## Why is this bad?
/// It's unnecessary to use a list or tuple literal within a call to `dict()`.
/// It can be rewritten as a dict literal (`{}`).
///
/// ## Example
/// ```python
/// dict([(1, 2), (3, 4)])
/// dict(((1, 2), (3, 4)))
/// dict([])
/// ```
///
/// Use instead:
/// ```python
/// {1: 2, 3: 4}
/// {1: 2, 3: 4}
/// {}
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.61")]
pub(crate) struct UnnecessaryLiteralDict {
obj_type: LiteralKind,
}
impl AlwaysFixableViolation for UnnecessaryLiteralDict {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryLiteralDict { obj_type } = self;
format!("Unnecessary {obj_type} literal (rewrite as a dict literal)")
}
fn fix_title(&self) -> String {
"Rewrite as a dict literal".to_string()
}
}
/// C406 (`dict([(1, 2)])`)
pub(crate) fn unnecessary_literal_dict(
checker: &Checker,
expr: &Expr,
func: &Expr,
args: &[Expr],
keywords: &[Keyword],
) {
let Some(argument) =
helpers::exactly_one_argument_with_matching_function("dict", func, args, keywords)
else {
return;
};
let (kind, elts) = match argument {
Expr::Tuple(ast::ExprTuple { elts, .. }) => (LiteralKind::Tuple, elts),
Expr::List(ast::ExprList { elts, .. }) => (LiteralKind::List, elts),
_ => return,
};
// Accept `dict((1, 2), ...))` `dict([(1, 2), ...])`.
if !elts
.iter()
.all(|elt| matches!(&elt, Expr::Tuple(tuple) if tuple.len() == 2))
{
return;
}
if !checker.semantic().has_builtin_binding("dict") {
return;
}
let mut diagnostic =
checker.report_diagnostic(UnnecessaryLiteralDict { obj_type: kind }, expr.range());
diagnostic
.try_set_fix(|| fixes::fix_unnecessary_literal_dict(expr, checker).map(Fix::unsafe_edit));
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum LiteralKind {
Tuple,
List,
}
impl LiteralKind {
const fn as_str(self) -> &'static str {
match self {
Self::Tuple => "tuple",
Self::List => "list",
}
}
}
impl std::fmt::Display for LiteralKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_dict_comprehension_for_iterable.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_dict_comprehension_for_iterable.rs | use ast::ExprName;
use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::any_over_expr;
use ruff_python_ast::{self as ast, Arguments, Comprehension, Expr, ExprCall, ExprContext};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::edits::pad_start;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for unnecessary dict comprehension when creating a dictionary from
/// an iterable.
///
/// ## Why is this bad?
/// It's unnecessary to use a dict comprehension to build a dictionary from
/// an iterable when the value is static.
///
/// Prefer `dict.fromkeys(iterable)` over `{value: None for value in iterable}`,
/// as `dict.fromkeys` is more readable and efficient.
///
/// ## Example
/// ```python
/// {a: None for a in iterable}
/// {a: 1 for a in iterable}
/// ```
///
/// Use instead:
/// ```python
/// dict.fromkeys(iterable)
/// dict.fromkeys(iterable, 1)
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe if there's comments inside the dict comprehension,
/// as comments may be removed.
///
/// For example, the fix would be marked as unsafe in the following case:
/// ```python
/// { # comment 1
/// a: # comment 2
/// None # comment 3
/// for a in iterable # comment 4
/// }
/// ```
///
/// ## References
/// - [Python documentation: `dict.fromkeys`](https://docs.python.org/3/library/stdtypes.html#dict.fromkeys)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.10.0")]
pub(crate) struct UnnecessaryDictComprehensionForIterable {
is_value_none_literal: bool,
}
impl Violation for UnnecessaryDictComprehensionForIterable {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead".to_string()
}
fn fix_title(&self) -> Option<String> {
let title = if self.is_value_none_literal {
"Replace with `dict.fromkeys(iterable, value)`)"
} else {
"Replace with `dict.fromkeys(iterable)`)"
};
Some(title.to_string())
}
}
/// C420
pub(crate) fn unnecessary_dict_comprehension_for_iterable(
checker: &Checker,
dict_comp: &ast::ExprDictComp,
) {
let [generator] = dict_comp.generators.as_slice() else {
return;
};
// Don't suggest `dict.fromkeys` for:
// - async generator expressions, because `dict.fromkeys` is not async.
// - nested generator expressions, because `dict.fromkeys` might be error-prone option at least for fixing.
// - generator expressions with `if` clauses, because `dict.fromkeys` might not be valid option.
if !generator.ifs.is_empty() {
return;
}
if generator.is_async {
return;
}
// Don't suggest `dict.keys` if the target is not the same as the key.
if ComparableExpr::from(&generator.target) != ComparableExpr::from(dict_comp.key.as_ref()) {
return;
}
// Don't suggest `dict.fromkeys` if the target contains side-effecting expressions
// (attributes, subscripts, or slices).
if contains_side_effecting_sub_expression(&generator.target) {
return;
}
// Don't suggest `dict.fromkeys` if the value is not a constant or constant-like.
if !is_constant_like(dict_comp.value.as_ref()) {
return;
}
// Don't suggest `dict.fromkeys` if any of the expressions in the value are defined within
// the comprehension (e.g., by the target).
let self_referential = any_over_expr(dict_comp.value.as_ref(), &|expr| {
let Expr::Name(name) = expr else {
return false;
};
let Some(id) = checker.semantic().resolve_name(name) else {
return false;
};
let binding = checker.semantic().binding(id);
// Builtin bindings have a range of 0..0, and are never
// defined within the comprehension, so we abort before
// checking the range overlap below. Note this only matters
// if the comprehension appears at the top of the file!
if binding.kind.is_builtin() {
return false;
}
dict_comp.range().contains_range(binding.range())
});
if self_referential {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryDictComprehensionForIterable {
is_value_none_literal: dict_comp.value.is_none_literal_expr(),
},
dict_comp.range(),
);
if checker.semantic().has_builtin_binding("dict") {
let edit = Edit::range_replacement(
pad_start(
checker
.generator()
.expr(&fix_unnecessary_dict_comprehension(
dict_comp.value.as_ref(),
generator,
)),
dict_comp.start(),
checker.locator(),
),
dict_comp.range(),
);
diagnostic.set_fix(Fix::applicable_edit(
edit,
if checker.comment_ranges().intersects(dict_comp.range()) {
Applicability::Unsafe
} else {
Applicability::Safe
},
));
}
}
/// Returns `true` if the expression can be shared across multiple values.
///
/// When converting from `{key: value for key in iterable}` to `dict.fromkeys(iterable, value)`,
/// the `value` is shared across all values without being evaluated multiple times. If the value
/// contains, e.g., a function call, it cannot be shared, as the function might have side effects.
/// Similarly, if the value contains a list comprehension, it cannot be shared, as `dict.fromkeys`
/// would leave each value with a reference to the same list.
fn is_constant_like(expr: &Expr) -> bool {
!any_over_expr(expr, &|expr| {
matches!(
expr,
Expr::Lambda(_)
| Expr::List(_)
| Expr::Dict(_)
| Expr::Set(_)
| Expr::ListComp(_)
| Expr::SetComp(_)
| Expr::DictComp(_)
| Expr::Generator(_)
| Expr::Await(_)
| Expr::Yield(_)
| Expr::YieldFrom(_)
| Expr::Call(_)
| Expr::Named(_)
)
})
}
/// Generate a [`Fix`] to replace a dict comprehension with `dict.fromkeys`.
///
/// For example:
/// - Given `{n: None for n in [1,2,3]}`, generate `dict.fromkeys([1,2,3])`.
/// - Given `{n: 1 for n in [1,2,3]}`, generate `dict.fromkeys([1,2,3], 1)`.
fn fix_unnecessary_dict_comprehension(value: &Expr, generator: &Comprehension) -> Expr {
let iterable = generator.iter.clone();
let args = Arguments {
args: if value.is_none_literal_expr() {
Box::from([iterable])
} else {
Box::from([iterable, value.clone()])
},
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
Expr::Call(ExprCall {
func: Box::new(Expr::Name(ExprName {
id: "dict.fromkeys".into(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})),
arguments: args,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})
}
fn contains_side_effecting_sub_expression(target: &Expr) -> bool {
any_over_expr(target, &|expr| {
matches!(
expr,
Expr::Attribute(_) | Expr::Subscript(_) | Expr::Slice(_)
)
})
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_in_call.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_in_call.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::any_over_expr;
use ruff_python_ast::{self as ast, Expr, Keyword};
use ruff_text_size::{Ranged, TextSize};
use crate::FixAvailability;
use crate::checkers::ast::Checker;
use crate::preview::is_comprehension_with_min_max_sum_enabled;
use crate::rules::flake8_comprehensions::fixes;
use crate::{Edit, Fix, Violation};
/// ## What it does
/// Checks for unnecessary list or set comprehensions passed to builtin functions that take an iterable.
///
/// Set comprehensions are only a violation in the case where the builtin function does not care about
/// duplication of elements in the passed iterable.
///
/// ## Why is this bad?
/// Many builtin functions (this rule currently covers `any` and `all` in stable, along with `min`,
/// `max`, and `sum` in [preview]) accept any iterable, including a generator. Constructing a
/// temporary list via list comprehension is unnecessary and wastes memory for large iterables.
///
/// `any` and `all` can also short-circuit iteration, saving a lot of time. The unnecessary
/// comprehension forces a full iteration of the input iterable, giving up the benefits of
/// short-circuiting. For example, compare the performance of `all` with a list comprehension
/// against that of a generator in a case where an early short-circuit is possible (almost 40x
/// faster):
///
/// ```console
/// In [1]: %timeit all([i for i in range(1000)])
/// 8.14 Β΅s Β± 25.4 ns per loop (mean Β± std. dev. of 7 runs, 100,000 loops each)
///
/// In [2]: %timeit all(i for i in range(1000))
/// 212 ns Β± 0.892 ns per loop (mean Β± std. dev. of 7 runs, 1,000,000 loops each)
/// ```
///
/// This performance improvement is due to short-circuiting. If the entire iterable has to be
/// traversed, the comprehension version may even be a bit faster: list allocation overhead is not
/// necessarily greater than generator overhead.
///
/// Applying this rule simplifies the code and will usually save memory, but in the absence of
/// short-circuiting it may not improve performance. (It may even slightly regress performance,
/// though the difference will usually be small.)
///
/// ## Example
/// ```python
/// any([x.id for x in bar])
/// all([x.id for x in bar])
/// sum([x.val for x in bar])
/// min([x.val for x in bar])
/// max([x.val for x in bar])
/// ```
///
/// Use instead:
/// ```python
/// any(x.id for x in bar)
/// all(x.id for x in bar)
/// sum(x.val for x in bar)
/// min(x.val for x in bar)
/// max(x.val for x in bar)
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it can change the behavior of the code if the iteration
/// has side effects (due to laziness and short-circuiting). The fix may also drop comments when
/// rewriting some comprehensions.
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.262")]
pub(crate) struct UnnecessaryComprehensionInCall {
comprehension_kind: ComprehensionKind,
}
impl Violation for UnnecessaryComprehensionInCall {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
match self.comprehension_kind {
ComprehensionKind::List => "Unnecessary list comprehension".to_string(),
ComprehensionKind::Set => "Unnecessary set comprehension".to_string(),
}
}
fn fix_title(&self) -> Option<String> {
Some("Remove unnecessary comprehension".to_string())
}
}
/// C419
pub(crate) fn unnecessary_comprehension_in_call(
checker: &Checker,
expr: &Expr,
func: &Expr,
args: &[Expr],
keywords: &[Keyword],
) {
if !keywords.is_empty() {
return;
}
let Some(arg) = args.first() else {
return;
};
let (Expr::ListComp(ast::ExprListComp {
elt, generators, ..
})
| Expr::SetComp(ast::ExprSetComp {
elt, generators, ..
})) = arg
else {
return;
};
if contains_await(elt) {
return;
}
if generators.iter().any(|generator| generator.is_async) {
return;
}
let Some(Ok(builtin_function)) = checker
.semantic()
.resolve_builtin_symbol(func)
.map(SupportedBuiltins::try_from)
else {
return;
};
if !(matches!(
builtin_function,
SupportedBuiltins::Any | SupportedBuiltins::All
) || (is_comprehension_with_min_max_sum_enabled(checker.settings())
&& matches!(
builtin_function,
SupportedBuiltins::Sum | SupportedBuiltins::Min | SupportedBuiltins::Max
)))
{
return;
}
let mut diagnostic = match (arg, builtin_function.duplication_variance()) {
(Expr::ListComp(_), _) => checker.report_diagnostic(
UnnecessaryComprehensionInCall {
comprehension_kind: ComprehensionKind::List,
},
arg.range(),
),
(Expr::SetComp(_), DuplicationVariance::Invariant) => checker.report_diagnostic(
UnnecessaryComprehensionInCall {
comprehension_kind: ComprehensionKind::Set,
},
arg.range(),
),
_ => {
return;
}
};
if args.len() == 1 {
// If there's only one argument, remove the list or set brackets.
diagnostic.try_set_fix(|| {
fixes::fix_unnecessary_comprehension_in_call(expr, checker.locator(), checker.stylist())
});
} else {
// If there are multiple arguments, replace the list or set brackets with parentheses.
// If a function call has multiple arguments, one of which is a generator, then the
// generator must be parenthesized.
// Replace `[` with `(`.
let collection_start = Edit::replacement(
"(".to_string(),
arg.start(),
arg.start() + TextSize::from(1),
);
// Replace `]` with `)`.
let collection_end =
Edit::replacement(")".to_string(), arg.end() - TextSize::from(1), arg.end());
diagnostic.set_fix(Fix::unsafe_edits(collection_start, [collection_end]));
}
}
/// Return `true` if the [`Expr`] contains an `await` expression.
fn contains_await(expr: &Expr) -> bool {
any_over_expr(expr, &Expr::is_await_expr)
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum DuplicationVariance {
Invariant,
Variant,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ComprehensionKind {
List,
Set,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum SupportedBuiltins {
All,
Any,
Sum,
Min,
Max,
}
impl TryFrom<&str> for SupportedBuiltins {
type Error = &'static str;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"all" => Ok(Self::All),
"any" => Ok(Self::Any),
"sum" => Ok(Self::Sum),
"min" => Ok(Self::Min),
"max" => Ok(Self::Max),
_ => Err("Unsupported builtin for `unnecessary-comprehension-in-call`"),
}
}
}
impl SupportedBuiltins {
fn duplication_variance(self) -> DuplicationVariance {
match self {
SupportedBuiltins::All
| SupportedBuiltins::Any
| SupportedBuiltins::Min
| SupportedBuiltins::Max => DuplicationVariance::Invariant,
SupportedBuiltins::Sum => DuplicationVariance::Variant,
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Comprehension, Expr};
use ruff_python_semantic::analyze::typing;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Fix};
use crate::rules::flake8_comprehensions::fixes;
/// ## What it does
/// Checks for unnecessary dict, list, and set comprehension.
///
/// ## Why is this bad?
/// It's unnecessary to use a dict/list/set comprehension to build a data structure if the
/// elements are unchanged. Wrap the iterable with `dict()`, `list()`, or `set()` instead.
///
/// ## Example
/// ```python
/// {a: b for a, b in iterable}
/// [x for x in iterable]
/// {x for x in iterable}
/// ```
///
/// Use instead:
/// ```python
/// dict(iterable)
/// list(iterable)
/// set(iterable)
/// ```
///
/// ## Known problems
///
/// This rule may produce false positives for dictionary comprehensions that iterate over a mapping.
/// The dict constructor behaves differently depending on if it receives a sequence (e.g., a
/// list) or a mapping (e.g., a dict). When a comprehension iterates over the keys of a mapping,
/// replacing it with a `dict()` constructor call will give a different result.
///
/// For example:
///
/// ```pycon
/// >>> d1 = {(1, 2): 3, (4, 5): 6}
/// >>> {x: y for x, y in d1} # Iterates over the keys of a mapping
/// {1: 2, 4: 5}
/// >>> dict(d1) # Ruff's incorrect suggested fix
/// {(1, 2): 3, (4, 5): 6}
/// >>> dict(d1.keys()) # Correct fix
/// {1: 2, 4: 5}
/// ```
///
/// When the comprehension iterates over a sequence, Ruff's suggested fix is correct. However, Ruff
/// cannot consistently infer if the iterable type is a sequence or a mapping and cannot suggest
/// the correct fix for mappings.
///
/// ## Fix safety
/// Due to the known problem with dictionary comprehensions, this fix is marked as unsafe.
///
/// Additionally, this fix may drop comments when rewriting the comprehension.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.73")]
pub(crate) struct UnnecessaryComprehension {
kind: ComprehensionKind,
}
impl AlwaysFixableViolation for UnnecessaryComprehension {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryComprehension { kind } = self;
format!("Unnecessary {kind} comprehension (rewrite using `{kind}()`)")
}
fn fix_title(&self) -> String {
let UnnecessaryComprehension { kind } = self;
format!("Rewrite using `{kind}()`")
}
}
/// Add diagnostic for C416 based on the expression node id.
fn add_diagnostic(checker: &Checker, expr: &Expr) {
let Some(comprehension_kind) = ComprehensionKind::try_from_expr(expr) else {
return;
};
if !checker
.semantic()
.has_builtin_binding(comprehension_kind.as_str())
{
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryComprehension {
kind: comprehension_kind,
},
expr.range(),
);
diagnostic.try_set_fix(|| {
fixes::fix_unnecessary_comprehension(expr, checker.locator(), checker.stylist())
.map(Fix::unsafe_edit)
});
}
/// C416
pub(crate) fn unnecessary_dict_comprehension(
checker: &Checker,
expr: &Expr,
key: &Expr,
value: &Expr,
generators: &[Comprehension],
) {
let [generator] = generators else {
return;
};
if !generator.ifs.is_empty() || generator.is_async {
return;
}
let Expr::Tuple(ast::ExprTuple { elts, .. }) = &generator.target else {
return;
};
let [
Expr::Name(ast::ExprName { id: target_key, .. }),
Expr::Name(ast::ExprName {
id: target_value, ..
}),
] = elts.as_slice()
else {
return;
};
let Expr::Name(ast::ExprName { id: key, .. }) = &key else {
return;
};
let Expr::Name(ast::ExprName { id: value, .. }) = &value else {
return;
};
if target_key == key && target_value == value {
add_diagnostic(checker, expr);
}
}
/// C416
pub(crate) fn unnecessary_list_set_comprehension(
checker: &Checker,
expr: &Expr,
elt: &Expr,
generators: &[Comprehension],
) {
let [generator] = generators else {
return;
};
if !generator.ifs.is_empty() || generator.is_async {
return;
}
if is_dict_items(checker, &generator.iter) {
match (&generator.target, elt) {
// [(k, v) for k, v in dict.items()] or [(k, v) for [k, v] in dict.items()]
(
Expr::Tuple(ast::ExprTuple {
elts: target_elts, ..
})
| Expr::List(ast::ExprList {
elts: target_elts, ..
}),
Expr::Tuple(ast::ExprTuple { elts, .. }),
) => {
let [
Expr::Name(ast::ExprName { id: target_key, .. }),
Expr::Name(ast::ExprName {
id: target_value, ..
}),
] = target_elts.as_slice()
else {
return;
};
let [
Expr::Name(ast::ExprName { id: key, .. }),
Expr::Name(ast::ExprName { id: value, .. }),
] = elts.as_slice()
else {
return;
};
if target_key == key && target_value == value {
add_diagnostic(checker, expr);
}
}
// [x for x in dict.items()]
(
Expr::Name(ast::ExprName {
id: target_name, ..
}),
Expr::Name(ast::ExprName { id: elt_name, .. }),
) if target_name == elt_name => {
add_diagnostic(checker, expr);
}
_ => {}
}
} else {
// [x for x in iterable]
let Expr::Name(ast::ExprName {
id: target_name, ..
}) = &generator.target
else {
return;
};
let Expr::Name(ast::ExprName { id: elt_name, .. }) = &elt else {
return;
};
if elt_name == target_name {
add_diagnostic(checker, expr);
}
}
}
fn is_dict_items(checker: &Checker, expr: &Expr) -> bool {
let Expr::Call(ast::ExprCall { func, .. }) = expr else {
return false;
};
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() else {
return false;
};
if attr.as_str() != "items" {
return false;
}
let Expr::Name(name) = value.as_ref() else {
return false;
};
let Some(id) = checker.semantic().resolve_name(name) else {
return false;
};
typing::is_dict(checker.semantic().binding(id), checker.semantic())
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ComprehensionKind {
List,
Set,
Dict,
}
impl ComprehensionKind {
const fn as_str(self) -> &'static str {
match self {
Self::List => "list",
Self::Dict => "dict",
Self::Set => "set",
}
}
const fn try_from_expr(expr: &Expr) -> Option<Self> {
match expr {
Expr::ListComp(_) => Some(Self::List),
Expr::DictComp(_) => Some(Self::Dict),
Expr::SetComp(_) => Some(Self::Set),
_ => None,
}
}
}
impl std::fmt::Display for ComprehensionKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::ExprGenerator;
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::token::TokenKind;
use ruff_python_ast::token::parenthesized_range;
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for unnecessary generators that can be rewritten as list
/// comprehensions (or with `list()` directly).
///
/// ## Why is this bad?
/// It is unnecessary to use `list()` around a generator expression, since
/// there are equivalent comprehensions for these types. Using a
/// comprehension is clearer and more idiomatic.
///
/// Further, if the comprehension can be removed entirely, as in the case of
/// `list(x for x in foo)`, it's better to use `list(foo)` directly, since it's
/// even more direct.
///
/// ## Example
/// ```python
/// list(f(x) for x in foo)
/// list(x for x in foo)
/// list((x for x in foo))
/// ```
///
/// Use instead:
/// ```python
/// [f(x) for x in foo]
/// list(foo)
/// list(foo)
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.61")]
pub(crate) struct UnnecessaryGeneratorList {
short_circuit: bool,
}
impl AlwaysFixableViolation for UnnecessaryGeneratorList {
#[derive_message_formats]
fn message(&self) -> String {
if self.short_circuit {
"Unnecessary generator (rewrite using `list()`)".to_string()
} else {
"Unnecessary generator (rewrite as a list comprehension)".to_string()
}
}
fn fix_title(&self) -> String {
if self.short_circuit {
"Rewrite using `list()`".to_string()
} else {
"Rewrite as a list comprehension".to_string()
}
}
}
/// C400 (`list(generator)`)
pub(crate) fn unnecessary_generator_list(checker: &Checker, call: &ast::ExprCall) {
let Some(argument) = helpers::exactly_one_argument_with_matching_function(
"list",
&call.func,
&call.arguments.args,
&call.arguments.keywords,
) else {
return;
};
let ast::Expr::Generator(ExprGenerator {
elt,
generators,
parenthesized,
..
}) = argument
else {
return;
};
if !checker.semantic().has_builtin_binding("list") {
return;
}
// Short-circuit: given `list(x for x in y)`, generate `list(y)` (in lieu of `[x for x in y]`).
if let [generator] = generators.as_slice() {
if generator.ifs.is_empty() && !generator.is_async {
if ComparableExpr::from(elt) == ComparableExpr::from(&generator.target) {
let iterator = format!("list({})", checker.locator().slice(generator.iter.range()));
let fix = Fix::unsafe_edit(Edit::range_replacement(iterator, call.range()));
checker
.report_diagnostic(
UnnecessaryGeneratorList {
short_circuit: true,
},
call.range(),
)
.set_fix(fix);
return;
}
}
}
// Convert `list(f(x) for x in y)` to `[f(x) for x in y]`.
let mut diagnostic = checker.report_diagnostic(
UnnecessaryGeneratorList {
short_circuit: false,
},
call.range(),
);
let fix = {
// Replace `list(` with `[`.
let call_start = Edit::replacement(
"[".to_string(),
call.start(),
call.arguments.start() + TextSize::from(1),
);
// Replace `)` with `]`.
// Place `]` at argument's end or at trailing comma if present
let after_arg_tokens = checker
.tokens()
.in_range(TextRange::new(argument.end(), call.end()));
let right_bracket_loc = after_arg_tokens
.iter()
.find(|token| token.kind() == TokenKind::Comma)
.map_or(call.arguments.end(), Ranged::end)
- TextSize::from(1);
let call_end = Edit::replacement("]".to_string(), right_bracket_loc, call.end());
// Remove the inner parentheses, if the expression is a generator. The easiest way to do
// this reliably is to use the printer.
if *parenthesized {
// The generator's range will include the innermost parentheses, but it could be
// surrounded by additional parentheses.
let range =
parenthesized_range(argument.into(), (&call.arguments).into(), checker.tokens())
.unwrap_or(argument.range());
// The generator always parenthesizes the expression; trim the parentheses.
let generator = checker.generator().expr(argument);
let generator = generator[1..generator.len() - 1].to_string();
let replacement = Edit::range_replacement(generator, range);
Fix::unsafe_edits(call_start, [call_end, replacement])
} else {
Fix::unsafe_edits(call_start, [call_end])
}
};
diagnostic.set_fix(fix);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs | crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::{Ranged, TextSize};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::rules::flake8_comprehensions::helpers;
/// ## What it does
/// Checks for `list()` calls that take unnecessary list or tuple literals as
/// arguments.
///
/// ## Why is this bad?
/// It's unnecessary to use a list or tuple literal within a `list()` call,
/// since there is a literal syntax for these types.
///
/// If a list literal is passed in, then the outer call to `list()` should be
/// removed. Otherwise, if a tuple literal is passed in, then it should be
/// rewritten as a list literal.
///
/// ## Example
/// ```python
/// list([1, 2])
/// list((1, 2))
/// ```
///
/// Use instead:
/// ```python
/// [1, 2]
/// [1, 2]
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may occasionally drop comments
/// when rewriting the call. In most cases, though, comments will be preserved.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.66")]
pub(crate) struct UnnecessaryLiteralWithinListCall {
kind: LiteralKind,
}
impl AlwaysFixableViolation for UnnecessaryLiteralWithinListCall {
#[derive_message_formats]
fn message(&self) -> String {
match self.kind {
LiteralKind::List => {
"Unnecessary list literal passed to `list()` (remove the outer call to `list()`)"
.to_string()
}
LiteralKind::Tuple => {
"Unnecessary tuple literal passed to `list()` (rewrite as a single list literal)"
.to_string()
}
}
}
fn fix_title(&self) -> String {
match self.kind {
LiteralKind::List => "Remove outer `list()` call".to_string(),
LiteralKind::Tuple => "Rewrite as a single list literal".to_string(),
}
}
}
/// C410
pub(crate) fn unnecessary_literal_within_list_call(checker: &Checker, call: &ast::ExprCall) {
if !call.arguments.keywords.is_empty() {
return;
}
if call.arguments.args.len() > 1 {
return;
}
let Some(argument) =
helpers::first_argument_with_matching_function("list", &call.func, &call.arguments.args)
else {
return;
};
let Some(argument_kind) = LiteralKind::try_from_expr(argument) else {
return;
};
if !checker.semantic().has_builtin_binding("list") {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryLiteralWithinListCall {
kind: argument_kind,
},
call.range(),
);
// Convert `list([1, 2])` to `[1, 2]`
let fix = {
// Delete from the start of the call to the start of the argument.
let call_start = Edit::deletion(call.start(), argument.start());
// Delete from the end of the argument to the end of the call.
let call_end = Edit::deletion(argument.end(), call.end());
// If this is a tuple, we also need to convert the inner argument to a list.
if argument.is_tuple_expr() {
// Replace `(` with `[`.
let argument_start = Edit::replacement(
"[".to_string(),
argument.start(),
argument.start() + TextSize::from(1),
);
// Replace `)` with `]`.
let argument_end = Edit::replacement(
"]".to_string(),
argument.end() - TextSize::from(1),
argument.end(),
);
Fix::unsafe_edits(call_start, [argument_start, argument_end, call_end])
} else {
Fix::unsafe_edits(call_start, [call_end])
}
};
diagnostic.set_fix(fix);
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum LiteralKind {
Tuple,
List,
}
impl LiteralKind {
const fn try_from_expr(expr: &Expr) -> Option<Self> {
match expr {
Expr::Tuple(_) => Some(Self::Tuple),
Expr::List(_) => Some(Self::List),
_ => None,
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/helpers.rs | crates/ruff_linter/src/rules/tryceratops/helpers.rs | use ruff_python_ast::visitor;
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{self as ast, ExceptHandler, Expr};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::logging;
use ruff_python_stdlib::logging::LoggingLevel;
/// Collect `logging`-like calls from an AST.
pub(super) struct LoggerCandidateVisitor<'a, 'b> {
semantic: &'a SemanticModel<'b>,
logger_objects: &'a [String],
pub(super) calls: Vec<(&'b ast::ExprCall, LoggingLevel)>,
}
impl<'a, 'b> LoggerCandidateVisitor<'a, 'b> {
pub(super) fn new(semantic: &'a SemanticModel<'b>, logger_objects: &'a [String]) -> Self {
LoggerCandidateVisitor {
semantic,
logger_objects,
calls: Vec::new(),
}
}
}
impl<'b> Visitor<'b> for LoggerCandidateVisitor<'_, 'b> {
fn visit_expr(&mut self, expr: &'b Expr) {
if let Expr::Call(call) = expr {
match call.func.as_ref() {
Expr::Attribute(ast::ExprAttribute { attr, .. }) => {
if logging::is_logger_candidate(&call.func, self.semantic, self.logger_objects)
{
if let Some(logging_level) = LoggingLevel::from_attribute(attr) {
self.calls.push((call, logging_level));
}
}
}
Expr::Name(_) => {
if let Some(qualified_name) =
self.semantic.resolve_qualified_name(call.func.as_ref())
{
if let ["logging", attribute] = qualified_name.segments() {
if let Some(logging_level) = LoggingLevel::from_attribute(attribute) {
{
self.calls.push((call, logging_level));
}
}
}
}
}
_ => {}
}
}
visitor::walk_expr(self, expr);
}
fn visit_except_handler(&mut self, _except_handler: &'b ExceptHandler) {
// Don't recurse into exception handlers, since we'll re-run the visitor on any such
// handlers.
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/mod.rs | crates/ruff_linter/src/rules/tryceratops/mod.rs | //! Rules from [tryceratops](https://pypi.org/project/tryceratops/).
pub(crate) mod helpers;
pub(crate) mod rules;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test_case(Rule::RaiseVanillaClass, Path::new("TRY002.py"))]
#[test_case(Rule::RaiseVanillaArgs, Path::new("TRY003.py"))]
#[test_case(Rule::TypeCheckWithoutTypeError, Path::new("TRY004.py"))]
#[test_case(Rule::VerboseRaise, Path::new("TRY201.py"))]
#[test_case(Rule::UselessTryExcept, Path::new("TRY203.py"))]
#[test_case(Rule::TryConsiderElse, Path::new("TRY300.py"))]
#[test_case(Rule::RaiseWithinTry, Path::new("TRY301.py"))]
#[test_case(Rule::ErrorInsteadOfException, Path::new("TRY400.py"))]
#[test_case(Rule::VerboseLogMessage, Path::new("TRY401.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.name(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("tryceratops").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/verbose_log_message.rs | crates/ruff_linter/src/rules/tryceratops/rules/verbose_log_message.rs | use ruff_python_ast::{self as ast, ExceptHandler, Expr};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::visitor;
use ruff_python_ast::visitor::Visitor;
use ruff_python_stdlib::logging::LoggingLevel;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::tryceratops::helpers::LoggerCandidateVisitor;
/// ## What it does
/// Checks for excessive logging of exception objects.
///
/// ## Why is this bad?
/// When logging exceptions via `logging.exception`, the exception object
/// is logged automatically. Including the exception object in the log
/// message is redundant and can lead to excessive logging.
///
/// ## Example
/// ```python
/// try:
/// ...
/// except ValueError as e:
/// logger.exception(f"Found an error: {e}")
/// ```
///
/// Use instead:
/// ```python
/// try:
/// ...
/// except ValueError:
/// logger.exception("Found an error")
/// ```
///
/// ## Options
///
/// - `lint.logger-objects`
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.250")]
pub(crate) struct VerboseLogMessage;
impl Violation for VerboseLogMessage {
#[derive_message_formats]
fn message(&self) -> String {
"Redundant exception object included in `logging.exception` call".to_string()
}
}
/// TRY401
pub(crate) fn verbose_log_message(checker: &Checker, handlers: &[ExceptHandler]) {
for handler in handlers {
let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) = handler;
// Find all calls to `logging.exception`.
let calls = {
let mut visitor =
LoggerCandidateVisitor::new(checker.semantic(), &checker.settings().logger_objects);
visitor.visit_body(body);
visitor.calls
};
for (expr, logging_level) in calls {
if matches!(logging_level, LoggingLevel::Exception) {
// Collect all referenced names in the `logging.exception` call.
let names: Vec<&ast::ExprName> = {
expr.arguments
.args
.iter()
.flat_map(|arg| {
let mut visitor = NameVisitor::default();
visitor.visit_expr(arg);
visitor.names
})
.collect()
};
// Find any bound exceptions in the call.
for expr in names {
let Some(id) = checker.semantic().resolve_name(expr) else {
continue;
};
let binding = checker.semantic().binding(id);
if binding.kind.is_bound_exception() {
checker.report_diagnostic(VerboseLogMessage, expr.range());
}
}
}
}
}
}
#[derive(Default)]
struct NameVisitor<'a> {
names: Vec<&'a ast::ExprName>,
}
impl<'a> Visitor<'a> for NameVisitor<'a> {
fn visit_expr(&mut self, expr: &'a Expr) {
match expr {
Expr::Name(name) if name.ctx.is_load() => self.names.push(name),
Expr::Attribute(_) => {}
_ => visitor::walk_expr(self, expr),
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_args.rs | crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_args.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Arguments, Expr};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for long exception messages that are not defined in the exception
/// class itself.
///
/// ## Why is this bad?
/// By formatting an exception message at the `raise` site, the exception class
/// becomes less reusable, and may now raise inconsistent messages depending on
/// where it is raised.
///
/// If the exception message is instead defined within the exception class, it
/// will be consistent across all `raise` invocations.
///
/// This rule is not enforced for some built-in exceptions that are commonly
/// raised with a message and would be unusual to subclass, such as
/// `NotImplementedError`.
///
/// ## Example
/// ```python
/// class CantBeNegative(Exception):
/// pass
///
///
/// def foo(x):
/// if x < 0:
/// raise CantBeNegative(f"{x} is negative")
/// ```
///
/// Use instead:
/// ```python
/// class CantBeNegative(Exception):
/// def __init__(self, number):
/// super().__init__(f"{number} is negative")
///
///
/// def foo(x):
/// if x < 0:
/// raise CantBeNegative(x)
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.236")]
pub(crate) struct RaiseVanillaArgs;
impl Violation for RaiseVanillaArgs {
#[derive_message_formats]
fn message(&self) -> String {
"Avoid specifying long messages outside the exception class".to_string()
}
}
/// TRY003
pub(crate) fn raise_vanilla_args(checker: &Checker, expr: &Expr) {
let Expr::Call(ast::ExprCall {
func,
arguments: Arguments { args, .. },
..
}) = expr
else {
return;
};
let Some(arg) = args.first() else {
return;
};
// Ignore some built-in exceptions that don't make sense to subclass, like
// `NotImplementedError`.
if checker
.semantic()
.match_builtin_expr(func, "NotImplementedError")
{
return;
}
if contains_message(arg) {
checker.report_diagnostic(RaiseVanillaArgs, expr.range());
}
}
/// Returns `true` if an expression appears to be an exception message (i.e., a string with
/// some whitespace).
fn contains_message(expr: &Expr) -> bool {
match expr {
Expr::FString(ast::ExprFString { value, .. }) => {
for f_string_part in value {
match f_string_part {
ast::FStringPart::Literal(literal) => {
if literal.chars().any(char::is_whitespace) {
return true;
}
}
ast::FStringPart::FString(f_string) => {
for literal in f_string.elements.literals() {
if literal.chars().any(char::is_whitespace) {
return true;
}
}
}
}
}
}
Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => {
if value.chars().any(char::is_whitespace) {
return true;
}
}
_ => {}
}
false
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/reraise_no_cause.rs | crates/ruff_linter/src/rules/tryceratops/rules/reraise_no_cause.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::Violation;
/// ## Removed
/// This rule is identical to [B904] which should be used instead.
///
/// ## What it does
/// Checks for exceptions that are re-raised without specifying the cause via
/// the `from` keyword.
///
/// ## Why is this bad?
/// The `from` keyword sets the `__cause__` attribute of the exception, which
/// stores the "cause" of the exception. The availability of an exception
/// "cause" is useful for debugging.
///
/// ## Example
/// ```python
/// def reciprocal(n):
/// try:
/// return 1 / n
/// except ZeroDivisionError:
/// raise ValueError()
/// ```
///
/// Use instead:
/// ```python
/// def reciprocal(n):
/// try:
/// return 1 / n
/// except ZeroDivisionError as exc:
/// raise ValueError() from exc
/// ```
///
/// ## References
/// - [Python documentation: Exception context](https://docs.python.org/3/library/exceptions.html#exception-context)
///
/// [B904]: https://docs.astral.sh/ruff/rules/raise-without-from-inside-except/
#[derive(ViolationMetadata)]
#[violation_metadata(removed_since = "v0.2.0")]
pub(crate) struct ReraiseNoCause;
/// TRY200
impl Violation for ReraiseNoCause {
#[derive_message_formats]
fn message(&self) -> String {
"Use `raise from` to specify exception cause".to_string()
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/useless_try_except.rs | crates/ruff_linter/src/rules/tryceratops/rules/useless_try_except.rs | use ruff_python_ast::{self as ast, ExceptHandler, ExceptHandlerExceptHandler, Expr, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for immediate uses of `raise` within exception handlers.
///
/// ## Why is this bad?
/// Capturing an exception, only to immediately reraise it, has no effect.
/// Instead, remove the error-handling code and let the exception propagate
/// upwards without the unnecessary `try`-`except` block.
///
/// ## Example
/// ```python
/// def foo():
/// try:
/// bar()
/// except NotImplementedError:
/// raise
/// ```
///
/// Use instead:
/// ```python
/// def foo():
/// bar()
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.7.0")]
pub(crate) struct UselessTryExcept;
impl Violation for UselessTryExcept {
#[derive_message_formats]
fn message(&self) -> String {
"Remove exception handler; error is immediately re-raised".to_string()
}
}
/// TRY203 (previously TRY302)
pub(crate) fn useless_try_except(checker: &Checker, handlers: &[ExceptHandler]) {
if handlers.iter().all(|handler| {
let ExceptHandler::ExceptHandler(ExceptHandlerExceptHandler { name, body, .. }) = handler;
let Some(Stmt::Raise(ast::StmtRaise {
exc, cause: None, ..
})) = &body.first()
else {
return false;
};
if let Some(expr) = exc {
// E.g., `except ... as e: raise e`
if let Expr::Name(ast::ExprName { id, .. }) = expr.as_ref() {
if name.as_ref().is_some_and(|name| name.as_str() == id) {
return true;
}
}
false
} else {
// E.g., `except ...: raise`
true
}
}) {
// Require that all handlers are useless, but create one diagnostic per handler.
for handler in handlers {
checker.report_diagnostic(UselessTryExcept, handler.range());
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/verbose_raise.rs | crates/ruff_linter/src/rules/tryceratops/rules/verbose_raise.rs | use ruff_python_ast::{self as ast, ExceptHandler, Expr, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for needless exception names in `raise` statements.
///
/// ## Why is this bad?
/// It's redundant to specify the exception name in a `raise` statement if the
/// exception is being re-raised.
///
/// ## Example
/// ```python
/// def foo():
/// try:
/// ...
/// except ValueError as exc:
/// raise exc
/// ```
///
/// Use instead:
/// ```python
/// def foo():
/// try:
/// ...
/// except ValueError:
/// raise
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it doesn't properly handle bound
/// exceptions that are shadowed between the `except` and `raise` statements.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct VerboseRaise;
impl AlwaysFixableViolation for VerboseRaise {
#[derive_message_formats]
fn message(&self) -> String {
"Use `raise` without specifying exception name".to_string()
}
fn fix_title(&self) -> String {
"Remove exception name".to_string()
}
}
/// TRY201
pub(crate) fn verbose_raise(checker: &Checker, handlers: &[ExceptHandler]) {
for handler in handlers {
// If the handler assigned a name to the exception...
if let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler {
name: Some(exception_name),
body,
..
}) = handler
{
let raises = {
let mut visitor = RaiseStatementVisitor::default();
visitor.visit_body(body);
visitor.raises
};
for raise in raises {
if raise.cause.is_some() {
continue;
}
if let Some(exc) = raise.exc.as_ref() {
// ...and the raised object is bound to the same name...
if let Expr::Name(ast::ExprName { id, .. }) = exc.as_ref() {
if id == exception_name.as_str() {
let mut diagnostic =
checker.report_diagnostic(VerboseRaise, exc.range());
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
"raise".to_string(),
raise.range(),
)));
}
}
}
}
}
}
}
#[derive(Default)]
struct RaiseStatementVisitor<'a> {
raises: Vec<&'a ast::StmtRaise>,
}
impl<'a> StatementVisitor<'a> for RaiseStatementVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt {
Stmt::Raise(raise @ ast::StmtRaise { .. }) => {
self.raises.push(raise);
}
Stmt::Try(ast::StmtTry {
body, finalbody, ..
}) => {
for stmt in body.iter().chain(finalbody) {
walk_stmt(self, stmt);
}
}
_ => walk_stmt(self, stmt),
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/type_check_without_type_error.rs | crates/ruff_linter/src/rules/tryceratops/rules/type_check_without_type_error.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::map_callable;
use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt};
use ruff_python_ast::{self as ast, Expr, Stmt, StmtIf};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for type checks that do not raise `TypeError`.
///
/// ## Why is this bad?
/// The Python documentation states that `TypeError` should be raised upon
/// encountering an inappropriate type.
///
/// ## Example
/// ```python
/// def foo(n: int):
/// if isinstance(n, int):
/// pass
/// else:
/// raise ValueError("n must be an integer")
/// ```
///
/// Use instead:
/// ```python
/// def foo(n: int):
/// if isinstance(n, int):
/// pass
/// else:
/// raise TypeError("n must be an integer")
/// ```
///
/// ## References
/// - [Python documentation: `TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.230")]
pub(crate) struct TypeCheckWithoutTypeError;
impl Violation for TypeCheckWithoutTypeError {
#[derive_message_formats]
fn message(&self) -> String {
"Prefer `TypeError` exception for invalid type".to_string()
}
}
#[derive(Default)]
struct ControlFlowVisitor<'a> {
returns: Vec<&'a Stmt>,
breaks: Vec<&'a Stmt>,
continues: Vec<&'a Stmt>,
}
impl<'a> StatementVisitor<'a> for ControlFlowVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt {
Stmt::FunctionDef(_) | Stmt::ClassDef(_) => {
// Don't recurse.
}
Stmt::Return(_) => self.returns.push(stmt),
Stmt::Break(_) => self.breaks.push(stmt),
Stmt::Continue(_) => self.continues.push(stmt),
_ => walk_stmt(self, stmt),
}
}
}
/// Returns `true` if a [`Stmt`] contains a `return`, `break`, or `continue`.
fn has_control_flow(stmt: &Stmt) -> bool {
let mut visitor = ControlFlowVisitor::default();
visitor.visit_stmt(stmt);
!visitor.returns.is_empty() || !visitor.breaks.is_empty() || !visitor.continues.is_empty()
}
/// Returns `true` if an [`Expr`] is a call to check types.
fn check_type_check_call(semantic: &SemanticModel, call: &Expr) -> bool {
semantic
.resolve_builtin_symbol(call)
.is_some_and(|builtin| matches!(builtin, "isinstance" | "issubclass" | "callable"))
}
/// Returns `true` if an [`Expr`] is a test to check types (e.g. via isinstance)
fn check_type_check_test(semantic: &SemanticModel, test: &Expr) -> bool {
match test {
Expr::BoolOp(ast::ExprBoolOp { values, .. }) => values
.iter()
.all(|expr| check_type_check_test(semantic, expr)),
Expr::UnaryOp(ast::ExprUnaryOp { operand, .. }) => check_type_check_test(semantic, operand),
Expr::Call(ast::ExprCall { func, .. }) => check_type_check_call(semantic, func),
_ => false,
}
}
fn check_raise(checker: &Checker, exc: &Expr, item: &Stmt) {
if is_builtin_exception(exc, checker.semantic()) {
checker.report_diagnostic(TypeCheckWithoutTypeError, item.range());
}
}
/// Search the body of an if-condition for raises.
fn check_body(checker: &Checker, body: &[Stmt]) {
for item in body {
if has_control_flow(item) {
return;
}
if let Stmt::Raise(ast::StmtRaise { exc: Some(exc), .. }) = &item {
check_raise(checker, exc, item);
}
}
}
/// Returns `true` if the given expression is a builtin exception.
///
/// This function only matches to a subset of the builtin exceptions, and omits `TypeError`.
fn is_builtin_exception(expr: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(map_callable(expr))
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
[
"",
"ArithmeticError"
| "AssertionError"
| "AttributeError"
| "BufferError"
| "EOFError"
| "Exception"
| "ImportError"
| "LookupError"
| "MemoryError"
| "NameError"
| "ReferenceError"
| "RuntimeError"
| "SyntaxError"
| "SystemError"
| "ValueError"
]
)
})
}
/// TRY004
pub(crate) fn type_check_without_type_error(
checker: &Checker,
stmt_if: &StmtIf,
parent: Option<&Stmt>,
) {
let StmtIf {
body,
test,
elif_else_clauses,
..
} = stmt_if;
if let Some(Stmt::If(ast::StmtIf { test, .. })) = parent {
if !check_type_check_test(checker.semantic(), test) {
return;
}
}
// Only consider the body when the `if` condition is all type-related
if !check_type_check_test(checker.semantic(), test) {
return;
}
check_body(checker, body);
for clause in elif_else_clauses {
if let Some(test) = &clause.test {
// If there are any `elif`, they must all also be type-related
if !check_type_check_test(checker.semantic(), test) {
return;
}
}
// The `elif` or `else` body raises the wrong exception
check_body(checker, &clause.body);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/mod.rs | crates/ruff_linter/src/rules/tryceratops/rules/mod.rs | pub(crate) use error_instead_of_exception::*;
pub(crate) use raise_vanilla_args::*;
pub(crate) use raise_vanilla_class::*;
pub(crate) use raise_within_try::*;
pub(crate) use reraise_no_cause::*;
pub(crate) use try_consider_else::*;
pub(crate) use type_check_without_type_error::*;
pub(crate) use useless_try_except::*;
pub(crate) use verbose_log_message::*;
pub(crate) use verbose_raise::*;
mod error_instead_of_exception;
mod raise_vanilla_args;
mod raise_vanilla_class;
mod raise_within_try;
mod reraise_no_cause;
mod try_consider_else;
mod type_check_without_type_error;
mod useless_try_except;
mod verbose_log_message;
mod verbose_raise;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/error_instead_of_exception.rs | crates/ruff_linter/src/rules/tryceratops/rules/error_instead_of_exception.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{self as ast, ExceptHandler, Expr};
use ruff_python_semantic::analyze::logging::exc_info;
use ruff_python_stdlib::logging::LoggingLevel;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::rules::tryceratops::helpers::LoggerCandidateVisitor;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `logging.error` instead of `logging.exception` when
/// logging an exception.
///
/// ## Why is this bad?
/// `logging.exception` logs the exception and the traceback, while
/// `logging.error` only logs the exception. The former is more appropriate
/// when logging an exception, as the traceback is often useful for debugging.
///
/// ## Example
/// ```python
/// import logging
///
///
/// def func():
/// try:
/// raise NotImplementedError
/// except NotImplementedError:
/// logging.error("Exception occurred")
/// ```
///
/// Use instead:
/// ```python
/// import logging
///
///
/// def func():
/// try:
/// raise NotImplementedError
/// except NotImplementedError:
/// logging.exception("Exception occurred")
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as safe when run against `logging.error` calls,
/// but unsafe when marked against other logger-like calls (e.g.,
/// `logger.error`), since the rule is prone to false positives when detecting
/// logger-like calls outside of the `logging` module.
///
/// ## Options
///
/// - `lint.logger-objects`
///
/// ## References
/// - [Python documentation: `logging.exception`](https://docs.python.org/3/library/logging.html#logging.exception)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.236")]
pub(crate) struct ErrorInsteadOfException;
impl Violation for ErrorInsteadOfException {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use `logging.exception` instead of `logging.error`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `exception`".to_string())
}
}
/// TRY400
pub(crate) fn error_instead_of_exception(checker: &Checker, handlers: &[ExceptHandler]) {
for handler in handlers {
let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) = handler;
let calls = {
let mut visitor =
LoggerCandidateVisitor::new(checker.semantic(), &checker.settings().logger_objects);
visitor.visit_body(body);
visitor.calls
};
for (expr, logging_level) in calls {
if matches!(logging_level, LoggingLevel::Error) {
if exc_info(&expr.arguments, checker.semantic()).is_none() {
let mut diagnostic =
checker.report_diagnostic(ErrorInsteadOfException, expr.range());
match expr.func.as_ref() {
Expr::Attribute(ast::ExprAttribute { attr, .. }) => {
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement("exception".to_string(), attr.range()),
// When run against `logging.error`, the fix is safe; otherwise,
// the object _may_ not be a logger.
if checker
.semantic()
.resolve_qualified_name(expr.func.as_ref())
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["logging", "error"])
})
{
Applicability::Safe
} else {
Applicability::Unsafe
},
));
}
Expr::Name(_) => {
diagnostic.try_set_fix(|| {
let (import_edit, binding) =
checker.importer().get_or_import_symbol(
&ImportRequest::import("logging", "exception"),
expr.start(),
checker.semantic(),
)?;
let name_edit = Edit::range_replacement(binding, expr.func.range());
Ok(Fix::applicable_edits(
import_edit,
[name_edit],
// When run against `logging.error`, the fix is safe; otherwise,
// the object _may_ not be a logger.
if checker
.semantic()
.resolve_qualified_name(expr.func.as_ref())
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["logging", "error"]
)
})
{
Applicability::Safe
} else {
Applicability::Unsafe
},
))
});
}
_ => {}
}
}
}
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_class.rs | crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_class.rs | use ruff_python_ast::Expr;
use ruff_python_ast::helpers::map_callable;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for code that raises `Exception` or `BaseException` directly.
///
/// ## Why is this bad?
/// Handling such exceptions requires the use of `except Exception` or
/// `except BaseException`. These will capture almost _any_ raised exception,
/// including failed assertions, division by zero, and more.
///
/// Prefer to raise your own exception, or a more specific built-in
/// exception, so that you can avoid over-capturing exceptions that you
/// don't intend to handle.
///
/// ## Example
/// ```python
/// def main_function():
/// if not cond:
/// raise Exception()
///
///
/// def consumer_func():
/// try:
/// do_step()
/// prepare()
/// main_function()
/// except Exception:
/// logger.error("Oops")
/// ```
///
/// Use instead:
/// ```python
/// def main_function():
/// if not cond:
/// raise CustomException()
///
///
/// def consumer_func():
/// try:
/// do_step()
/// prepare()
/// main_function()
/// except CustomException:
/// logger.error("Main function failed")
/// except Exception:
/// logger.error("Oops")
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.236")]
pub(crate) struct RaiseVanillaClass;
impl Violation for RaiseVanillaClass {
#[derive_message_formats]
fn message(&self) -> String {
"Create your own exception".to_string()
}
}
/// TRY002
pub(crate) fn raise_vanilla_class(checker: &Checker, expr: &Expr) {
if checker
.semantic()
.resolve_qualified_name(map_callable(expr))
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["" | "builtins", "Exception" | "BaseException"]
)
})
{
checker.report_diagnostic(RaiseVanillaClass, expr.range());
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs | crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs | use ruff_python_ast::{self as ast, ExceptHandler, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::contains_effect;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for `return` statements in `try` blocks.
///
/// ## Why is this bad?
/// The `try`-`except` statement has an `else` clause for code that should
/// run _only_ if no exceptions were raised. Returns in `try` blocks may
/// exhibit confusing or unwanted behavior, such as being overridden by
/// control flow in `except` and `finally` blocks, or unintentionally
/// suppressing an exception.
///
/// ## Example
/// ```python
/// import logging
///
///
/// def reciprocal(n):
/// try:
/// rec = 1 / n
/// print(f"reciprocal of {n} is {rec}")
/// return rec
/// except ZeroDivisionError:
/// logging.exception("Exception occurred")
/// raise
/// ```
///
/// Use instead:
/// ```python
/// import logging
///
///
/// def reciprocal(n):
/// try:
/// rec = 1 / n
/// except ZeroDivisionError:
/// logging.exception("Exception occurred")
/// raise
/// else:
/// print(f"reciprocal of {n} is {rec}")
/// return rec
/// ```
///
/// ## References
/// - [Python documentation: Errors and Exceptions](https://docs.python.org/3/tutorial/errors.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.229")]
pub(crate) struct TryConsiderElse;
impl Violation for TryConsiderElse {
#[derive_message_formats]
fn message(&self) -> String {
"Consider moving this statement to an `else` block".to_string()
}
}
/// TRY300
pub(crate) fn try_consider_else(
checker: &Checker,
body: &[Stmt],
orelse: &[Stmt],
handler: &[ExceptHandler],
) {
if body.len() > 1 && orelse.is_empty() && !handler.is_empty() {
if let Some(stmt) = body.last() {
if let Stmt::Return(ast::StmtReturn {
value,
range: _,
node_index: _,
}) = stmt
{
if let Some(value) = value {
if contains_effect(value, |id| checker.semantic().has_builtin_binding(id)) {
return;
}
}
checker.report_diagnostic(TryConsiderElse, stmt.range());
}
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/tryceratops/rules/raise_within_try.rs | crates/ruff_linter/src/rules/tryceratops/rules/raise_within_try.rs | use ruff_python_ast::{self as ast, ExceptHandler, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{
comparable::ComparableExpr,
helpers::{self, map_callable},
statement_visitor::{StatementVisitor, walk_stmt},
};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for `raise` statements within `try` blocks. The only `raise`s
/// caught are those that throw exceptions caught by the `try` statement itself.
///
/// ## Why is this bad?
/// Raising and catching exceptions within the same `try` block is redundant,
/// as the code can be refactored to avoid the `try` block entirely.
///
/// Alternatively, the `raise` can be moved within an inner function, making
/// the exception reusable across multiple call sites.
///
/// ## Example
/// ```python
/// def bar():
/// pass
///
///
/// def foo():
/// try:
/// a = bar()
/// if not a:
/// raise ValueError
/// except ValueError:
/// raise
/// ```
///
/// Use instead:
/// ```python
/// def bar():
/// raise ValueError
///
///
/// def foo():
/// try:
/// a = bar() # refactored `bar` to raise `ValueError`
/// except ValueError:
/// raise
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.233")]
pub(crate) struct RaiseWithinTry;
impl Violation for RaiseWithinTry {
#[derive_message_formats]
fn message(&self) -> String {
"Abstract `raise` to an inner function".to_string()
}
}
#[derive(Default)]
struct RaiseStatementVisitor<'a> {
raises: Vec<&'a Stmt>,
}
impl<'a> StatementVisitor<'a> for RaiseStatementVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt {
Stmt::Raise(_) => self.raises.push(stmt),
Stmt::Try(_) => (),
_ => walk_stmt(self, stmt),
}
}
}
/// TRY301
pub(crate) fn raise_within_try(checker: &Checker, body: &[Stmt], handlers: &[ExceptHandler]) {
if handlers.is_empty() {
return;
}
let raises = {
let mut visitor = RaiseStatementVisitor::default();
visitor.visit_body(body);
visitor.raises
};
if raises.is_empty() {
return;
}
let handled_exceptions = helpers::extract_handled_exceptions(handlers);
let comparables: Vec<ComparableExpr> = handled_exceptions
.iter()
.map(|handler| ComparableExpr::from(*handler))
.collect();
for stmt in raises {
let Stmt::Raise(ast::StmtRaise {
exc: Some(exception),
..
}) = stmt
else {
continue;
};
// We can't check exception sub-classes without a type-checker implementation, so let's
// just catch the blanket `Exception` for now.
if comparables.contains(&ComparableExpr::from(map_callable(exception)))
|| handled_exceptions.iter().any(|expr| {
checker
.semantic()
.resolve_builtin_symbol(expr)
.is_some_and(|builtin| matches!(builtin, "Exception" | "BaseException"))
})
{
checker.report_diagnostic(RaiseWithinTry, stmt.range());
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_slots/helpers.rs | crates/ruff_linter/src/rules/flake8_slots/helpers.rs | use ruff_python_ast::{self as ast, Expr, Stmt};
/// Return `true` if the given body contains a `__slots__` assignment.
pub(super) fn has_slots(body: &[Stmt]) -> bool {
for stmt in body {
match stmt {
Stmt::Assign(ast::StmtAssign { targets, .. }) => {
for target in targets {
if let Expr::Name(ast::ExprName { id, .. }) = target {
if id.as_str() == "__slots__" {
return true;
}
}
}
}
Stmt::AnnAssign(ast::StmtAnnAssign { target, .. }) => {
if let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() {
if id.as_str() == "__slots__" {
return true;
}
}
}
_ => {}
}
}
false
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_slots/mod.rs | crates/ruff_linter/src/rules/flake8_slots/mod.rs | //! Rules from [flake8-slots](https://pypi.org/project/flake8-slots/).
mod helpers;
pub(crate) mod rules;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test_case(Rule::NoSlotsInStrSubclass, Path::new("SLOT000.py"))]
#[test_case(Rule::NoSlotsInTupleSubclass, Path::new("SLOT001.py"))]
#[test_case(Rule::NoSlotsInNamedtupleSubclass, Path::new("SLOT002.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("flake8_slots").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_tuple_subclass.rs | crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_tuple_subclass.rs | use ruff_python_ast::{Arguments, Stmt, StmtClassDef};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::map_subscript;
use ruff_python_ast::identifier::Identifier;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_slots::helpers::has_slots;
/// ## What it does
/// Checks for subclasses of `tuple` that lack a `__slots__` definition.
///
/// ## Why is this bad?
/// In Python, the `__slots__` attribute allows you to explicitly define the
/// attributes (instance variables) that a class can have. By default, Python
/// uses a dictionary to store an object's attributes, which incurs some memory
/// overhead. However, when `__slots__` is defined, Python uses a more compact
/// internal structure to store the object's attributes, resulting in memory
/// savings.
///
/// Subclasses of `tuple` inherit all the attributes and methods of the
/// built-in `tuple` class. Since tuples are typically immutable, they don't
/// require additional attributes beyond what the `tuple` class provides.
/// Defining `__slots__` for subclasses of `tuple` prevents the creation of a
/// dictionary for each instance, reducing memory consumption.
///
/// ## Example
/// ```python
/// class Foo(tuple):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// class Foo(tuple):
/// __slots__ = ()
/// ```
///
/// ## References
/// - [Python documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.273")]
pub(crate) struct NoSlotsInTupleSubclass;
impl Violation for NoSlotsInTupleSubclass {
#[derive_message_formats]
fn message(&self) -> String {
"Subclasses of `tuple` should define `__slots__`".to_string()
}
}
/// SLOT001
pub(crate) fn no_slots_in_tuple_subclass(checker: &Checker, stmt: &Stmt, class: &StmtClassDef) {
// https://github.com/astral-sh/ruff/issues/14535
if checker.source_type.is_stub() {
return;
}
let Some(Arguments { args: bases, .. }) = class.arguments.as_deref() else {
return;
};
let semantic = checker.semantic();
if bases.iter().any(|base| {
let base = map_subscript(base);
semantic.match_builtin_expr(base, "tuple") || semantic.match_typing_expr(base, "Tuple")
}) {
if !has_slots(&class.body) {
checker.report_diagnostic(NoSlotsInTupleSubclass, stmt.identifier());
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_str_subclass.rs | crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_str_subclass.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::{Arguments, Expr, Stmt, StmtClassDef};
use ruff_python_semantic::{SemanticModel, analyze::class::is_enumeration};
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_slots::helpers::has_slots;
/// ## What it does
/// Checks for subclasses of `str` that lack a `__slots__` definition.
///
/// ## Why is this bad?
/// In Python, the `__slots__` attribute allows you to explicitly define the
/// attributes (instance variables) that a class can have. By default, Python
/// uses a dictionary to store an object's attributes, which incurs some memory
/// overhead. However, when `__slots__` is defined, Python uses a more compact
/// internal structure to store the object's attributes, resulting in memory
/// savings.
///
/// Subclasses of `str` inherit all the attributes and methods of the built-in
/// `str` class. Since strings are typically immutable, they don't require
/// additional attributes beyond what the `str` class provides. Defining
/// `__slots__` for subclasses of `str` prevents the creation of a dictionary
/// for each instance, reducing memory consumption.
///
/// ## Example
/// ```python
/// class Foo(str):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// class Foo(str):
/// __slots__ = ()
/// ```
///
/// ## References
/// - [Python documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.273")]
pub(crate) struct NoSlotsInStrSubclass;
impl Violation for NoSlotsInStrSubclass {
#[derive_message_formats]
fn message(&self) -> String {
"Subclasses of `str` should define `__slots__`".to_string()
}
}
/// SLOT000
pub(crate) fn no_slots_in_str_subclass(checker: &Checker, stmt: &Stmt, class: &StmtClassDef) {
// https://github.com/astral-sh/ruff/issues/14535
if checker.source_type.is_stub() {
return;
}
let Some(Arguments { args: bases, .. }) = class.arguments.as_deref() else {
return;
};
let semantic = checker.semantic();
if !is_str_subclass(bases, semantic) {
return;
}
// Ignore subclasses of `enum.Enum` et al.
if is_enumeration(class, semantic) {
return;
}
if has_slots(&class.body) {
return;
}
checker.report_diagnostic(NoSlotsInStrSubclass, stmt.identifier());
}
/// Return `true` if the class is a subclass of `str`.
fn is_str_subclass(bases: &[Expr], semantic: &SemanticModel) -> bool {
bases
.iter()
.any(|base| semantic.match_builtin_expr(base, "str"))
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_namedtuple_subclass.rs | crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_namedtuple_subclass.rs | use std::fmt;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Arguments, Expr, Stmt, StmtClassDef, identifier::Identifier};
use ruff_python_semantic::SemanticModel;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_slots::helpers::has_slots;
/// ## What it does
/// Checks for subclasses of `collections.namedtuple` or `typing.NamedTuple`
/// that lack a `__slots__` definition.
///
/// ## Why is this bad?
/// In Python, the `__slots__` attribute allows you to explicitly define the
/// attributes (instance variables) that a class can have. By default, Python
/// uses a dictionary to store an object's attributes, which incurs some memory
/// overhead. However, when `__slots__` is defined, Python uses a more compact
/// internal structure to store the object's attributes, resulting in memory
/// savings.
///
/// Subclasses of `namedtuple` inherit all the attributes and methods of the
/// built-in `namedtuple` class. Since tuples are typically immutable, they
/// don't require additional attributes beyond what the `namedtuple` class
/// provides. Defining `__slots__` for subclasses of `namedtuple` prevents the
/// creation of a dictionary for each instance, reducing memory consumption.
///
/// ## Example
/// ```python
/// from collections import namedtuple
///
///
/// class Foo(namedtuple("foo", ["str", "int"])):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// from collections import namedtuple
///
///
/// class Foo(namedtuple("foo", ["str", "int"])):
/// __slots__ = ()
/// ```
///
/// ## References
/// - [Python documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.273")]
pub(crate) struct NoSlotsInNamedtupleSubclass(NamedTupleKind);
impl Violation for NoSlotsInNamedtupleSubclass {
#[derive_message_formats]
fn message(&self) -> String {
let NoSlotsInNamedtupleSubclass(namedtuple_kind) = self;
format!("Subclasses of {namedtuple_kind} should define `__slots__`")
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum NamedTupleKind {
Collections,
Typing,
}
impl fmt::Display for NamedTupleKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Collections => "`collections.namedtuple()`",
Self::Typing => "call-based `typing.NamedTuple()`",
})
}
}
/// SLOT002
pub(crate) fn no_slots_in_namedtuple_subclass(
checker: &Checker,
stmt: &Stmt,
class: &StmtClassDef,
) {
// https://github.com/astral-sh/ruff/issues/14535
if checker.source_type.is_stub() {
return;
}
let Some(Arguments { args: bases, .. }) = class.arguments.as_deref() else {
return;
};
if let Some(namedtuple_kind) = namedtuple_base(bases, checker.semantic()) {
if !has_slots(&class.body) {
checker.report_diagnostic(
NoSlotsInNamedtupleSubclass(namedtuple_kind),
stmt.identifier(),
);
}
}
}
/// If the class's bases consist solely of named tuples, return the kind of named tuple
/// (either `collections.namedtuple()`, or `typing.NamedTuple()`). Otherwise, return `None`.
fn namedtuple_base(bases: &[Expr], semantic: &SemanticModel) -> Option<NamedTupleKind> {
let mut kind = None;
for base in bases {
if let Expr::Call(ast::ExprCall { func, .. }) = base {
// Ex) `collections.namedtuple()`
let qualified_name = semantic.resolve_qualified_name(func)?;
match qualified_name.segments() {
["collections", "namedtuple"] => kind = kind.or(Some(NamedTupleKind::Collections)),
["typing", "NamedTuple"] => kind = kind.or(Some(NamedTupleKind::Typing)),
// Ex) `enum.Enum`
_ => return None,
}
} else if !semantic.match_builtin_expr(base, "object") {
// Allow inheriting from `object`.
return None;
}
}
kind
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_slots/rules/mod.rs | crates/ruff_linter/src/rules/flake8_slots/rules/mod.rs | pub(crate) use no_slots_in_namedtuple_subclass::*;
pub(crate) use no_slots_in_str_subclass::*;
pub(crate) use no_slots_in_tuple_subclass::*;
mod no_slots_in_namedtuple_subclass;
mod no_slots_in_str_subclass;
mod no_slots_in_tuple_subclass;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_unused_arguments/settings.rs | crates/ruff_linter/src/rules/flake8_unused_arguments/settings.rs | //! Settings for the `flake8-unused-arguments` plugin.
use crate::display_settings;
use ruff_macros::CacheKey;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, Default, CacheKey)]
pub struct Settings {
pub ignore_variadic_names: bool,
}
impl Display for Settings {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.flake8_unused_arguments",
fields = [
self.ignore_variadic_names
]
}
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_unused_arguments/mod.rs | crates/ruff_linter/src/rules/flake8_unused_arguments/mod.rs | //! Rules from [flake8-unused-arguments](https://pypi.org/project/flake8-unused-arguments/).
pub(crate) mod rules;
pub mod settings;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test_case(Rule::UnusedFunctionArgument, Path::new("ARG.py"))]
#[test_case(Rule::UnusedMethodArgument, Path::new("ARG.py"))]
#[test_case(Rule::UnusedClassMethodArgument, Path::new("ARG.py"))]
#[test_case(Rule::UnusedStaticMethodArgument, Path::new("ARG.py"))]
#[test_case(Rule::UnusedLambdaArgument, Path::new("ARG.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("flake8_unused_arguments").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test]
fn ignore_variadic_names() -> Result<()> {
let diagnostics = test_path(
Path::new("flake8_unused_arguments/ignore_variadic_names.py"),
&settings::LinterSettings {
flake8_unused_arguments: super::settings::Settings {
ignore_variadic_names: true,
},
..settings::LinterSettings::for_rules(vec![
Rule::UnusedFunctionArgument,
Rule::UnusedMethodArgument,
Rule::UnusedClassMethodArgument,
Rule::UnusedStaticMethodArgument,
Rule::UnusedLambdaArgument,
])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn enforce_variadic_names() -> Result<()> {
let diagnostics = test_path(
Path::new("flake8_unused_arguments/ignore_variadic_names.py"),
&settings::LinterSettings {
flake8_unused_arguments: super::settings::Settings {
ignore_variadic_names: false,
},
..settings::LinterSettings::for_rules(vec![
Rule::UnusedFunctionArgument,
Rule::UnusedMethodArgument,
Rule::UnusedClassMethodArgument,
Rule::UnusedStaticMethodArgument,
Rule::UnusedLambdaArgument,
])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_unused_arguments/rules/mod.rs | crates/ruff_linter/src/rules/flake8_unused_arguments/rules/mod.rs | pub(crate) use unused_arguments::*;
mod unused_arguments;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_unused_arguments/rules/unused_arguments.rs | crates/ruff_linter/src/rules/flake8_unused_arguments/rules/unused_arguments.rs | use ruff_python_ast as ast;
use ruff_python_ast::{Parameter, Parameters, Stmt, StmtExpr, StmtFunctionDef, StmtRaise};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::analyze::{function_type, visibility};
use ruff_python_semantic::{Scope, ScopeKind, SemanticModel};
use ruff_text_size::{Ranged, TextRange};
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::registry::Rule;
/// ## What it does
/// Checks for the presence of unused arguments in function definitions.
///
/// ## Why is this bad?
/// An argument that is defined but not used is likely a mistake, and should
/// be removed to avoid confusion.
///
/// If a variable is intentionally defined-but-not-used, it should be
/// prefixed with an underscore, or some other value that adheres to the
/// [`lint.dummy-variable-rgx`] pattern.
///
/// ## Example
/// ```python
/// def foo(bar, baz):
/// return bar * 2
/// ```
///
/// Use instead:
/// ```python
/// def foo(bar):
/// return bar * 2
/// ```
///
/// ## Options
/// - `lint.dummy-variable-rgx`
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.168")]
pub(crate) struct UnusedFunctionArgument {
name: String,
}
impl Violation for UnusedFunctionArgument {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedFunctionArgument { name } = self;
format!("Unused function argument: `{name}`")
}
}
/// ## What it does
/// Checks for the presence of unused arguments in instance method definitions.
///
/// ## Why is this bad?
/// An argument that is defined but not used is likely a mistake, and should
/// be removed to avoid confusion.
///
/// If a variable is intentionally defined-but-not-used, it should be
/// prefixed with an underscore, or some other value that adheres to the
/// [`lint.dummy-variable-rgx`] pattern.
///
/// This rule exempts methods decorated with [`@typing.override`][override].
/// Removing a parameter from a subclass method (or changing a parameter's
/// name) may cause type checkers to complain about a violation of the Liskov
/// Substitution Principle if it means that the method now incompatibly
/// overrides a method defined on a superclass. Explicitly decorating an
/// overriding method with `@override` signals to Ruff that the method is
/// intended to override a superclass method and that a type checker will
/// enforce that it does so; Ruff therefore knows that it should not enforce
/// rules about unused arguments on such methods.
///
/// ## Example
/// ```python
/// class Class:
/// def foo(self, arg1, arg2):
/// print(arg1)
/// ```
///
/// Use instead:
/// ```python
/// class Class:
/// def foo(self, arg1):
/// print(arg1)
/// ```
///
/// ## Options
/// - `lint.dummy-variable-rgx`
///
/// [override]: https://docs.python.org/3/library/typing.html#typing.override
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.168")]
pub(crate) struct UnusedMethodArgument {
name: String,
}
impl Violation for UnusedMethodArgument {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedMethodArgument { name } = self;
format!("Unused method argument: `{name}`")
}
}
/// ## What it does
/// Checks for the presence of unused arguments in class method definitions.
///
/// ## Why is this bad?
/// An argument that is defined but not used is likely a mistake, and should
/// be removed to avoid confusion.
///
/// If a variable is intentionally defined-but-not-used, it should be
/// prefixed with an underscore, or some other value that adheres to the
/// [`lint.dummy-variable-rgx`] pattern.
///
/// This rule exempts methods decorated with [`@typing.override`][override].
/// Removing a parameter from a subclass method (or changing a parameter's
/// name) may cause type checkers to complain about a violation of the Liskov
/// Substitution Principle if it means that the method now incompatibly
/// overrides a method defined on a superclass. Explicitly decorating an
/// overriding method with `@override` signals to Ruff that the method is
/// intended to override a superclass method and that a type checker will
/// enforce that it does so; Ruff therefore knows that it should not enforce
/// rules about unused arguments on such methods.
///
/// ## Example
/// ```python
/// class Class:
/// @classmethod
/// def foo(cls, arg1, arg2):
/// print(arg1)
/// ```
///
/// Use instead:
/// ```python
/// class Class:
/// @classmethod
/// def foo(cls, arg1):
/// print(arg1)
/// ```
///
/// ## Options
/// - `lint.dummy-variable-rgx`
///
/// [override]: https://docs.python.org/3/library/typing.html#typing.override
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.168")]
pub(crate) struct UnusedClassMethodArgument {
name: String,
}
impl Violation for UnusedClassMethodArgument {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedClassMethodArgument { name } = self;
format!("Unused class method argument: `{name}`")
}
}
/// ## What it does
/// Checks for the presence of unused arguments in static method definitions.
///
/// ## Why is this bad?
/// An argument that is defined but not used is likely a mistake, and should
/// be removed to avoid confusion.
///
/// If a variable is intentionally defined-but-not-used, it should be
/// prefixed with an underscore, or some other value that adheres to the
/// [`lint.dummy-variable-rgx`] pattern.
///
/// This rule exempts methods decorated with [`@typing.override`][override].
/// Removing a parameter from a subclass method (or changing a parameter's
/// name) may cause type checkers to complain about a violation of the Liskov
/// Substitution Principle if it means that the method now incompatibly
/// overrides a method defined on a superclass. Explicitly decorating an
/// overriding method with `@override` signals to Ruff that the method is
/// intended to override a superclass method, and that a type checker will
/// enforce that it does so; Ruff therefore knows that it should not enforce
/// rules about unused arguments on such methods.
///
/// ## Example
/// ```python
/// class Class:
/// @staticmethod
/// def foo(arg1, arg2):
/// print(arg1)
/// ```
///
/// Use instead:
/// ```python
/// class Class:
/// @staticmethod
/// def foo(arg1):
/// print(arg1)
/// ```
///
/// ## Options
/// - `lint.dummy-variable-rgx`
///
/// [override]: https://docs.python.org/3/library/typing.html#typing.override
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.168")]
pub(crate) struct UnusedStaticMethodArgument {
name: String,
}
impl Violation for UnusedStaticMethodArgument {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedStaticMethodArgument { name } = self;
format!("Unused static method argument: `{name}`")
}
}
/// ## What it does
/// Checks for the presence of unused arguments in lambda expression
/// definitions.
///
/// ## Why is this bad?
/// An argument that is defined but not used is likely a mistake, and should
/// be removed to avoid confusion.
///
/// If a variable is intentionally defined-but-not-used, it should be
/// prefixed with an underscore, or some other value that adheres to the
/// [`lint.dummy-variable-rgx`] pattern.
///
/// ## Example
/// ```python
/// my_list = [1, 2, 3, 4, 5]
/// squares = map(lambda x, y: x**2, my_list)
/// ```
///
/// Use instead:
/// ```python
/// my_list = [1, 2, 3, 4, 5]
/// squares = map(lambda x: x**2, my_list)
/// ```
///
/// ## Options
/// - `lint.dummy-variable-rgx`
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.168")]
pub(crate) struct UnusedLambdaArgument {
name: String,
}
impl Violation for UnusedLambdaArgument {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedLambdaArgument { name } = self;
format!("Unused lambda argument: `{name}`")
}
}
/// An AST node that can contain arguments.
#[derive(Debug, Copy, Clone)]
enum Argumentable {
Function,
Method,
ClassMethod,
StaticMethod,
Lambda,
}
impl Argumentable {
fn check_for(self, checker: &Checker, name: String, range: TextRange) {
let mut diagnostic = match self {
Self::Function => checker.report_diagnostic(UnusedFunctionArgument { name }, range),
Self::Method => checker.report_diagnostic(UnusedMethodArgument { name }, range),
Self::ClassMethod => {
checker.report_diagnostic(UnusedClassMethodArgument { name }, range)
}
Self::StaticMethod => {
checker.report_diagnostic(UnusedStaticMethodArgument { name }, range)
}
Self::Lambda => checker.report_diagnostic(UnusedLambdaArgument { name }, range),
};
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Unnecessary);
}
const fn rule_code(self) -> Rule {
match self {
Self::Function => Rule::UnusedFunctionArgument,
Self::Method => Rule::UnusedMethodArgument,
Self::ClassMethod => Rule::UnusedClassMethodArgument,
Self::StaticMethod => Rule::UnusedStaticMethodArgument,
Self::Lambda => Rule::UnusedLambdaArgument,
}
}
}
/// Check a plain function for unused arguments.
fn function(argumentable: Argumentable, parameters: &Parameters, scope: &Scope, checker: &Checker) {
let ignore_variadic_names = checker
.settings()
.flake8_unused_arguments
.ignore_variadic_names;
let args = parameters
.iter_non_variadic_params()
.map(|parameter_with_default| ¶meter_with_default.parameter)
.chain(
parameters
.vararg
.as_deref()
.into_iter()
.skip(usize::from(ignore_variadic_names)),
)
.chain(
parameters
.kwarg
.as_deref()
.into_iter()
.skip(usize::from(ignore_variadic_names)),
);
call(argumentable, args, scope, checker);
}
/// Check a method for unused arguments.
fn method(argumentable: Argumentable, parameters: &Parameters, scope: &Scope, checker: &Checker) {
let ignore_variadic_names = checker
.settings()
.flake8_unused_arguments
.ignore_variadic_names;
let args = parameters
.iter_non_variadic_params()
.skip(1)
.map(|parameter_with_default| ¶meter_with_default.parameter)
.chain(
parameters
.vararg
.as_deref()
.into_iter()
.skip(usize::from(ignore_variadic_names)),
)
.chain(
parameters
.kwarg
.as_deref()
.into_iter()
.skip(usize::from(ignore_variadic_names)),
);
call(argumentable, args, scope, checker);
}
fn call<'a>(
argumentable: Argumentable,
parameters: impl Iterator<Item = &'a Parameter>,
scope: &Scope,
checker: &Checker,
) {
let semantic = checker.semantic();
let dummy_variable_rgx = &checker.settings().dummy_variable_rgx;
for arg in parameters {
let Some(binding) = scope
.get(arg.name())
.map(|binding_id| semantic.binding(binding_id))
else {
continue;
};
if binding.kind.is_argument()
&& binding.is_unused()
&& !dummy_variable_rgx.is_match(arg.name())
{
argumentable.check_for(checker, arg.name.to_string(), binding.range());
}
}
}
/// Returns `true` if a function appears to be a base class stub. In other
/// words, if it matches the following syntax:
///
/// ```text
/// variable = <string | f-string>
/// raise NotImplementedError(variable)
/// ```
///
/// See also [`is_stub`]. We're a bit more generous in what is considered a
/// stub in this rule to avoid clashing with [`EM101`].
///
/// [`is_stub`]: function_type::is_stub
/// [`EM101`]: https://docs.astral.sh/ruff/rules/raw-string-in-exception/
pub(crate) fn is_not_implemented_stub_with_variable(
function_def: &StmtFunctionDef,
semantic: &SemanticModel,
) -> bool {
// Ignore doc-strings.
let statements = match function_def.body.as_slice() {
[Stmt::Expr(StmtExpr { value, .. }), rest @ ..] if value.is_string_literal_expr() => rest,
_ => &function_def.body,
};
let [
Stmt::Assign(ast::StmtAssign { targets, value, .. }),
Stmt::Raise(StmtRaise {
exc: Some(exception),
..
}),
] = statements
else {
return false;
};
if !matches!(**value, ast::Expr::StringLiteral(_) | ast::Expr::FString(_)) {
return false;
}
let ast::Expr::Call(ast::ExprCall {
func, arguments, ..
}) = &**exception
else {
return false;
};
if !semantic.match_builtin_expr(func, "NotImplementedError") {
return false;
}
let [argument] = &*arguments.args else {
return false;
};
let [target] = targets.as_slice() else {
return false;
};
argument.as_name_expr().map(ast::ExprName::id) == target.as_name_expr().map(ast::ExprName::id)
}
/// ARG001, ARG002, ARG003, ARG004, ARG005
pub(crate) fn unused_arguments(checker: &Checker, scope: &Scope) {
if scope.uses_locals() {
return;
}
let Some(parent) = checker.semantic().first_non_type_parent_scope(scope) else {
return;
};
match &scope.kind {
ScopeKind::Function(
function_def @ ast::StmtFunctionDef {
name,
parameters,
decorator_list,
..
},
) => {
match function_type::classify(
name,
decorator_list,
parent,
checker.semantic(),
&checker.settings().pep8_naming.classmethod_decorators,
&checker.settings().pep8_naming.staticmethod_decorators,
) {
function_type::FunctionType::Function => {
if checker.is_rule_enabled(Argumentable::Function.rule_code())
&& !function_type::is_stub(function_def, checker.semantic())
&& !is_not_implemented_stub_with_variable(function_def, checker.semantic())
&& !visibility::is_overload(decorator_list, checker.semantic())
{
function(Argumentable::Function, parameters, scope, checker);
}
}
function_type::FunctionType::Method => {
if checker.is_rule_enabled(Argumentable::Method.rule_code())
&& !function_type::is_stub(function_def, checker.semantic())
&& !is_not_implemented_stub_with_variable(function_def, checker.semantic())
&& (!visibility::is_magic(name)
|| visibility::is_init(name)
|| visibility::is_call(name))
&& !visibility::is_abstract(decorator_list, checker.semantic())
&& !visibility::is_override(decorator_list, checker.semantic())
&& !visibility::is_overload(decorator_list, checker.semantic())
{
method(Argumentable::Method, parameters, scope, checker);
}
}
function_type::FunctionType::ClassMethod => {
if checker.is_rule_enabled(Argumentable::ClassMethod.rule_code())
&& !function_type::is_stub(function_def, checker.semantic())
&& !is_not_implemented_stub_with_variable(function_def, checker.semantic())
&& (!visibility::is_magic(name)
|| visibility::is_init(name)
|| visibility::is_call(name))
&& !visibility::is_abstract(decorator_list, checker.semantic())
&& !visibility::is_override(decorator_list, checker.semantic())
&& !visibility::is_overload(decorator_list, checker.semantic())
{
method(Argumentable::ClassMethod, parameters, scope, checker);
}
}
function_type::FunctionType::StaticMethod => {
if checker.is_rule_enabled(Argumentable::StaticMethod.rule_code())
&& !function_type::is_stub(function_def, checker.semantic())
&& !is_not_implemented_stub_with_variable(function_def, checker.semantic())
&& (!visibility::is_magic(name)
|| visibility::is_init(name)
|| visibility::is_call(name))
&& !visibility::is_abstract(decorator_list, checker.semantic())
&& !visibility::is_override(decorator_list, checker.semantic())
&& !visibility::is_overload(decorator_list, checker.semantic())
{
function(Argumentable::StaticMethod, parameters, scope, checker);
}
}
function_type::FunctionType::NewMethod => {
if checker.is_rule_enabled(Argumentable::StaticMethod.rule_code())
&& !function_type::is_stub(function_def, checker.semantic())
&& !is_not_implemented_stub_with_variable(function_def, checker.semantic())
&& !visibility::is_abstract(decorator_list, checker.semantic())
&& !visibility::is_override(decorator_list, checker.semantic())
&& !visibility::is_overload(decorator_list, checker.semantic())
{
// we use `method()` here rather than `function()`, as although `__new__` is
// an implicit staticmethod, `__new__` methods must always have at least one parameter
method(Argumentable::StaticMethod, parameters, scope, checker);
}
}
}
}
ScopeKind::Lambda(ast::ExprLambda { parameters, .. }) => {
if let Some(parameters) = parameters {
if checker.is_rule_enabled(Argumentable::Lambda.rule_code()) {
function(Argumentable::Lambda, parameters, scope, checker);
}
}
}
_ => panic!("Expected ScopeKind::Function | ScopeKind::Lambda"),
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/settings.rs | crates/ruff_linter/src/rules/flake8_pytest_style/settings.rs | //! Settings for the `flake8-pytest-style` plugin.
use std::error::Error;
use std::fmt;
use std::fmt::Formatter;
use crate::display_settings;
use ruff_macros::CacheKey;
use crate::settings::types::IdentifierPattern;
use super::types;
pub fn default_broad_exceptions() -> Vec<IdentifierPattern> {
[
"BaseException",
"Exception",
"ValueError",
"OSError",
"IOError",
"EnvironmentError",
"socket.error",
]
.map(|pattern| IdentifierPattern::new(pattern).expect("invalid default exception pattern"))
.to_vec()
}
pub fn default_broad_warnings() -> Vec<IdentifierPattern> {
["Warning", "UserWarning", "DeprecationWarning"]
.map(|pattern| IdentifierPattern::new(pattern).expect("invalid default warning pattern"))
.to_vec()
}
#[derive(Debug, Clone, CacheKey)]
pub struct Settings {
pub fixture_parentheses: bool,
pub parametrize_names_type: types::ParametrizeNameType,
pub parametrize_values_type: types::ParametrizeValuesType,
pub parametrize_values_row_type: types::ParametrizeValuesRowType,
pub raises_require_match_for: Vec<IdentifierPattern>,
pub raises_extend_require_match_for: Vec<IdentifierPattern>,
pub mark_parentheses: bool,
pub warns_require_match_for: Vec<IdentifierPattern>,
pub warns_extend_require_match_for: Vec<IdentifierPattern>,
}
impl Default for Settings {
fn default() -> Self {
Self {
fixture_parentheses: false,
parametrize_names_type: types::ParametrizeNameType::default(),
parametrize_values_type: types::ParametrizeValuesType::default(),
parametrize_values_row_type: types::ParametrizeValuesRowType::default(),
raises_require_match_for: default_broad_exceptions(),
raises_extend_require_match_for: vec![],
mark_parentheses: false,
warns_require_match_for: default_broad_warnings(),
warns_extend_require_match_for: vec![],
}
}
}
impl fmt::Display for Settings {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.flake8_pytest_style",
fields = [
self.fixture_parentheses,
self.parametrize_names_type,
self.parametrize_values_type,
self.parametrize_values_row_type,
self.raises_require_match_for | array,
self.raises_extend_require_match_for | array,
self.mark_parentheses
]
}
Ok(())
}
}
/// Error returned by the [`TryFrom`] implementation of [`Settings`].
#[derive(Debug)]
pub enum SettingsError {
InvalidRaisesRequireMatchFor(glob::PatternError),
InvalidRaisesExtendRequireMatchFor(glob::PatternError),
InvalidWarnsRequireMatchFor(glob::PatternError),
InvalidWarnsExtendRequireMatchFor(glob::PatternError),
}
impl fmt::Display for SettingsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SettingsError::InvalidRaisesRequireMatchFor(err) => {
write!(f, "invalid raises-require-match-for pattern: {err}")
}
SettingsError::InvalidRaisesExtendRequireMatchFor(err) => {
write!(f, "invalid raises-extend-require-match-for pattern: {err}")
}
SettingsError::InvalidWarnsRequireMatchFor(err) => {
write!(f, "invalid warns-require-match-for pattern: {err}")
}
SettingsError::InvalidWarnsExtendRequireMatchFor(err) => {
write!(f, "invalid warns-extend-require-match-for pattern: {err}")
}
}
}
}
impl Error for SettingsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
SettingsError::InvalidRaisesRequireMatchFor(err) => Some(err),
SettingsError::InvalidRaisesExtendRequireMatchFor(err) => Some(err),
SettingsError::InvalidWarnsRequireMatchFor(err) => Some(err),
SettingsError::InvalidWarnsExtendRequireMatchFor(err) => Some(err),
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/helpers.rs | crates/ruff_linter/src/rules/flake8_pytest_style/helpers.rs | use std::fmt;
use ruff_python_ast::helpers::map_callable;
use ruff_python_ast::{self as ast, Decorator, Expr, ExprCall, Keyword, Stmt, StmtFunctionDef};
use ruff_python_semantic::analyze::visibility;
use ruff_python_semantic::{ScopeKind, SemanticModel};
use ruff_python_trivia::PythonWhitespace;
use crate::checkers::ast::Checker;
pub(super) fn get_mark_decorators<'a>(
decorators: &'a [Decorator],
semantic: &'a SemanticModel,
) -> impl Iterator<Item = (&'a Decorator, &'a str)> + 'a {
decorators.iter().filter_map(move |decorator| {
let expr = map_callable(&decorator.expression);
let qualified_name = semantic.resolve_qualified_name(expr)?;
match qualified_name.segments() {
["pytest", "mark", marker] => Some((decorator, *marker)),
_ => None,
}
})
}
pub(super) fn is_pytest_fail(call: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(call)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["pytest", "fail"]))
}
pub(super) fn is_pytest_fixture(decorator: &Decorator, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(map_callable(&decorator.expression))
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["pytest", "fixture"]))
}
pub(super) fn is_pytest_yield_fixture(decorator: &Decorator, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(map_callable(&decorator.expression))
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["pytest", "yield_fixture"])
})
}
pub(super) fn is_pytest_parametrize(call: &ExprCall, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["pytest", "mark", "parametrize"])
})
}
/// Whether the currently checked `func` is likely to be a Pytest test.
///
/// A normal Pytest test function is one whose name starts with `test` and is either:
///
/// * Placed at module-level, or
/// * Placed within a class whose name starts with `Test` and does not have an `__init__` method.
///
/// During test discovery, Pytest respects a few settings which we do not have access to.
/// This function is thus prone to both false positives and false negatives.
///
/// References:
/// - [`pytest` documentation: Conventions for Python test discovery](https://docs.pytest.org/en/stable/explanation/goodpractices.html#conventions-for-python-test-discovery)
/// - [`pytest` documentation: Changing naming conventions](https://docs.pytest.org/en/stable/example/pythoncollection.html#changing-naming-conventions)
pub(crate) fn is_likely_pytest_test(func: &StmtFunctionDef, checker: &Checker) -> bool {
let semantic = checker.semantic();
if !func.name.starts_with("test") {
return false;
}
if semantic.scope_id.is_global() {
return true;
}
let ScopeKind::Class(class) = semantic.current_scope().kind else {
return false;
};
if !class.name.starts_with("Test") {
return false;
}
class.body.iter().all(|stmt| {
let Stmt::FunctionDef(function) = stmt else {
return true;
};
!visibility::is_init(&function.name)
})
}
pub(super) fn keyword_is_literal(keyword: &Keyword, literal: &str) -> bool {
if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &keyword.value {
value == literal
} else {
false
}
}
pub(super) fn is_empty_or_null_string(expr: &Expr) -> bool {
match expr {
Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => value.is_empty(),
Expr::NoneLiteral(_) => true,
Expr::FString(ast::ExprFString { value, .. }) => {
value.iter().all(|f_string_part| match f_string_part {
ast::FStringPart::Literal(literal) => literal.is_empty(),
ast::FStringPart::FString(f_string) => f_string
.elements
.iter()
.all(is_empty_or_null_interpolated_string_element),
})
}
_ => false,
}
}
fn is_empty_or_null_interpolated_string_element(element: &ast::InterpolatedStringElement) -> bool {
match element {
ast::InterpolatedStringElement::Literal(ast::InterpolatedStringLiteralElement {
value,
..
}) => value.is_empty(),
ast::InterpolatedStringElement::Interpolation(ast::InterpolatedElement {
expression,
..
}) => is_empty_or_null_string(expression),
}
}
pub(super) fn split_names(names: &str) -> Vec<&str> {
// Match the following pytest code:
// [x.strip() for x in argnames.split(",") if x.strip()]
names
.split(',')
.filter_map(|s| {
let trimmed = s.trim_whitespace();
if trimmed.is_empty() {
None
} else {
Some(trimmed)
}
})
.collect::<Vec<&str>>()
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub(super) enum Parentheses {
None,
Empty,
}
impl fmt::Display for Parentheses {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Parentheses::None => fmt.write_str(""),
Parentheses::Empty => fmt.write_str("()"),
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/types.rs | crates/ruff_linter/src/rules/flake8_pytest_style/types.rs | use std::fmt::{Display, Formatter};
use serde::{Deserialize, Serialize};
use ruff_macros::CacheKey;
#[derive(Clone, Copy, Debug, CacheKey, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Default)]
pub enum ParametrizeNameType {
#[serde(rename = "csv")]
Csv,
#[serde(rename = "tuple")]
#[default]
Tuple,
#[serde(rename = "list")]
List,
}
impl Display for ParametrizeNameType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Csv => write!(f, "string of comma-separated values"),
Self::Tuple => write!(f, "tuple"),
Self::List => write!(f, "list"),
}
}
}
#[derive(Clone, Copy, Debug, CacheKey, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Default)]
pub enum ParametrizeValuesType {
#[serde(rename = "tuple")]
Tuple,
#[serde(rename = "list")]
#[default]
List,
}
impl Display for ParametrizeValuesType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Tuple => write!(f, "tuple"),
Self::List => write!(f, "list"),
}
}
}
#[derive(Clone, Copy, Debug, CacheKey, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Default)]
pub enum ParametrizeValuesRowType {
#[serde(rename = "tuple")]
#[default]
Tuple,
#[serde(rename = "list")]
List,
}
impl Display for ParametrizeValuesRowType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Tuple => write!(f, "tuple"),
Self::List => write!(f, "list"),
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/mod.rs | crates/ruff_linter/src/rules/flake8_pytest_style/mod.rs | //! Rules from [flake8-pytest-style](https://pypi.org/project/flake8-pytest-style/).
mod helpers;
pub(crate) mod rules;
pub mod settings;
pub mod types;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::registry::Rule;
use crate::settings::types::IdentifierPattern;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
use super::settings::Settings;
use super::types;
#[test_case(
Rule::PytestParameterWithDefaultArgument,
Path::new("is_pytest_test.py"),
Settings::default(),
"is_pytest_test"
)]
#[test_case(
Rule::PytestFixtureIncorrectParenthesesStyle,
Path::new("PT001.py"),
Settings::default(),
"PT001_default"
)]
#[test_case(
Rule::PytestFixtureIncorrectParenthesesStyle,
Path::new("PT001.py"),
Settings {
fixture_parentheses: true,
..Settings::default()
},
"PT001_parentheses"
)]
#[test_case(
Rule::PytestFixturePositionalArgs,
Path::new("PT002.py"),
Settings::default(),
"PT002"
)]
#[test_case(
Rule::PytestExtraneousScopeFunction,
Path::new("PT003.py"),
Settings::default(),
"PT003"
)]
#[test_case(
Rule::PytestParametrizeNamesWrongType,
Path::new("PT006.py"),
Settings::default(),
"PT006_default"
)]
#[test_case(
Rule::PytestParametrizeNamesWrongType,
Path::new("PT006.py"),
Settings {
parametrize_names_type: types::ParametrizeNameType::Csv,
..Settings::default()
},
"PT006_csv"
)]
#[test_case(
Rule::PytestParametrizeNamesWrongType,
Path::new("PT006.py"),
Settings {
parametrize_names_type: types::ParametrizeNameType::List,
..Settings::default()
},
"PT006_list"
)]
#[test_case(
Rule::PytestParametrizeValuesWrongType,
Path::new("PT007.py"),
Settings::default(),
"PT007_list_of_tuples"
)]
#[test_case(
Rule::PytestParametrizeValuesWrongType,
Path::new("PT007.py"),
Settings {
parametrize_values_type: types::ParametrizeValuesType::Tuple,
..Settings::default()
},
"PT007_tuple_of_tuples"
)]
#[test_case(
Rule::PytestParametrizeValuesWrongType,
Path::new("PT007.py"),
Settings {
parametrize_values_type: types::ParametrizeValuesType::Tuple,
parametrize_values_row_type: types::ParametrizeValuesRowType::List,
..Settings::default()
},
"PT007_tuple_of_lists"
)]
#[test_case(
Rule::PytestParametrizeValuesWrongType,
Path::new("PT007.py"),
Settings {
parametrize_values_row_type: types::ParametrizeValuesRowType::List,
..Settings::default()
},
"PT007_list_of_lists"
)]
#[test_case(
Rule::PytestPatchWithLambda,
Path::new("PT008.py"),
Settings::default(),
"PT008"
)]
#[test_case(
Rule::PytestUnittestAssertion,
Path::new("PT009.py"),
Settings::default(),
"PT009";
"PT009"
)]
#[test_case(
Rule::PytestRaisesWithoutException,
Path::new("PT010.py"),
Settings::default(),
"PT010"
)]
#[test_case(
Rule::PytestRaisesTooBroad,
Path::new("PT011.py"),
Settings::default(),
"PT011_default"
)]
#[test_case(
Rule::PytestRaisesTooBroad,
Path::new("PT011.py"),
Settings {
raises_extend_require_match_for: vec![IdentifierPattern::new("ZeroDivisionError").unwrap()],
..Settings::default()
},
"PT011_extend_broad_exceptions"
)]
#[test_case(
Rule::PytestRaisesTooBroad,
Path::new("PT011.py"),
Settings {
raises_require_match_for: vec![IdentifierPattern::new("ZeroDivisionError").unwrap()],
..Settings::default()
},
"PT011_replace_broad_exceptions"
)]
#[test_case(
Rule::PytestRaisesTooBroad,
Path::new("PT011.py"),
Settings {
raises_require_match_for: vec![IdentifierPattern::new("*").unwrap()],
..Settings::default()
},
"PT011_glob_all"
)]
#[test_case(
Rule::PytestRaisesTooBroad,
Path::new("PT011.py"),
Settings {
raises_require_match_for: vec![IdentifierPattern::new("pickle.*").unwrap()],
..Settings::default()
},
"PT011_glob_prefix"
)]
#[test_case(
Rule::PytestRaisesWithMultipleStatements,
Path::new("PT012.py"),
Settings::default(),
"PT012"
)]
#[test_case(
Rule::PytestIncorrectPytestImport,
Path::new("PT013.py"),
Settings::default(),
"PT013"
)]
#[test_case(
Rule::PytestDuplicateParametrizeTestCases,
Path::new("PT014.py"),
Settings::default(),
"PT014"
)]
#[test_case(
Rule::PytestAssertAlwaysFalse,
Path::new("PT015.py"),
Settings::default(),
"PT015"
)]
#[test_case(
Rule::PytestFailWithoutMessage,
Path::new("PT016.py"),
Settings::default(),
"PT016"
)]
#[test_case(
Rule::PytestAssertInExcept,
Path::new("PT017.py"),
Settings::default(),
"PT017"
)]
#[test_case(
Rule::PytestCompositeAssertion,
Path::new("PT018.py"),
Settings::default(),
"PT018"
)]
#[test_case(
Rule::PytestFixtureParamWithoutValue,
Path::new("PT019.py"),
Settings::default(),
"PT019"
)]
#[test_case(
Rule::PytestDeprecatedYieldFixture,
Path::new("PT020.py"),
Settings::default(),
"PT020"
)]
#[test_case(
Rule::PytestFixtureFinalizerCallback,
Path::new("PT021.py"),
Settings::default(),
"PT021"
)]
#[test_case(
Rule::PytestUselessYieldFixture,
Path::new("PT022.py"),
Settings::default(),
"PT022"
)]
#[test_case(
Rule::PytestIncorrectMarkParenthesesStyle,
Path::new("PT023.py"),
Settings::default(),
"PT023_default"
)]
#[test_case(
Rule::PytestIncorrectMarkParenthesesStyle,
Path::new("PT023.py"),
Settings {
mark_parentheses: true,
..Settings::default()
},
"PT023_parentheses"
)]
#[test_case(
Rule::PytestUnnecessaryAsyncioMarkOnFixture,
Path::new("PT024.py"),
Settings::default(),
"PT024"
)]
#[test_case(
Rule::PytestErroneousUseFixturesOnFixture,
Path::new("PT025.py"),
Settings::default(),
"PT025"
)]
#[test_case(
Rule::PytestUseFixturesWithoutParameters,
Path::new("PT026.py"),
Settings::default(),
"PT026"
)]
#[test_case(
Rule::PytestUnittestRaisesAssertion,
Path::new("PT027_0.py"),
Settings::default(),
"PT027_0"
)]
#[test_case(
Rule::PytestUnittestRaisesAssertion,
Path::new("PT027_1.py"),
Settings::default(),
"PT027_1"
)]
#[test_case(
Rule::PytestParameterWithDefaultArgument,
Path::new("PT028.py"),
Settings::default(),
"PT028"
)]
#[test_case(
Rule::PytestWarnsWithoutWarning,
Path::new("PT029.py"),
Settings::default(),
"PT029"
)]
#[test_case(
Rule::PytestWarnsTooBroad,
Path::new("PT030.py"),
Settings::default(),
"PT030_default"
)]
#[test_case(
Rule::PytestWarnsTooBroad,
Path::new("PT030.py"),
Settings {
warns_extend_require_match_for: vec![IdentifierPattern::new("EncodingWarning").unwrap()],
..Settings::default()
},
"PT030_extend_broad_exceptions"
)]
#[test_case(
Rule::PytestWarnsTooBroad,
Path::new("PT030.py"),
Settings {
warns_require_match_for: vec![IdentifierPattern::new("EncodingWarning").unwrap()],
..Settings::default()
},
"PT030_replace_broad_exceptions"
)]
#[test_case(
Rule::PytestWarnsTooBroad,
Path::new("PT030.py"),
Settings {
warns_require_match_for: vec![IdentifierPattern::new("*").unwrap()],
..Settings::default()
},
"PT030_glob_all"
)]
#[test_case(
Rule::PytestWarnsTooBroad,
Path::new("PT030.py"),
Settings {
warns_require_match_for: vec![IdentifierPattern::new("foo.*").unwrap()],
..Settings::default()
},
"PT030_glob_prefix"
)]
#[test_case(
Rule::PytestWarnsWithMultipleStatements,
Path::new("PT031.py"),
Settings::default(),
"PT031"
)]
fn test_pytest_style(
rule_code: Rule,
path: &Path,
plugin_settings: Settings,
name: &str,
) -> Result<()> {
let diagnostics = test_path(
Path::new("flake8_pytest_style").join(path).as_path(),
&settings::LinterSettings {
flake8_pytest_style: plugin_settings,
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(name, diagnostics);
Ok(())
}
/// This test ensure that PT006 and PT007 don't conflict when both of them suggest a fix that
/// edits `argvalues` for `pytest.mark.parametrize`.
#[test]
fn test_pytest_style_pt006_and_pt007() -> Result<()> {
let diagnostics = test_path(
Path::new("flake8_pytest_style")
.join(Path::new("PT006_and_PT007.py"))
.as_path(),
&settings::LinterSettings {
..settings::LinterSettings::for_rules(vec![
Rule::PytestParametrizeNamesWrongType,
Rule::PytestParametrizeValuesWrongType,
])
},
)?;
assert_diagnostics!("PT006_and_PT007", diagnostics);
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/imports.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/imports.rs | use ruff_python_ast::Stmt;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::{Violation, checkers::ast::Checker};
/// ## What it does
/// Checks for incorrect import of pytest.
///
/// ## Why is this bad?
/// For consistency, `pytest` should be imported as `import pytest` and its members should be
/// accessed in the form of `pytest.xxx.yyy` for consistency
///
/// ## Example
/// ```python
/// import pytest as pt
/// from pytest import fixture
/// ```
///
/// Use instead:
/// ```python
/// import pytest
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestIncorrectPytestImport;
impl Violation for PytestIncorrectPytestImport {
#[derive_message_formats]
fn message(&self) -> String {
"Incorrect import of `pytest`; use `import pytest` instead".to_string()
}
}
fn is_pytest_or_subpackage(imported_name: &str) -> bool {
imported_name == "pytest" || imported_name.starts_with("pytest.")
}
/// PT013
pub(crate) fn import(checker: &Checker, import_from: &Stmt, name: &str, asname: Option<&str>) {
if is_pytest_or_subpackage(name) {
if let Some(alias) = asname {
if alias != name {
checker.report_diagnostic(PytestIncorrectPytestImport, import_from.range());
}
}
}
}
/// PT013
pub(crate) fn import_from(checker: &Checker, import_from: &Stmt, module: Option<&str>, level: u32) {
// If level is not zero or module is none, return
if level != 0 {
return;
}
if let Some(module) = module {
if is_pytest_or_subpackage(module) {
checker.report_diagnostic(PytestIncorrectPytestImport, import_from.range());
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/warns.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/warns.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_compound_statement;
use ruff_python_ast::{self as ast, Expr, Stmt, WithItem};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use crate::rules::flake8_pytest_style::helpers::is_empty_or_null_string;
/// ## What it does
/// Checks for `pytest.warns` context managers with multiple statements.
///
/// This rule allows `pytest.warns` bodies to contain `for`
/// loops with empty bodies (e.g., `pass` or `...` statements), to test
/// iterator behavior.
///
/// ## Why is this bad?
/// When `pytest.warns` is used as a context manager and contains multiple
/// statements, it can lead to the test passing when it should instead fail.
///
/// A `pytest.warns` context manager should only contain a single
/// simple statement that triggers the expected warning.
///
///
/// ## Example
/// ```python
/// import pytest
///
///
/// def test_foo_warns():
/// with pytest.warns(Warning):
/// setup() # False negative if setup triggers a warning but foo does not.
/// foo()
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// def test_foo_warns():
/// setup()
/// with pytest.warns(Warning):
/// foo()
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.warns`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-warns)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct PytestWarnsWithMultipleStatements;
impl Violation for PytestWarnsWithMultipleStatements {
#[derive_message_formats]
fn message(&self) -> String {
"`pytest.warns()` block should contain a single simple statement".to_string()
}
}
/// ## What it does
/// Checks for `pytest.warns` calls without a `match` parameter.
///
/// ## Why is this bad?
/// `pytest.warns(Warning)` will catch any `Warning` and may catch warnings that
/// are unrelated to the code under test. To avoid this, `pytest.warns` should
/// be called with a `match` parameter. The warning names that require a `match`
/// parameter can be configured via the
/// [`lint.flake8-pytest-style.warns-require-match-for`] and
/// [`lint.flake8-pytest-style.warns-extend-require-match-for`] settings.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.warns(Warning):
/// ...
///
/// # empty string is also an error
/// with pytest.warns(Warning, match=""):
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.warns(Warning, match="expected message"):
/// ...
/// ```
///
/// ## Options
/// - `lint.flake8-pytest-style.warns-require-match-for`
/// - `lint.flake8-pytest-style.warns-extend-require-match-for`
///
/// ## References
/// - [`pytest` documentation: `pytest.warns`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-warns)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct PytestWarnsTooBroad {
warning: String,
}
impl Violation for PytestWarnsTooBroad {
#[derive_message_formats]
fn message(&self) -> String {
let PytestWarnsTooBroad { warning } = self;
format!(
"`pytest.warns({warning})` is too broad, set the `match` parameter or use a more \
specific warning"
)
}
}
/// ## What it does
/// Checks for `pytest.warns` calls without an expected warning.
///
/// ## Why is this bad?
/// `pytest.warns` expects to receive an expected warning as its first
/// argument. If omitted, the `pytest.warns` call will fail at runtime.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.warns():
/// do_something()
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.warns(SomeWarning):
/// do_something()
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.warns`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-warns)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.9.2")]
pub(crate) struct PytestWarnsWithoutWarning;
impl Violation for PytestWarnsWithoutWarning {
#[derive_message_formats]
fn message(&self) -> String {
"Set the expected warning in `pytest.warns()`".to_string()
}
}
pub(crate) fn is_pytest_warns(func: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["pytest", "warns"]))
}
const fn is_non_trivial_with_body(body: &[Stmt]) -> bool {
if let [stmt] = body {
is_compound_statement(stmt)
} else {
true
}
}
/// PT029, PT030
pub(crate) fn warns_call(checker: &Checker, call: &ast::ExprCall) {
if is_pytest_warns(&call.func, checker.semantic()) {
if checker.is_rule_enabled(Rule::PytestWarnsWithoutWarning) {
if call.arguments.is_empty() {
checker.report_diagnostic(PytestWarnsWithoutWarning, call.func.range());
}
}
if checker.is_rule_enabled(Rule::PytestWarnsTooBroad) {
if let Some(warning) = call.arguments.find_argument_value("expected_warning", 0) {
if call
.arguments
.find_keyword("match")
.is_none_or(|k| is_empty_or_null_string(&k.value))
{
warning_needs_match(checker, warning);
}
}
}
}
}
/// PT031
pub(crate) fn complex_warns(checker: &Checker, stmt: &Stmt, items: &[WithItem], body: &[Stmt]) {
let warns_called = items.iter().any(|item| match &item.context_expr {
Expr::Call(ast::ExprCall { func, .. }) => is_pytest_warns(func, checker.semantic()),
_ => false,
});
// Check body for `pytest.warns` context manager
if warns_called {
let is_too_complex = if let [stmt] = body {
match stmt {
Stmt::With(ast::StmtWith { body, .. }) => is_non_trivial_with_body(body),
// Allow function and class definitions to test decorators.
Stmt::ClassDef(_) | Stmt::FunctionDef(_) => false,
// Allow empty `for` loops to test iterators.
Stmt::For(ast::StmtFor { body, .. }) => match &body[..] {
[Stmt::Pass(_)] => false,
[Stmt::Expr(ast::StmtExpr { value, .. })] => !value.is_ellipsis_literal_expr(),
_ => true,
},
stmt => is_compound_statement(stmt),
}
} else {
true
};
if is_too_complex {
checker.report_diagnostic(PytestWarnsWithMultipleStatements, stmt.range());
}
}
}
/// PT030
fn warning_needs_match(checker: &Checker, warning: &Expr) {
if let Some(qualified_name) =
checker
.semantic()
.resolve_qualified_name(warning)
.and_then(|qualified_name| {
let qualified_name = qualified_name.to_string();
checker
.settings()
.flake8_pytest_style
.warns_require_match_for
.iter()
.chain(
&checker
.settings()
.flake8_pytest_style
.warns_extend_require_match_for,
)
.any(|pattern| pattern.matches(&qualified_name))
.then_some(qualified_name)
})
{
checker.report_diagnostic(
PytestWarnsTooBroad {
warning: qualified_name,
},
warning.range(),
);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fail.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/fail.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_pytest_style::helpers::{is_empty_or_null_string, is_pytest_fail};
/// ## What it does
/// Checks for `pytest.fail` calls without a message.
///
/// ## Why is this bad?
/// `pytest.fail` calls without a message make it harder to understand and debug test failures.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// def test_foo():
/// pytest.fail()
///
///
/// def test_bar():
/// pytest.fail("")
///
///
/// def test_baz():
/// pytest.fail(reason="")
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// def test_foo():
/// pytest.fail("...")
///
///
/// def test_bar():
/// pytest.fail(reason="...")
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.fail`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fail)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestFailWithoutMessage;
impl Violation for PytestFailWithoutMessage {
#[derive_message_formats]
fn message(&self) -> String {
"No message passed to `pytest.fail()`".to_string()
}
}
/// PT016
pub(crate) fn fail_call(checker: &Checker, call: &ast::ExprCall) {
if is_pytest_fail(&call.func, checker.semantic()) {
// Allow either `pytest.fail(reason="...")` (introduced in pytest 7.0) or
// `pytest.fail(msg="...")` (deprecated in pytest 7.0)
if call
.arguments
.find_argument_value("reason", 0)
.or_else(|| call.arguments.find_argument_value("msg", 0))
.is_none_or(is_empty_or_null_string)
{
checker.report_diagnostic(PytestFailWithoutMessage, call.func.range());
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/unittest_assert.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/unittest_assert.rs | use anyhow::{Result, anyhow, bail};
use ruff_python_ast::name::Name;
use ruff_python_ast::{
self as ast, Arguments, CmpOp, Expr, ExprContext, Identifier, Keyword, Stmt, UnaryOp,
};
use ruff_text_size::TextRange;
use rustc_hash::{FxBuildHasher, FxHashMap};
/// An enum to represent the different types of assertions present in the
/// `unittest` module. Note: any variants that can't be replaced with plain
/// `assert` statements are commented out.
#[derive(Copy, Clone)]
pub(crate) enum UnittestAssert {
AlmostEqual,
AlmostEquals,
CountEqual,
DictContainsSubset,
DictEqual,
Equal,
Equals,
FailIf,
FailIfAlmostEqual,
FailIfEqual,
FailUnless,
FailUnlessAlmostEqual,
FailUnlessEqual,
// FailUnlessRaises,
False,
Greater,
GreaterEqual,
In,
Is,
IsInstance,
IsNone,
IsNot,
IsNotNone,
Less,
LessEqual,
ListEqual,
// Logs,
MultiLineEqual,
// NoLogs,
NotAlmostEqual,
NotAlmostEquals,
NotEqual,
NotEquals,
NotIn,
NotIsInstance,
NotRegex,
NotRegexpMatches,
// Raises,
// RaisesRegex,
// RaisesRegexp,
Regex,
RegexpMatches,
SequenceEqual,
SetEqual,
True,
TupleEqual,
Underscore,
// Warns,
// WarnsRegex,
}
impl std::fmt::Display for UnittestAssert {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UnittestAssert::AlmostEqual => write!(f, "assertAlmostEqual"),
UnittestAssert::AlmostEquals => write!(f, "assertAlmostEquals"),
UnittestAssert::CountEqual => write!(f, "assertCountEqual"),
UnittestAssert::DictContainsSubset => write!(f, "assertDictContainsSubset"),
UnittestAssert::DictEqual => write!(f, "assertDictEqual"),
UnittestAssert::Equal => write!(f, "assertEqual"),
UnittestAssert::Equals => write!(f, "assertEquals"),
UnittestAssert::FailIf => write!(f, "failIf"),
UnittestAssert::FailIfAlmostEqual => write!(f, "failIfAlmostEqual"),
UnittestAssert::FailIfEqual => write!(f, "failIfEqual"),
UnittestAssert::FailUnless => write!(f, "failUnless"),
UnittestAssert::FailUnlessAlmostEqual => write!(f, "failUnlessAlmostEqual"),
UnittestAssert::FailUnlessEqual => write!(f, "failUnlessEqual"),
UnittestAssert::False => write!(f, "assertFalse"),
UnittestAssert::Greater => write!(f, "assertGreater"),
UnittestAssert::GreaterEqual => write!(f, "assertGreaterEqual"),
UnittestAssert::In => write!(f, "assertIn"),
UnittestAssert::Is => write!(f, "assertIs"),
UnittestAssert::IsInstance => write!(f, "assertIsInstance"),
UnittestAssert::IsNone => write!(f, "assertIsNone"),
UnittestAssert::IsNot => write!(f, "assertIsNot"),
UnittestAssert::IsNotNone => write!(f, "assertIsNotNone"),
UnittestAssert::Less => write!(f, "assertLess"),
UnittestAssert::LessEqual => write!(f, "assertLessEqual"),
UnittestAssert::ListEqual => write!(f, "assertListEqual"),
UnittestAssert::MultiLineEqual => write!(f, "assertMultiLineEqual"),
UnittestAssert::NotAlmostEqual => write!(f, "assertNotAlmostEqual"),
UnittestAssert::NotAlmostEquals => write!(f, "assertNotAlmostEquals"),
UnittestAssert::NotEqual => write!(f, "assertNotEqual"),
UnittestAssert::NotEquals => write!(f, "assertNotEquals"),
UnittestAssert::NotIn => write!(f, "assertNotIn"),
UnittestAssert::NotIsInstance => write!(f, "assertNotIsInstance"),
UnittestAssert::NotRegex => write!(f, "assertNotRegex"),
UnittestAssert::NotRegexpMatches => write!(f, "assertNotRegexpMatches"),
UnittestAssert::Regex => write!(f, "assertRegex"),
UnittestAssert::RegexpMatches => write!(f, "assertRegexpMatches"),
UnittestAssert::SequenceEqual => write!(f, "assertSequenceEqual"),
UnittestAssert::SetEqual => write!(f, "assertSetEqual"),
UnittestAssert::True => write!(f, "assertTrue"),
UnittestAssert::TupleEqual => write!(f, "assertTupleEqual"),
UnittestAssert::Underscore => write!(f, "assert_"),
}
}
}
impl TryFrom<&str> for UnittestAssert {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"assertAlmostEqual" => Ok(UnittestAssert::AlmostEqual),
"assertAlmostEquals" => Ok(UnittestAssert::AlmostEquals),
"assertCountEqual" => Ok(UnittestAssert::CountEqual),
"assertDictContainsSubset" => Ok(UnittestAssert::DictContainsSubset),
"assertDictEqual" => Ok(UnittestAssert::DictEqual),
"assertEqual" => Ok(UnittestAssert::Equal),
"assertEquals" => Ok(UnittestAssert::Equals),
"failIf" => Ok(UnittestAssert::FailIf),
"failIfAlmostEqual" => Ok(UnittestAssert::FailIfAlmostEqual),
"failIfEqual" => Ok(UnittestAssert::FailIfEqual),
"failUnless" => Ok(UnittestAssert::FailUnless),
"failUnlessAlmostEqual" => Ok(UnittestAssert::FailUnlessAlmostEqual),
"failUnlessEqual" => Ok(UnittestAssert::FailUnlessEqual),
"assertFalse" => Ok(UnittestAssert::False),
"assertGreater" => Ok(UnittestAssert::Greater),
"assertGreaterEqual" => Ok(UnittestAssert::GreaterEqual),
"assertIn" => Ok(UnittestAssert::In),
"assertIs" => Ok(UnittestAssert::Is),
"assertIsInstance" => Ok(UnittestAssert::IsInstance),
"assertIsNone" => Ok(UnittestAssert::IsNone),
"assertIsNot" => Ok(UnittestAssert::IsNot),
"assertIsNotNone" => Ok(UnittestAssert::IsNotNone),
"assertLess" => Ok(UnittestAssert::Less),
"assertLessEqual" => Ok(UnittestAssert::LessEqual),
"assertListEqual" => Ok(UnittestAssert::ListEqual),
"assertMultiLineEqual" => Ok(UnittestAssert::MultiLineEqual),
"assertNotAlmostEqual" => Ok(UnittestAssert::NotAlmostEqual),
"assertNotAlmostEquals" => Ok(UnittestAssert::NotAlmostEquals),
"assertNotEqual" => Ok(UnittestAssert::NotEqual),
"assertNotEquals" => Ok(UnittestAssert::NotEquals),
"assertNotIn" => Ok(UnittestAssert::NotIn),
"assertNotIsInstance" => Ok(UnittestAssert::NotIsInstance),
"assertNotRegex" => Ok(UnittestAssert::NotRegex),
"assertNotRegexpMatches" => Ok(UnittestAssert::NotRegexpMatches),
"assertRegex" => Ok(UnittestAssert::Regex),
"assertRegexpMatches" => Ok(UnittestAssert::RegexpMatches),
"assertSequenceEqual" => Ok(UnittestAssert::SequenceEqual),
"assertSetEqual" => Ok(UnittestAssert::SetEqual),
"assertTrue" => Ok(UnittestAssert::True),
"assertTupleEqual" => Ok(UnittestAssert::TupleEqual),
"assert_" => Ok(UnittestAssert::Underscore),
_ => Err(format!("Unknown unittest assert method: {value}")),
}
}
}
fn assert(expr: &Expr, msg: Option<&Expr>) -> Stmt {
Stmt::Assert(ast::StmtAssert {
test: Box::new(expr.clone()),
msg: msg.map(|msg| Box::new(msg.clone())),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})
}
fn compare(left: &Expr, cmp_op: CmpOp, right: &Expr) -> Expr {
Expr::Compare(ast::ExprCompare {
left: Box::new(left.clone()),
ops: Box::from([cmp_op]),
comparators: Box::from([right.clone()]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})
}
impl UnittestAssert {
fn arg_spec(&self) -> &[&str] {
match self {
UnittestAssert::AlmostEqual => &["first", "second", "places", "msg", "delta"],
UnittestAssert::AlmostEquals => &["first", "second", "places", "msg", "delta"],
UnittestAssert::CountEqual => &["first", "second", "msg"],
UnittestAssert::DictContainsSubset => &["subset", "dictionary", "msg"],
UnittestAssert::DictEqual => &["first", "second", "msg"],
UnittestAssert::Equal => &["first", "second", "msg"],
UnittestAssert::Equals => &["first", "second", "msg"],
UnittestAssert::False => &["expr", "msg"],
UnittestAssert::Greater => &["first", "second", "msg"],
UnittestAssert::GreaterEqual => &["first", "second", "msg"],
UnittestAssert::In => &["member", "container", "msg"],
UnittestAssert::Is => &["first", "second", "msg"],
UnittestAssert::IsInstance => &["obj", "cls", "msg"],
UnittestAssert::IsNone => &["expr", "msg"],
UnittestAssert::IsNot => &["first", "second", "msg"],
UnittestAssert::IsNotNone => &["expr", "msg"],
UnittestAssert::Less => &["first", "second", "msg"],
UnittestAssert::LessEqual => &["first", "second", "msg"],
UnittestAssert::ListEqual => &["first", "second", "msg"],
UnittestAssert::MultiLineEqual => &["first", "second", "msg"],
UnittestAssert::NotAlmostEqual => &["first", "second", "msg"],
UnittestAssert::NotAlmostEquals => &["first", "second", "msg"],
UnittestAssert::NotEqual => &["first", "second", "msg"],
UnittestAssert::NotEquals => &["first", "second", "msg"],
UnittestAssert::NotIn => &["member", "container", "msg"],
UnittestAssert::NotIsInstance => &["obj", "cls", "msg"],
UnittestAssert::NotRegex => &["text", "regex", "msg"],
UnittestAssert::NotRegexpMatches => &["text", "regex", "msg"],
UnittestAssert::Regex => &["text", "regex", "msg"],
UnittestAssert::RegexpMatches => &["text", "regex", "msg"],
UnittestAssert::SequenceEqual => &["first", "second", "msg", "seq_type"],
UnittestAssert::SetEqual => &["first", "second", "msg"],
UnittestAssert::True => &["expr", "msg"],
UnittestAssert::TupleEqual => &["first", "second", "msg"],
UnittestAssert::Underscore => &["expr", "msg"],
UnittestAssert::FailIf => &["expr", "msg"],
UnittestAssert::FailIfAlmostEqual => &["first", "second", "msg"],
UnittestAssert::FailIfEqual => &["first", "second", "msg"],
UnittestAssert::FailUnless => &["expr", "msg"],
UnittestAssert::FailUnlessAlmostEqual => &["first", "second", "places", "msg", "delta"],
UnittestAssert::FailUnlessEqual => &["first", "second", "places", "msg", "delta"],
}
}
/// Create a map from argument name to value.
pub(crate) fn args_map<'a>(
&'a self,
args: &'a [Expr],
keywords: &'a [Keyword],
) -> Result<FxHashMap<&'a str, &'a Expr>> {
// If we have variable-length arguments, abort.
if args.iter().any(Expr::is_starred_expr) || keywords.iter().any(|kw| kw.arg.is_none()) {
bail!("Variable-length arguments are not supported");
}
let arg_spec = self.arg_spec();
// If any of the keyword arguments are not in the argument spec, abort.
if keywords.iter().any(|kw| {
kw.arg
.as_ref()
.is_some_and(|kwarg_name| !arg_spec.contains(&kwarg_name.as_str()))
}) {
bail!("Unknown keyword argument");
}
// Generate a map from argument name to value.
let mut args_map: FxHashMap<&str, &Expr> =
FxHashMap::with_capacity_and_hasher(args.len() + keywords.len(), FxBuildHasher);
// Process positional arguments.
for (arg_name, value) in arg_spec.iter().zip(args) {
args_map.insert(arg_name, value);
}
// Process keyword arguments.
for arg_name in arg_spec.iter().skip(args.len()) {
if let Some(value) = keywords.iter().find_map(|keyword| {
if keyword
.arg
.as_ref()
.is_some_and(|kwarg_name| &kwarg_name == arg_name)
{
Some(&keyword.value)
} else {
None
}
}) {
args_map.insert(arg_name, value);
}
}
Ok(args_map)
}
pub(crate) fn generate_assert(self, args: &[Expr], keywords: &[Keyword]) -> Result<Stmt> {
let args = self.args_map(args, keywords)?;
match self {
UnittestAssert::True
| UnittestAssert::False
| UnittestAssert::FailUnless
| UnittestAssert::FailIf => {
let expr = *args
.get("expr")
.ok_or_else(|| anyhow!("Missing argument `expr`"))?;
let msg = args.get("msg").copied();
Ok(
if matches!(self, UnittestAssert::False | UnittestAssert::FailIf) {
assert(
&Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::Not,
operand: Box::new(expr.clone()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}),
msg,
)
} else {
assert(expr, msg)
},
)
}
UnittestAssert::Equal
| UnittestAssert::Equals
| UnittestAssert::FailUnlessEqual
| UnittestAssert::NotEqual
| UnittestAssert::NotEquals
| UnittestAssert::FailIfEqual
| UnittestAssert::Greater
| UnittestAssert::GreaterEqual
| UnittestAssert::Less
| UnittestAssert::LessEqual
| UnittestAssert::Is
| UnittestAssert::IsNot => {
let first = args
.get("first")
.ok_or_else(|| anyhow!("Missing argument `first`"))?;
let second = args
.get("second")
.ok_or_else(|| anyhow!("Missing argument `second`"))?;
let msg = args.get("msg").copied();
let cmp_op = match self {
UnittestAssert::Equal
| UnittestAssert::Equals
| UnittestAssert::FailUnlessEqual => CmpOp::Eq,
UnittestAssert::NotEqual
| UnittestAssert::NotEquals
| UnittestAssert::FailIfEqual => CmpOp::NotEq,
UnittestAssert::Greater => CmpOp::Gt,
UnittestAssert::GreaterEqual => CmpOp::GtE,
UnittestAssert::Less => CmpOp::Lt,
UnittestAssert::LessEqual => CmpOp::LtE,
UnittestAssert::Is => CmpOp::Is,
UnittestAssert::IsNot => CmpOp::IsNot,
_ => unreachable!(),
};
let expr = compare(first, cmp_op, second);
Ok(assert(&expr, msg))
}
UnittestAssert::In | UnittestAssert::NotIn => {
let member = args
.get("member")
.ok_or_else(|| anyhow!("Missing argument `member`"))?;
let container = args
.get("container")
.ok_or_else(|| anyhow!("Missing argument `container`"))?;
let msg = args.get("msg").copied();
let cmp_op = if matches!(self, UnittestAssert::In) {
CmpOp::In
} else {
CmpOp::NotIn
};
let expr = compare(member, cmp_op, container);
Ok(assert(&expr, msg))
}
UnittestAssert::IsNone | UnittestAssert::IsNotNone => {
let expr = args
.get("expr")
.ok_or_else(|| anyhow!("Missing argument `expr`"))?;
let msg = args.get("msg").copied();
let cmp_op = if matches!(self, UnittestAssert::IsNone) {
CmpOp::Is
} else {
CmpOp::IsNot
};
let node = Expr::NoneLiteral(ast::ExprNoneLiteral {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
let expr = compare(expr, cmp_op, &node);
Ok(assert(&expr, msg))
}
UnittestAssert::IsInstance | UnittestAssert::NotIsInstance => {
let obj = args
.get("obj")
.ok_or_else(|| anyhow!("Missing argument `obj`"))?;
let cls = args
.get("cls")
.ok_or_else(|| anyhow!("Missing argument `cls`"))?;
let msg = args.get("msg").copied();
let node = ast::ExprName {
id: Name::new_static("isinstance"),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node1 = ast::ExprCall {
func: Box::new(node.into()),
arguments: Arguments {
args: Box::from([(**obj).clone(), (**cls).clone()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let isinstance = node1.into();
if matches!(self, UnittestAssert::IsInstance) {
Ok(assert(&isinstance, msg))
} else {
let node = ast::ExprUnaryOp {
op: UnaryOp::Not,
operand: Box::new(isinstance),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let expr = node.into();
Ok(assert(&expr, msg))
}
}
UnittestAssert::Regex
| UnittestAssert::RegexpMatches
| UnittestAssert::NotRegex
| UnittestAssert::NotRegexpMatches => {
let text = args
.get("text")
.ok_or_else(|| anyhow!("Missing argument `text`"))?;
let regex = args
.get("regex")
.ok_or_else(|| anyhow!("Missing argument `regex`"))?;
let msg = args.get("msg").copied();
let node = ast::ExprName {
id: Name::new_static("re"),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node1 = ast::ExprAttribute {
value: Box::new(node.into()),
attr: Identifier::new("search".to_string(), TextRange::default()),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node2 = ast::ExprCall {
func: Box::new(node1.into()),
arguments: Arguments {
args: Box::from([(**regex).clone(), (**text).clone()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let re_search = node2.into();
if matches!(self, UnittestAssert::Regex | UnittestAssert::RegexpMatches) {
Ok(assert(&re_search, msg))
} else {
let node = ast::ExprUnaryOp {
op: UnaryOp::Not,
operand: Box::new(re_search),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
Ok(assert(&node.into(), msg))
}
}
_ => bail!("Cannot fix `{self}`"),
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/test_functions.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/test_functions.rs | use crate::checkers::ast::Checker;
use crate::rules::flake8_pytest_style::helpers::is_likely_pytest_test;
use crate::{Edit, Fix, Violation};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::StmtFunctionDef;
use ruff_text_size::Ranged;
/// ## What it does
/// Checks for parameters of test functions with default arguments.
///
/// ## Why is this bad?
/// Such a parameter will always have the default value during the test
/// regardless of whether a fixture with the same name is defined.
///
/// ## Example
///
/// ```python
/// def test_foo(a=1): ...
/// ```
///
/// Use instead:
///
/// ```python
/// def test_foo(a): ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as modifying a function signature can
/// change the behavior of the code.
///
/// ## References
/// - [Original Pytest issue](https://github.com/pytest-dev/pytest/issues/12693)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct PytestParameterWithDefaultArgument {
parameter_name: String,
}
impl Violation for PytestParameterWithDefaultArgument {
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Test function parameter `{}` has default argument",
self.parameter_name
)
}
fn fix_title(&self) -> Option<String> {
Some("Remove default argument".to_string())
}
}
/// PT028
pub(crate) fn parameter_with_default_argument(checker: &Checker, function_def: &StmtFunctionDef) {
if !is_likely_pytest_test(function_def, checker) {
return;
}
for parameter in function_def.parameters.iter_non_variadic_params() {
let Some(default) = parameter.default() else {
continue;
};
let parameter_name = parameter.name().to_string();
let kind = PytestParameterWithDefaultArgument { parameter_name };
let edit = Edit::deletion(parameter.parameter.end(), parameter.end());
let fix = Fix::display_only_edit(edit);
checker
.report_diagnostic(kind, default.range())
.set_fix(fix);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/raises.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/raises.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_compound_statement;
use ruff_python_ast::{self as ast, Expr, Stmt, WithItem};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use crate::rules::flake8_pytest_style::helpers::is_empty_or_null_string;
/// ## What it does
/// Checks for `pytest.raises` context managers with multiple statements.
///
/// This rule allows `pytest.raises` bodies to contain `for`
/// loops with empty bodies (e.g., `pass` or `...` statements), to test
/// iterator behavior.
///
/// ## Why is this bad?
/// When a `pytest.raises` is used as a context manager and contains multiple
/// statements, it can lead to the test passing when it actually should fail.
///
/// A `pytest.raises` context manager should only contain a single simple
/// statement that raises the expected exception.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.raises(MyError):
/// setup()
/// func_to_test() # not executed if `setup()` raises `MyError`
/// assert foo() # not executed
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// def test_foo():
/// setup()
/// with pytest.raises(MyError):
/// func_to_test()
/// assert foo()
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestRaisesWithMultipleStatements;
impl Violation for PytestRaisesWithMultipleStatements {
#[derive_message_formats]
fn message(&self) -> String {
"`pytest.raises()` block should contain a single simple statement".to_string()
}
}
/// ## What it does
/// Checks for `pytest.raises` calls without a `match` parameter.
///
/// ## Why is this bad?
/// `pytest.raises(Error)` will catch any `Error` and may catch errors that are
/// unrelated to the code under test. To avoid this, `pytest.raises` should be
/// called with a `match` parameter. The exception names that require a `match`
/// parameter can be configured via the
/// [`lint.flake8-pytest-style.raises-require-match-for`] and
/// [`lint.flake8-pytest-style.raises-extend-require-match-for`] settings.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.raises(ValueError):
/// ...
///
/// # empty string is also an error
/// with pytest.raises(ValueError, match=""):
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.raises(ValueError, match="expected message"):
/// ...
/// ```
///
/// ## Options
/// - `lint.flake8-pytest-style.raises-require-match-for`
/// - `lint.flake8-pytest-style.raises-extend-require-match-for`
///
/// ## References
/// - [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestRaisesTooBroad {
exception: String,
}
impl Violation for PytestRaisesTooBroad {
#[derive_message_formats]
fn message(&self) -> String {
let PytestRaisesTooBroad { exception } = self;
format!(
"`pytest.raises({exception})` is too broad, set the `match` parameter or use a more \
specific exception"
)
}
}
/// ## What it does
/// Checks for `pytest.raises` calls without an expected exception.
///
/// ## Why is this bad?
/// `pytest.raises` expects to receive an expected exception as its first
/// argument. If omitted, the `pytest.raises` call will fail at runtime.
/// The rule will also accept calls without an expected exception but with
/// `match` and/or `check` keyword arguments, which are also valid after
/// pytest version 8.4.0.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.raises():
/// do_something()
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.raises(SomeException):
/// do_something()
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestRaisesWithoutException;
impl Violation for PytestRaisesWithoutException {
#[derive_message_formats]
fn message(&self) -> String {
"Set the expected exception in `pytest.raises()`".to_string()
}
}
pub(crate) fn is_pytest_raises(func: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["pytest", "raises"]))
}
const fn is_non_trivial_with_body(body: &[Stmt]) -> bool {
if let [stmt] = body {
is_compound_statement(stmt)
} else {
true
}
}
/// PT010
pub(crate) fn raises_call(checker: &Checker, call: &ast::ExprCall) {
if is_pytest_raises(&call.func, checker.semantic()) {
if checker.is_rule_enabled(Rule::PytestRaisesWithoutException) {
if call
.arguments
.find_argument("expected_exception", 0)
.is_none()
&& call.arguments.find_keyword("match").is_none()
&& call.arguments.find_keyword("check").is_none()
{
checker.report_diagnostic(PytestRaisesWithoutException, call.func.range());
}
}
if checker.is_rule_enabled(Rule::PytestRaisesTooBroad) {
// Pytest.raises has two overloads
// ```py
// with raises(expected_exception: type[E] | tuple[type[E], ...], *, match: str | Pattern[str] | None = ...) β RaisesContext[E] as excinfo
// with raises(expected_exception: type[E] | tuple[type[E], ...], func: Callable[[...], Any], *args: Any, **kwargs: Any) β ExceptionInfo[E] as excinfo
// ```
// Don't raise this diagnostic if the call matches the second overload (has a second positional argument or an argument named `func`)
if call.arguments.find_argument("func", 1).is_none() {
if let Some(exception) = call.arguments.find_argument_value("expected_exception", 0)
{
if call
.arguments
.find_keyword("match")
.is_none_or(|k| is_empty_or_null_string(&k.value))
{
exception_needs_match(checker, exception);
}
}
}
}
}
}
/// PT012
pub(crate) fn complex_raises(checker: &Checker, stmt: &Stmt, items: &[WithItem], body: &[Stmt]) {
let raises_called = items.iter().any(|item| match &item.context_expr {
Expr::Call(ast::ExprCall { func, .. }) => is_pytest_raises(func, checker.semantic()),
_ => false,
});
// Check body for `pytest.raises` context manager
if raises_called {
let is_too_complex = if let [stmt] = body {
match stmt {
Stmt::With(ast::StmtWith { body, .. }) => is_non_trivial_with_body(body),
// Allow function and class definitions to test decorators.
Stmt::ClassDef(_) | Stmt::FunctionDef(_) => false,
// Allow empty `for` loops to test iterators.
Stmt::For(ast::StmtFor { body, .. }) => match &body[..] {
[Stmt::Pass(_)] => false,
[Stmt::Expr(ast::StmtExpr { value, .. })] => !value.is_ellipsis_literal_expr(),
_ => true,
},
stmt => is_compound_statement(stmt),
}
} else {
true
};
if is_too_complex {
checker.report_diagnostic(PytestRaisesWithMultipleStatements, stmt.range());
}
}
}
/// PT011
fn exception_needs_match(checker: &Checker, exception: &Expr) {
if let Some(qualified_name) = checker
.semantic()
.resolve_qualified_name(exception)
.and_then(|qualified_name| {
let qualified_name = qualified_name.to_string();
checker
.settings()
.flake8_pytest_style
.raises_require_match_for
.iter()
.chain(
&checker
.settings()
.flake8_pytest_style
.raises_extend_require_match_for,
)
.any(|pattern| pattern.matches(&qualified_name))
.then_some(qualified_name)
})
{
checker.report_diagnostic(
PytestRaisesTooBroad {
exception: qualified_name,
},
exception.range(),
);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fixture.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/fixture.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::Decorator;
use ruff_python_ast::helpers::map_callable;
use ruff_python_ast::name::UnqualifiedName;
use ruff_python_ast::visitor;
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{self as ast, Expr, Parameters, Stmt};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::visibility::is_abstract;
use ruff_source_file::LineRanges;
use ruff_text_size::Ranged;
use ruff_text_size::{TextLen, TextRange};
use rustc_hash::FxHashSet;
use crate::checkers::ast::Checker;
use crate::fix::edits;
use crate::registry::Rule;
use crate::{AlwaysFixableViolation, Violation};
use crate::{Edit, Fix};
use crate::rules::flake8_pytest_style::helpers::{
Parentheses, get_mark_decorators, is_pytest_fixture, is_pytest_yield_fixture,
keyword_is_literal,
};
/// ## What it does
/// Checks for argument-free `@pytest.fixture()` decorators with or without
/// parentheses, depending on the [`lint.flake8-pytest-style.fixture-parentheses`]
/// setting.
///
/// ## Why is this bad?
/// If a `@pytest.fixture()` doesn't take any arguments, the parentheses are
/// optional.
///
/// Either removing those unnecessary parentheses _or_ requiring them for all
/// fixtures is fine, but it's best to be consistent. The rule defaults to
/// removing unnecessary parentheses, to match the documentation of the
/// official pytest projects.
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture(): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import pytest
///
///
/// @pytest.fixture
/// def my_fixture(): ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe if there's comments in the
/// `pytest.fixture` decorator.
///
/// For example, the fix would be marked as unsafe in the following case:
/// ```python
/// import pytest
///
///
/// @pytest.fixture(
/// # comment
/// # scope = "module"
/// )
/// def my_fixture(): ...
/// ```
///
/// ## Options
/// - `lint.flake8-pytest-style.fixture-parentheses`
///
/// ## References
/// - [`pytest` documentation: API Reference: Fixtures](https://docs.pytest.org/en/latest/reference/reference.html#fixtures-api)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestFixtureIncorrectParenthesesStyle {
expected: Parentheses,
actual: Parentheses,
}
impl AlwaysFixableViolation for PytestFixtureIncorrectParenthesesStyle {
#[derive_message_formats]
fn message(&self) -> String {
let PytestFixtureIncorrectParenthesesStyle { expected, actual } = self;
format!("Use `@pytest.fixture{expected}` over `@pytest.fixture{actual}`")
}
fn fix_title(&self) -> String {
let PytestFixtureIncorrectParenthesesStyle { expected, .. } = self;
match expected {
Parentheses::None => "Remove parentheses".to_string(),
Parentheses::Empty => "Add parentheses".to_string(),
}
}
}
/// ## What it does
/// Checks for `pytest.fixture` calls with positional arguments.
///
/// ## Why is this bad?
/// For clarity and consistency, prefer using keyword arguments to specify
/// fixture configuration.
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// @pytest.fixture("module")
/// def my_fixture(): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import pytest
///
///
/// @pytest.fixture(scope="module")
/// def my_fixture(): ...
/// ```
///
/// ## References
/// - [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestFixturePositionalArgs {
function: String,
}
impl Violation for PytestFixturePositionalArgs {
#[derive_message_formats]
fn message(&self) -> String {
let PytestFixturePositionalArgs { function } = self;
format!("Configuration for fixture `{function}` specified via positional args, use kwargs")
}
}
/// ## What it does
/// Checks for `pytest.fixture` calls with `scope="function"`.
///
/// ## Why is this bad?
/// `scope="function"` can be omitted, as it is the default.
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// @pytest.fixture(scope="function")
/// def my_fixture(): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture(): ...
/// ```
///
/// ## References
/// - [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestExtraneousScopeFunction;
impl AlwaysFixableViolation for PytestExtraneousScopeFunction {
#[derive_message_formats]
fn message(&self) -> String {
"`scope='function'` is implied in `@pytest.fixture()`".to_string()
}
fn fix_title(&self) -> String {
"Remove implied `scope` argument".to_string()
}
}
/// ## Removal
/// This rule has been removed because marking fixtures that do not return a value with an underscore
/// isn't a practice recommended by the pytest community.
///
/// ## What it does
/// Checks for `pytest` fixtures that do not return a value, but are not named
/// with a leading underscore.
///
/// ## Why is this bad?
/// By convention, fixtures that don't return a value should be named with a
/// leading underscore, while fixtures that do return a value should not.
///
/// This rule ignores abstract fixtures and generators.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def patch_something(mocker):
/// mocker.patch("module.object")
///
///
/// @pytest.fixture()
/// def use_context():
/// with create_context():
/// yield
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def _patch_something(mocker):
/// mocker.patch("module.object")
///
///
/// @pytest.fixture()
/// def _use_context():
/// with create_context():
/// yield
/// ```
///
/// ## References
/// - [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)
#[derive(ViolationMetadata)]
#[deprecated(note = "PT004 has been removed")]
#[violation_metadata(removed_since = "0.8.0")]
pub(crate) struct PytestMissingFixtureNameUnderscore;
#[expect(deprecated)]
impl Violation for PytestMissingFixtureNameUnderscore {
fn message(&self) -> String {
unreachable!("PT004 has been removed");
}
fn message_formats() -> &'static [&'static str] {
&["Fixture `{function}` does not return anything, add leading underscore"]
}
}
/// ## Removal
/// This rule has been removed because marking fixtures that do not return a value with an underscore
/// isn't a practice recommended by the pytest community.
///
/// ## What it does
/// Checks for `pytest` fixtures that return a value, but are named with a
/// leading underscore.
///
/// ## Why is this bad?
/// By convention, fixtures that don't return a value should be named with a
/// leading underscore, while fixtures that do return a value should not.
///
/// This rule ignores abstract fixtures.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def _some_object():
/// return SomeClass()
///
///
/// @pytest.fixture()
/// def _some_object_with_cleanup():
/// obj = SomeClass()
/// yield obj
/// obj.cleanup()
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def some_object():
/// return SomeClass()
///
///
/// @pytest.fixture()
/// def some_object_with_cleanup():
/// obj = SomeClass()
/// yield obj
/// obj.cleanup()
/// ```
///
/// ## References
/// - [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)
#[derive(ViolationMetadata)]
#[deprecated(note = "PT005 has been removed")]
#[violation_metadata(removed_since = "0.8.0")]
pub(crate) struct PytestIncorrectFixtureNameUnderscore;
#[expect(deprecated)]
impl Violation for PytestIncorrectFixtureNameUnderscore {
fn message(&self) -> String {
unreachable!("PT005 has been removed");
}
fn message_formats() -> &'static [&'static str] {
&["Fixture `{function}` returns a value, remove leading underscore"]
}
}
/// ## What it does
/// Checks for `pytest` test functions that should be decorated with
/// `@pytest.mark.usefixtures`.
///
/// ## Why is this bad?
/// In `pytest`, fixture injection is used to activate fixtures in a test
/// function.
///
/// Fixtures can be injected either by passing them as parameters to the test
/// function, or by using the `@pytest.mark.usefixtures` decorator.
///
/// If the test function depends on the fixture being activated, but does not
/// use it in the test body or otherwise rely on its return value, prefer
/// the `@pytest.mark.usefixtures` decorator, to make the dependency explicit
/// and avoid the confusion caused by unused arguments.
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// @pytest.fixture
/// def _patch_something(): ...
///
///
/// def test_foo(_patch_something): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import pytest
///
///
/// @pytest.fixture
/// def _patch_something(): ...
///
///
/// @pytest.mark.usefixtures("_patch_something")
/// def test_foo(): ...
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.mark.usefixtures`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-mark-usefixtures)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestFixtureParamWithoutValue {
name: String,
}
impl Violation for PytestFixtureParamWithoutValue {
#[derive_message_formats]
fn message(&self) -> String {
let PytestFixtureParamWithoutValue { name } = self;
format!(
"Fixture `{name}` without value is injected as parameter, use \
`@pytest.mark.usefixtures` instead"
)
}
}
/// ## What it does
/// Checks for `pytest.yield_fixture` usage.
///
/// ## Why is this bad?
/// `pytest.yield_fixture` is deprecated. `pytest.fixture` should be used instead.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.yield_fixture()
/// def my_fixture():
/// obj = SomeClass()
/// yield obj
/// obj.cleanup()
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture():
/// obj = SomeClass()
/// yield obj
/// obj.cleanup()
/// ```
///
/// ## References
/// - [`pytest` documentation: `yield_fixture` functions](https://docs.pytest.org/en/latest/yieldfixture.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestDeprecatedYieldFixture;
impl Violation for PytestDeprecatedYieldFixture {
#[derive_message_formats]
fn message(&self) -> String {
"`@pytest.yield_fixture` is deprecated, use `@pytest.fixture`".to_string()
}
}
/// ## What it does
/// Checks for unnecessary `request.addfinalizer` usages in `pytest` fixtures.
///
/// ## Why is this bad?
/// `pytest` offers two ways to perform cleanup in fixture code. The first is
/// sequential (via the `yield` statement), the second callback-based (via
/// `request.addfinalizer`).
///
/// The sequential approach is more readable and should be preferred, unless
/// the fixture uses the "factory as fixture" pattern.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture(request):
/// resource = acquire_resource()
/// request.addfinalizer(resource.release)
/// return resource
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture():
/// resource = acquire_resource()
/// yield resource
/// resource.release()
///
///
/// # "factory-as-fixture" pattern
/// @pytest.fixture()
/// def my_factory(request):
/// def create_resource(arg):
/// resource = acquire_resource(arg)
/// request.addfinalizer(resource.release)
/// return resource
///
/// return create_resource
/// ```
///
/// ## References
/// - [`pytest` documentation: Adding finalizers directly](https://docs.pytest.org/en/latest/how-to/fixtures.html#adding-finalizers-directly)
/// - [`pytest` documentation: Factories as fixtures](https://docs.pytest.org/en/latest/how-to/fixtures.html#factories-as-fixtures)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestFixtureFinalizerCallback;
impl Violation for PytestFixtureFinalizerCallback {
#[derive_message_formats]
fn message(&self) -> String {
"Use `yield` instead of `request.addfinalizer`".to_string()
}
}
/// ## What it does
/// Checks for unnecessary `yield` expressions in `pytest` fixtures.
///
/// ## Why is this bad?
/// In `pytest` fixtures, the `yield` expression should only be used for fixtures
/// that include teardown code, to clean up the fixture after the test function
/// has finished executing.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture():
/// resource = acquire_resource()
/// yield resource
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture_with_teardown():
/// resource = acquire_resource()
/// yield resource
/// resource.release()
///
///
/// @pytest.fixture()
/// def my_fixture_without_teardown():
/// resource = acquire_resource()
/// return resource
/// ```
///
/// ## References
/// - [`pytest` documentation: Teardown/Cleanup](https://docs.pytest.org/en/latest/how-to/fixtures.html#teardown-cleanup-aka-fixture-finalization)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestUselessYieldFixture {
name: String,
}
impl AlwaysFixableViolation for PytestUselessYieldFixture {
#[derive_message_formats]
fn message(&self) -> String {
let PytestUselessYieldFixture { name } = self;
format!("No teardown in fixture `{name}`, use `return` instead of `yield`")
}
fn fix_title(&self) -> String {
"Replace `yield` with `return`".to_string()
}
}
/// ## What it does
/// Checks for `pytest.mark.usefixtures` decorators applied to `pytest`
/// fixtures.
///
/// ## Why is this bad?
/// The `pytest.mark.usefixtures` decorator has no effect on `pytest` fixtures.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def a():
/// pass
///
///
/// @pytest.mark.usefixtures("a")
/// @pytest.fixture()
/// def b(a):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def a():
/// pass
///
///
/// @pytest.fixture()
/// def b(a):
/// pass
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.mark.usefixtures`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-mark-usefixtures)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestErroneousUseFixturesOnFixture;
impl AlwaysFixableViolation for PytestErroneousUseFixturesOnFixture {
#[derive_message_formats]
fn message(&self) -> String {
"`pytest.mark.usefixtures` has no effect on fixtures".to_string()
}
fn fix_title(&self) -> String {
"Remove `pytest.mark.usefixtures`".to_string()
}
}
/// ## What it does
/// Checks for unnecessary `@pytest.mark.asyncio` decorators applied to fixtures.
///
/// ## Why is this bad?
/// `pytest.mark.asyncio` is unnecessary for fixtures.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.mark.asyncio()
/// @pytest.fixture()
/// async def my_fixture():
/// return 0
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// async def my_fixture():
/// return 0
/// ```
///
/// ## References
/// - [PyPI: `pytest-asyncio`](https://pypi.org/project/pytest-asyncio/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestUnnecessaryAsyncioMarkOnFixture;
impl AlwaysFixableViolation for PytestUnnecessaryAsyncioMarkOnFixture {
#[derive_message_formats]
fn message(&self) -> String {
"`pytest.mark.asyncio` is unnecessary for fixtures".to_string()
}
fn fix_title(&self) -> String {
"Remove `pytest.mark.asyncio`".to_string()
}
}
/// Visitor that skips functions
#[derive(Debug, Default)]
struct SkipFunctionsVisitor<'a> {
has_return_with_value: bool,
has_yield_from: bool,
yield_statements: Vec<&'a Expr>,
addfinalizer_call: Option<&'a Expr>,
}
impl<'a> Visitor<'a> for SkipFunctionsVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt {
Stmt::Return(ast::StmtReturn {
value,
range: _,
node_index: _,
}) => {
if value.is_some() {
self.has_return_with_value = true;
}
}
Stmt::FunctionDef(_) => {}
_ => visitor::walk_stmt(self, stmt),
}
}
fn visit_expr(&mut self, expr: &'a Expr) {
match expr {
Expr::YieldFrom(_) => {
self.has_yield_from = true;
}
Expr::Yield(ast::ExprYield {
value,
range: _,
node_index: _,
}) => {
self.yield_statements.push(expr);
if value.is_some() {
self.has_return_with_value = true;
}
}
Expr::Call(ast::ExprCall { func, .. }) => {
if UnqualifiedName::from_expr(func)
.is_some_and(|name| matches!(name.segments(), ["request", "addfinalizer"]))
{
self.addfinalizer_call = Some(expr);
}
visitor::walk_expr(self, expr);
}
_ => {}
}
}
}
fn fixture_decorator<'a>(
decorators: &'a [Decorator],
semantic: &SemanticModel,
) -> Option<&'a Decorator> {
decorators.iter().find(|decorator| {
is_pytest_fixture(decorator, semantic) || is_pytest_yield_fixture(decorator, semantic)
})
}
fn pytest_fixture_parentheses(
checker: &Checker,
decorator: &Decorator,
fix: Fix,
expected: Parentheses,
actual: Parentheses,
) {
let mut diagnostic = checker.report_diagnostic(
PytestFixtureIncorrectParenthesesStyle { expected, actual },
decorator.range(),
);
diagnostic.set_fix(fix);
}
/// PT001, PT002, PT003
fn check_fixture_decorator(checker: &Checker, func_name: &str, decorator: &Decorator) {
match &decorator.expression {
Expr::Call(ast::ExprCall {
func: _,
arguments,
range: _,
node_index: _,
}) => {
if checker.is_rule_enabled(Rule::PytestFixtureIncorrectParenthesesStyle) {
if !checker.settings().flake8_pytest_style.fixture_parentheses
&& arguments.args.is_empty()
&& arguments.keywords.is_empty()
{
let fix = Fix::applicable_edit(
Edit::range_deletion(arguments.range()),
if checker.comment_ranges().intersects(arguments.range()) {
Applicability::Unsafe
} else {
Applicability::Safe
},
);
pytest_fixture_parentheses(
checker,
decorator,
fix,
Parentheses::None,
Parentheses::Empty,
);
}
}
if checker.is_rule_enabled(Rule::PytestFixturePositionalArgs) {
if !arguments.args.is_empty() {
checker.report_diagnostic(
PytestFixturePositionalArgs {
function: func_name.to_string(),
},
decorator.range(),
);
}
}
if checker.is_rule_enabled(Rule::PytestExtraneousScopeFunction) {
if let Some(keyword) = arguments.find_keyword("scope") {
if keyword_is_literal(keyword, "function") {
let mut diagnostic = checker
.report_diagnostic(PytestExtraneousScopeFunction, keyword.range());
diagnostic.try_set_fix(|| {
edits::remove_argument(
keyword,
arguments,
edits::Parentheses::Preserve,
checker.source(),
checker.tokens(),
)
.map(Fix::unsafe_edit)
});
}
}
}
}
_ => {
if checker.is_rule_enabled(Rule::PytestFixtureIncorrectParenthesesStyle) {
if checker.settings().flake8_pytest_style.fixture_parentheses {
let fix = Fix::safe_edit(Edit::insertion(
Parentheses::Empty.to_string(),
decorator.end(),
));
pytest_fixture_parentheses(
checker,
decorator,
fix,
Parentheses::Empty,
Parentheses::None,
);
}
}
}
}
}
/// PT022
fn check_fixture_returns(checker: &Checker, name: &str, body: &[Stmt], returns: Option<&Expr>) {
let mut visitor = SkipFunctionsVisitor::default();
for stmt in body {
visitor.visit_stmt(stmt);
}
if checker.is_rule_enabled(Rule::PytestUselessYieldFixture) {
let Some(stmt) = body.last() else {
return;
};
let Stmt::Expr(ast::StmtExpr { value, .. }) = stmt else {
return;
};
if !value.is_yield_expr() {
return;
}
if visitor.yield_statements.len() != 1 {
return;
}
let mut diagnostic = checker.report_diagnostic(
PytestUselessYieldFixture {
name: name.to_string(),
},
stmt.range(),
);
let yield_edit = Edit::range_replacement(
"return".to_string(),
TextRange::at(stmt.start(), "yield".text_len()),
);
let return_type_edit = returns.and_then(|returns| {
let ast::ExprSubscript { value, slice, .. } = returns.as_subscript_expr()?;
let ast::ExprTuple { elts, .. } = slice.as_tuple_expr()?;
let [first, ..] = elts.as_slice() else {
return None;
};
if !checker.semantic().match_typing_expr(value, "Generator") {
return None;
}
Some(Edit::range_replacement(
checker.generator().expr(first),
returns.range(),
))
});
if let Some(return_type_edit) = return_type_edit {
diagnostic.set_fix(Fix::safe_edits(yield_edit, [return_type_edit]));
} else {
diagnostic.set_fix(Fix::safe_edit(yield_edit));
}
}
}
/// PT019
fn check_test_function_args(checker: &Checker, parameters: &Parameters, decorators: &[Decorator]) {
let mut named_parametrize = FxHashSet::default();
for decorator in decorators.iter().filter(|decorator| {
UnqualifiedName::from_expr(map_callable(&decorator.expression))
.is_some_and(|name| matches!(name.segments(), ["pytest", "mark", "parametrize"]))
}) {
let Some(call_expr) = decorator.expression.as_call_expr() else {
continue;
};
let Some(first_arg) = call_expr.arguments.find_argument_value("argnames", 0) else {
continue;
};
match first_arg {
Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => {
named_parametrize.extend(
value
.to_str()
.split(',')
.map(str::trim)
.filter(|param| !param.is_empty() && param.starts_with('_')),
);
}
Expr::Name(_) => return,
Expr::List(ast::ExprList { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. })
if elts.iter().any(Expr::is_name_expr) =>
{
return;
}
Expr::List(ast::ExprList { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. }) => {
named_parametrize.extend(
elts.iter()
.filter_map(Expr::as_string_literal_expr)
.map(|param| param.value.to_str().trim())
.filter(|param| !param.is_empty() && param.starts_with('_')),
);
}
_ => {}
}
}
for parameter in parameters.iter_non_variadic_params() {
let name = parameter.name();
if name.starts_with('_') && !named_parametrize.contains(name.as_str()) {
checker.report_diagnostic(
PytestFixtureParamWithoutValue {
name: name.to_string(),
},
parameter.range(),
);
}
}
}
/// PT020
fn check_fixture_decorator_name(checker: &Checker, decorator: &Decorator) {
if is_pytest_yield_fixture(decorator, checker.semantic()) {
let mut diagnostic =
checker.report_diagnostic(PytestDeprecatedYieldFixture, decorator.range());
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
}
}
/// PT021
fn check_fixture_addfinalizer(checker: &Checker, parameters: &Parameters, body: &[Stmt]) {
if !parameters.includes("request") {
return;
}
let mut visitor = SkipFunctionsVisitor::default();
for stmt in body {
visitor.visit_stmt(stmt);
}
if let Some(addfinalizer) = visitor.addfinalizer_call {
checker.report_diagnostic(PytestFixtureFinalizerCallback, addfinalizer.range());
}
}
/// PT024, PT025
fn check_fixture_marks(checker: &Checker, decorators: &[Decorator]) {
for (expr, marker) in get_mark_decorators(decorators, checker.semantic()) {
if checker.is_rule_enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture) {
if marker == "asyncio" {
let mut diagnostic =
checker.report_diagnostic(PytestUnnecessaryAsyncioMarkOnFixture, expr.range());
let range = checker.locator().full_lines_range(expr.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(range)));
}
}
if checker.is_rule_enabled(Rule::PytestErroneousUseFixturesOnFixture) {
if marker == "usefixtures" {
let mut diagnostic =
checker.report_diagnostic(PytestErroneousUseFixturesOnFixture, expr.range());
let line_range = checker.locator().full_lines_range(expr.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(line_range)));
}
}
}
}
pub(crate) fn fixture(
checker: &Checker,
name: &str,
parameters: &Parameters,
returns: Option<&Expr>,
decorators: &[Decorator],
body: &[Stmt],
) {
let decorator = fixture_decorator(decorators, checker.semantic());
if let Some(decorator) = decorator {
if checker.is_rule_enabled(Rule::PytestFixtureIncorrectParenthesesStyle)
|| checker.is_rule_enabled(Rule::PytestFixturePositionalArgs)
|| checker.is_rule_enabled(Rule::PytestExtraneousScopeFunction)
{
check_fixture_decorator(checker, name, decorator);
}
if checker.is_rule_enabled(Rule::PytestDeprecatedYieldFixture) {
check_fixture_decorator_name(checker, decorator);
}
if checker.is_rule_enabled(Rule::PytestUselessYieldFixture)
&& !is_abstract(decorators, checker.semantic())
{
check_fixture_returns(checker, name, body, returns);
}
if checker.is_rule_enabled(Rule::PytestFixtureFinalizerCallback) {
check_fixture_addfinalizer(checker, parameters, body);
}
if checker.is_rule_enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture)
|| checker.is_rule_enabled(Rule::PytestErroneousUseFixturesOnFixture)
{
check_fixture_marks(checker, decorators);
}
}
if checker.is_rule_enabled(Rule::PytestFixtureParamWithoutValue) && name.starts_with("test_") {
check_test_function_args(checker, parameters, decorators);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/assertion.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/assertion.rs | use std::borrow::Cow;
use std::iter;
use anyhow::Result;
use anyhow::{Context, bail};
use libcst_native::{
self, Assert, BooleanOp, CompoundStatement, Expression, ParenthesizedNode, SimpleStatementLine,
SimpleWhitespace, SmallStatement, Statement, TrailingWhitespace,
};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::Truthiness;
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{
self as ast, AnyNodeRef, Arguments, BoolOp, ExceptHandler, Expr, Keyword, Stmt, UnaryOp,
};
use ruff_python_ast::{visitor, whitespace};
use ruff_python_codegen::Stylist;
use ruff_python_semantic::{Binding, BindingKind};
use ruff_source_file::LineRanges;
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::cst::helpers::negate;
use crate::cst::matchers::match_indented_block;
use crate::cst::matchers::match_module;
use crate::fix::codemods::CodegenStylist;
use crate::importer::ImportRequest;
use crate::{Edit, Fix, FixAvailability, Violation};
use super::unittest_assert::UnittestAssert;
/// ## What it does
/// Checks for assertions that combine multiple independent conditions.
///
/// ## Why is this bad?
/// Composite assertion statements are harder to debug upon failure, as the
/// failure message will not indicate which condition failed.
///
/// ## Example
/// ```python
/// def test_foo():
/// assert something and something_else
///
///
/// def test_bar():
/// assert not (something or something_else)
/// ```
///
/// Use instead:
/// ```python
/// def test_foo():
/// assert something
/// assert something_else
///
///
/// def test_bar():
/// assert not something
/// assert not something_else
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestCompositeAssertion;
impl Violation for PytestCompositeAssertion {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Assertion should be broken down into multiple parts".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Break down assertion into multiple parts".to_string())
}
}
/// ## What it does
/// Checks for `assert` statements in `except` clauses.
///
/// ## Why is this bad?
/// When testing for exceptions, `pytest.raises()` should be used instead of
/// `assert` statements in `except` clauses, as it's more explicit and
/// idiomatic. Further, `pytest.raises()` will fail if the exception is _not_
/// raised, unlike the `assert` statement.
///
/// ## Example
/// ```python
/// def test_foo():
/// try:
/// 1 / 0
/// except ZeroDivisionError as e:
/// assert e.args
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// def test_foo():
/// with pytest.raises(ZeroDivisionError) as exc_info:
/// 1 / 0
/// assert exc_info.value.args
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestAssertInExcept {
name: String,
}
impl Violation for PytestAssertInExcept {
#[derive_message_formats]
fn message(&self) -> String {
let PytestAssertInExcept { name } = self;
format!(
"Found assertion on exception `{name}` in `except` block, use `pytest.raises()` instead"
)
}
}
/// ## What it does
/// Checks for `assert` statements whose test expression is a falsy value.
///
/// ## Why is this bad?
/// `pytest.fail` conveys the intent more clearly than `assert falsy_value`.
///
/// ## Example
/// ```python
/// def test_foo():
/// if some_condition:
/// assert False, "some_condition was True"
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// def test_foo():
/// if some_condition:
/// pytest.fail("some_condition was True")
/// ...
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.fail`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fail)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestAssertAlwaysFalse;
impl Violation for PytestAssertAlwaysFalse {
#[derive_message_formats]
fn message(&self) -> String {
"Assertion always fails, replace with `pytest.fail()`".to_string()
}
}
/// ## What it does
/// Checks for uses of assertion methods from the `unittest` module.
///
/// ## Why is this bad?
/// To make use of `pytest`'s assertion rewriting, a regular `assert` statement
/// is preferred over `unittest`'s assertion methods.
///
/// ## Example
/// ```python
/// import unittest
///
///
/// class TestFoo(unittest.TestCase):
/// def test_foo(self):
/// self.assertEqual(a, b)
/// ```
///
/// Use instead:
/// ```python
/// import unittest
///
///
/// class TestFoo(unittest.TestCase):
/// def test_foo(self):
/// assert a == b
/// ```
///
/// ## References
/// - [`pytest` documentation: Assertion introspection details](https://docs.pytest.org/en/7.1.x/how-to/assert.html#assertion-introspection-details)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestUnittestAssertion {
assertion: String,
}
impl Violation for PytestUnittestAssertion {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let PytestUnittestAssertion { assertion } = self;
format!("Use a regular `assert` instead of unittest-style `{assertion}`")
}
fn fix_title(&self) -> Option<String> {
let PytestUnittestAssertion { assertion } = self;
Some(format!("Replace `{assertion}(...)` with `assert ...`"))
}
}
/// Visitor that tracks assert statements and checks if they reference
/// the exception name.
struct ExceptionHandlerVisitor<'a, 'b> {
exception_name: &'a str,
current_assert: Option<&'a Stmt>,
checker: &'a Checker<'b>,
}
impl<'a, 'b> ExceptionHandlerVisitor<'a, 'b> {
const fn new(checker: &'a Checker<'b>, exception_name: &'a str) -> Self {
Self {
exception_name,
current_assert: None,
checker,
}
}
}
impl<'a> Visitor<'a> for ExceptionHandlerVisitor<'a, '_> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt {
Stmt::Assert(_) => {
self.current_assert = Some(stmt);
visitor::walk_stmt(self, stmt);
self.current_assert = None;
}
_ => visitor::walk_stmt(self, stmt),
}
}
fn visit_expr(&mut self, expr: &'a Expr) {
match expr {
Expr::Name(ast::ExprName { id, .. }) => {
if let Some(current_assert) = self.current_assert {
if id.as_str() == self.exception_name {
self.checker.report_diagnostic(
PytestAssertInExcept {
name: id.to_string(),
},
current_assert.range(),
);
}
}
}
_ => visitor::walk_expr(self, expr),
}
}
}
fn check_assert_in_except(checker: &Checker, name: &str, body: &[Stmt]) {
// Walk body to find assert statements that reference the exception name
let mut visitor = ExceptionHandlerVisitor::new(checker, name);
for stmt in body {
visitor.visit_stmt(stmt);
}
}
/// PT009
pub(crate) fn unittest_assertion(
checker: &Checker,
expr: &Expr,
func: &Expr,
args: &[Expr],
keywords: &[Keyword],
) {
let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func else {
return;
};
let Ok(unittest_assert) = UnittestAssert::try_from(attr.as_str()) else {
return;
};
let mut diagnostic = checker.report_diagnostic(
PytestUnittestAssertion {
assertion: unittest_assert.to_string(),
},
func.range(),
);
// We're converting an expression to a statement, so avoid applying the fix if
// the assertion is part of a larger expression.
if checker.semantic().current_statement().is_expr_stmt()
&& checker.semantic().current_expression_parent().is_none()
&& !checker.comment_ranges().intersects(expr.range())
{
if let Ok(stmt) = unittest_assert.generate_assert(args, keywords) {
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().stmt(&stmt),
parenthesized_range(
expr.into(),
checker.semantic().current_statement().into(),
checker.tokens(),
)
.unwrap_or(expr.range()),
)));
}
}
}
/// ## What it does
/// Checks for uses of exception-related assertion methods from the `unittest`
/// module.
///
/// ## Why is this bad?
/// To enforce the assertion style recommended by `pytest`, `pytest.raises` is
/// preferred over the exception-related assertion methods in `unittest`, like
/// `assertRaises`.
///
/// ## Example
/// ```python
/// import unittest
///
///
/// class TestFoo(unittest.TestCase):
/// def test_foo(self):
/// with self.assertRaises(ValueError):
/// raise ValueError("foo")
/// ```
///
/// Use instead:
/// ```python
/// import unittest
/// import pytest
///
///
/// class TestFoo(unittest.TestCase):
/// def test_foo(self):
/// with pytest.raises(ValueError):
/// raise ValueError("foo")
/// ```
///
/// ## References
/// - [`pytest` documentation: Assertions about expected exceptions](https://docs.pytest.org/en/latest/how-to/assert.html#assertions-about-expected-exceptions)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.285")]
pub(crate) struct PytestUnittestRaisesAssertion {
assertion: String,
}
impl Violation for PytestUnittestRaisesAssertion {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let PytestUnittestRaisesAssertion { assertion } = self;
format!("Use `pytest.raises` instead of unittest-style `{assertion}`")
}
fn fix_title(&self) -> Option<String> {
let PytestUnittestRaisesAssertion { assertion } = self;
Some(format!("Replace `{assertion}` with `pytest.raises`"))
}
}
/// PT027
pub(crate) fn unittest_raises_assertion_call(checker: &Checker, call: &ast::ExprCall) {
// Bindings in `with` statements are handled by `unittest_raises_assertion_bindings`.
if let Stmt::With(ast::StmtWith { items, .. }) = checker.semantic().current_statement() {
let call_ref = AnyNodeRef::from(call);
if items.iter().any(|item| {
AnyNodeRef::from(&item.context_expr).ptr_eq(call_ref) && item.optional_vars.is_some()
}) {
return;
}
}
unittest_raises_assertion(call, vec![], checker);
}
/// PT027
pub(crate) fn unittest_raises_assertion_binding(checker: &Checker, binding: &Binding) {
if !matches!(binding.kind, BindingKind::WithItemVar) {
return;
}
let semantic = checker.semantic();
let Some(Stmt::With(with)) = binding.statement(semantic) else {
return;
};
let Some(Expr::Call(call)) = corresponding_context_expr(binding, with) else {
return;
};
let mut edits = vec![];
// Rewrite all references to `.exception` to `.value`:
// ```py
// # Before
// with self.assertRaises(Exception) as e:
// ...
// print(e.exception)
//
// # After
// with pytest.raises(Exception) as e:
// ...
// print(e.value)
// ```
for reference_id in binding.references() {
let reference = semantic.reference(reference_id);
let Some(node_id) = reference.expression_id() else {
return;
};
let mut ancestors = semantic.expressions(node_id).skip(1);
let Some(Expr::Attribute(ast::ExprAttribute { attr, .. })) = ancestors.next() else {
continue;
};
if attr.as_str() == "exception" {
edits.push(Edit::range_replacement("value".to_string(), attr.range));
}
}
unittest_raises_assertion(call, edits, checker);
}
fn corresponding_context_expr<'a>(binding: &Binding, with: &'a ast::StmtWith) -> Option<&'a Expr> {
with.items.iter().find_map(|item| {
let Some(optional_var) = &item.optional_vars else {
return None;
};
let Expr::Name(name) = optional_var.as_ref() else {
return None;
};
if name.range == binding.range {
Some(&item.context_expr)
} else {
None
}
})
}
fn unittest_raises_assertion(call: &ast::ExprCall, extra_edits: Vec<Edit>, checker: &Checker) {
let Expr::Attribute(ast::ExprAttribute { attr, .. }) = call.func.as_ref() else {
return;
};
if !matches!(
attr.as_str(),
"assertRaises" | "failUnlessRaises" | "assertRaisesRegex" | "assertRaisesRegexp"
) {
return;
}
let mut diagnostic = checker.report_diagnostic(
PytestUnittestRaisesAssertion {
assertion: attr.to_string(),
},
call.func.range(),
);
if !checker
.comment_ranges()
.has_comments(call, checker.source())
{
if let Some(args) = to_pytest_raises_args(checker, attr.as_str(), &call.arguments) {
diagnostic.try_set_fix(|| {
let (import_pytest_raises, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pytest", "raises"),
call.func.start(),
checker.semantic(),
)?;
let replace_call =
Edit::range_replacement(format!("{binding}({args})"), call.range());
Ok(Fix::unsafe_edits(
import_pytest_raises,
iter::once(replace_call).chain(extra_edits),
))
});
}
}
}
fn to_pytest_raises_args<'a>(
checker: &Checker<'a>,
attr: &str,
arguments: &Arguments,
) -> Option<Cow<'a, str>> {
let args = match attr {
"assertRaises" | "failUnlessRaises" => {
match (&*arguments.args, &*arguments.keywords) {
// Ex) `assertRaises(Exception)`
([arg], []) => Cow::Borrowed(checker.locator().slice(arg)),
// Ex) `assertRaises(expected_exception=Exception)`
([], [kwarg])
if kwarg
.arg
.as_ref()
.is_some_and(|id| id.as_str() == "expected_exception") =>
{
Cow::Borrowed(checker.locator().slice(kwarg.value.range()))
}
_ => return None,
}
}
"assertRaisesRegex" | "assertRaisesRegexp" => {
match (&*arguments.args, &*arguments.keywords) {
// Ex) `assertRaisesRegex(Exception, regex)`
([arg1, arg2], []) => Cow::Owned(format!(
"{}, match={}",
checker.locator().slice(arg1),
checker.locator().slice(arg2)
)),
// Ex) `assertRaisesRegex(Exception, expected_regex=regex)`
([arg], [kwarg])
if kwarg
.arg
.as_ref()
.is_some_and(|arg| arg.as_str() == "expected_regex") =>
{
Cow::Owned(format!(
"{}, match={}",
checker.locator().slice(arg),
checker.locator().slice(kwarg.value.range())
))
}
// Ex) `assertRaisesRegex(expected_exception=Exception, expected_regex=regex)`
([], [kwarg1, kwarg2])
if kwarg1
.arg
.as_ref()
.is_some_and(|id| id.as_str() == "expected_exception")
&& kwarg2
.arg
.as_ref()
.is_some_and(|id| id.as_str() == "expected_regex") =>
{
Cow::Owned(format!(
"{}, match={}",
checker.locator().slice(kwarg1.value.range()),
checker.locator().slice(kwarg2.value.range())
))
}
// Ex) `assertRaisesRegex(expected_regex=regex, expected_exception=Exception)`
([], [kwarg1, kwarg2])
if kwarg1
.arg
.as_ref()
.is_some_and(|id| id.as_str() == "expected_regex")
&& kwarg2
.arg
.as_ref()
.is_some_and(|id| id.as_str() == "expected_exception") =>
{
Cow::Owned(format!(
"{}, match={}",
checker.locator().slice(kwarg2.value.range()),
checker.locator().slice(kwarg1.value.range())
))
}
_ => return None,
}
}
_ => return None,
};
Some(args)
}
/// PT015
pub(crate) fn assert_falsy(checker: &Checker, stmt: &Stmt, test: &Expr) {
let truthiness = Truthiness::from_expr(test, |id| checker.semantic().has_builtin_binding(id));
if truthiness.into_bool() == Some(false) {
checker.report_diagnostic(PytestAssertAlwaysFalse, stmt.range());
}
}
/// PT017
pub(crate) fn assert_in_exception_handler(checker: &Checker, handlers: &[ExceptHandler]) {
for handler in handlers {
let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { name, body, .. }) =
handler;
if let Some(name) = name {
check_assert_in_except(checker, name, body);
}
}
}
#[derive(Copy, Clone)]
enum CompositionKind {
// E.g., `a or b or c`.
None,
// E.g., `a and b` or `not (a or b)`.
Simple,
// E.g., `not (a and b or c)`.
Mixed,
}
/// Check if the test expression is a composite condition, and whether it can
/// be split into multiple independent conditions.
///
/// For example, `a and b` or `not (a or b)`. The latter is equivalent to
/// `not a and not b` by De Morgan's laws.
fn is_composite_condition(test: &Expr) -> CompositionKind {
match test {
Expr::BoolOp(ast::ExprBoolOp {
op: BoolOp::And, ..
}) => {
return CompositionKind::Simple;
}
Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::Not,
operand,
range: _,
node_index: _,
}) => {
if let Expr::BoolOp(ast::ExprBoolOp {
op: BoolOp::Or,
values,
range: _,
node_index: _,
}) = operand.as_ref()
{
// Only split cases without mixed `and` and `or`.
return if values.iter().all(|expr| {
!matches!(
expr,
Expr::BoolOp(ast::ExprBoolOp {
op: BoolOp::And,
..
})
)
}) {
CompositionKind::Simple
} else {
CompositionKind::Mixed
};
}
}
_ => {}
}
CompositionKind::None
}
/// Propagate parentheses from a parent to a child expression, if necessary.
///
/// For example, when splitting:
/// ```python
/// assert (a and b ==
/// """)
/// ```
///
/// The parentheses need to be propagated to the right-most expression:
/// ```python
/// assert a
/// assert (b ==
/// "")
/// ```
fn parenthesize<'a>(expression: &Expression<'a>, parent: &Expression<'a>) -> Expression<'a> {
if matches!(
expression,
Expression::Comparison(_)
| Expression::UnaryOperation(_)
| Expression::BinaryOperation(_)
| Expression::BooleanOperation(_)
| Expression::Attribute(_)
| Expression::Tuple(_)
| Expression::Call(_)
| Expression::GeneratorExp(_)
| Expression::ListComp(_)
| Expression::SetComp(_)
| Expression::DictComp(_)
| Expression::List(_)
| Expression::Set(_)
| Expression::Dict(_)
| Expression::Subscript(_)
| Expression::StarredElement(_)
| Expression::IfExp(_)
| Expression::Lambda(_)
| Expression::Yield(_)
| Expression::Await(_)
| Expression::ConcatenatedString(_)
| Expression::FormattedString(_)
| Expression::NamedExpr(_)
) {
if let (Some(left), Some(right)) = (parent.lpar().first(), parent.rpar().first()) {
return expression.clone().with_parens(left.clone(), right.clone());
}
}
expression.clone()
}
/// Replace composite condition `assert a == "hello" and b == "world"` with two statements
/// `assert a == "hello"` and `assert b == "world"`.
fn fix_composite_condition(stmt: &Stmt, locator: &Locator, stylist: &Stylist) -> Result<Edit> {
// Infer the indentation of the outer block.
let outer_indent = whitespace::indentation(locator.contents(), stmt)
.context("Unable to fix multiline statement")?;
// Extract the module text.
let contents = locator.lines_str(stmt.range());
// If the block is indented, "embed" it in a function definition, to preserve
// indentation while retaining valid source code. (We'll strip the prefix later
// on.)
let module_text = if outer_indent.is_empty() {
Cow::Borrowed(contents)
} else {
Cow::Owned(format!(
"def f():{}{contents}",
stylist.line_ending().as_str()
))
};
// Parse the CST.
let mut tree = match_module(&module_text)?;
// Extract the assert statement.
let statements = if outer_indent.is_empty() {
&mut tree.body
} else {
let [Statement::Compound(CompoundStatement::FunctionDef(embedding))] = &mut *tree.body
else {
bail!("Expected statement to be embedded in a function definition")
};
let indented_block = match_indented_block(&mut embedding.body)?;
indented_block.indent = Some(outer_indent);
&mut indented_block.body
};
let [Statement::Simple(simple_statement_line)] = statements.as_slice() else {
bail!("Expected one simple statement")
};
let [SmallStatement::Assert(assert_statement)] = simple_statement_line.body.as_slice() else {
bail!("Expected simple statement to be an assert")
};
// Extract the individual conditions.
let mut conditions: Vec<Expression> = Vec::with_capacity(2);
match &assert_statement.test {
Expression::UnaryOperation(op) => {
if matches!(op.operator, libcst_native::UnaryOp::Not { .. }) {
if let Expression::BooleanOperation(boolean_operation) = &*op.expression {
if matches!(boolean_operation.operator, BooleanOp::Or { .. }) {
conditions.push(negate(&parenthesize(
&boolean_operation.left,
&op.expression,
)));
conditions.push(negate(&parenthesize(
&boolean_operation.right,
&op.expression,
)));
} else {
bail!("Expected assert statement to be a composite condition");
}
} else {
bail!("Expected assert statement to be a composite condition");
}
}
}
Expression::BooleanOperation(op) => {
if matches!(op.operator, BooleanOp::And { .. }) {
conditions.push(parenthesize(&op.left, &assert_statement.test));
conditions.push(parenthesize(&op.right, &assert_statement.test));
} else {
bail!("Expected assert statement to be a composite condition");
}
}
_ => bail!("Expected assert statement to be a composite condition"),
}
// For each condition, create an `assert condition` statement.
statements.clear();
for condition in conditions {
statements.push(Statement::Simple(SimpleStatementLine {
body: vec![SmallStatement::Assert(Assert {
test: condition,
msg: None,
comma: None,
whitespace_after_assert: SimpleWhitespace(" "),
semicolon: None,
})],
leading_lines: Vec::default(),
trailing_whitespace: TrailingWhitespace::default(),
}));
}
// Reconstruct and reformat the code.
let module_text = tree.codegen_stylist(stylist);
let contents = if outer_indent.is_empty() {
module_text
} else {
module_text
.strip_prefix(&format!("def f():{}", stylist.line_ending().as_str()))
.unwrap()
.to_string()
};
let range = locator.full_lines_range(stmt.range());
Ok(Edit::range_replacement(contents, range))
}
/// PT018
pub(crate) fn composite_condition(checker: &Checker, stmt: &Stmt, test: &Expr, msg: Option<&Expr>) {
let composite = is_composite_condition(test);
if matches!(composite, CompositionKind::Simple | CompositionKind::Mixed) {
let mut diagnostic = checker.report_diagnostic(PytestCompositeAssertion, stmt.range());
if matches!(composite, CompositionKind::Simple)
&& msg.is_none()
&& !checker.comment_ranges().intersects(stmt.range())
&& !checker
.indexer()
.in_multi_statement_line(stmt, checker.source())
{
diagnostic.try_set_fix(|| {
fix_composite_condition(stmt, checker.locator(), checker.stylist())
.map(Fix::unsafe_edit)
});
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/parametrize.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/parametrize.rs | use rustc_hash::{FxBuildHasher, FxHashMap};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::token::{Tokens, parenthesized_range};
use ruff_python_ast::{self as ast, Expr, ExprCall, ExprContext, StringLiteralFlags};
use ruff_python_codegen::Generator;
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use crate::{Edit, Fix, FixAvailability, Violation};
use crate::rules::flake8_pytest_style::helpers::{is_pytest_parametrize, split_names};
use crate::rules::flake8_pytest_style::types;
/// ## What it does
/// Checks for the type of parameter names passed to `pytest.mark.parametrize`.
///
/// ## Why is this bad?
/// The `argnames` argument of `pytest.mark.parametrize` takes a string or
/// a sequence of strings. For a single parameter, it's preferable to use a
/// string. For multiple parameters, it's preferable to use the style
/// configured via the [`lint.flake8-pytest-style.parametrize-names-type`] setting.
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// # single parameter, always expecting string
/// @pytest.mark.parametrize(("param",), [1, 2, 3])
/// def test_foo(param): ...
///
///
/// # multiple parameters, expecting tuple
/// @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)])
/// def test_bar(param1, param2): ...
///
///
/// # multiple parameters, expecting tuple
/// @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)])
/// def test_baz(param1, param2): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize("param", [1, 2, 3])
/// def test_foo(param): ...
///
///
/// @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)])
/// def test_bar(param1, param2): ...
/// ```
///
/// ## Options
/// - `lint.flake8-pytest-style.parametrize-names-type`
///
/// ## References
/// - [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestParametrizeNamesWrongType {
single_argument: bool,
expected: types::ParametrizeNameType,
}
impl Violation for PytestParametrizeNamesWrongType {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let PytestParametrizeNamesWrongType {
single_argument,
expected,
} = self;
let expected_string = {
if *single_argument {
"`str`".to_string()
} else {
match expected {
types::ParametrizeNameType::Csv => format!("a {expected}"),
types::ParametrizeNameType::Tuple | types::ParametrizeNameType::List => {
format!("`{expected}`")
}
}
}
};
format!(
"Wrong type passed to first argument of `pytest.mark.parametrize`; expected {expected_string}"
)
}
fn fix_title(&self) -> Option<String> {
let PytestParametrizeNamesWrongType {
single_argument,
expected,
} = self;
let expected_string = {
if *single_argument {
"string".to_string()
} else {
match expected {
types::ParametrizeNameType::Csv => format!("{expected}"),
types::ParametrizeNameType::Tuple | types::ParametrizeNameType::List => {
format!("`{expected}`")
}
}
}
};
Some(format!("Use a {expected_string} for the first argument"))
}
}
/// ## What it does
/// Checks for the type of parameter values passed to `pytest.mark.parametrize`.
///
/// ## Why is this bad?
/// The `argvalues` argument of `pytest.mark.parametrize` takes an iterator of
/// parameter values, which can be provided as lists or tuples.
///
/// To aid in readability, it's recommended to use a consistent style for the
/// list of values rows, and, in the case of multiple parameters, for each row
/// of values.
///
/// The style for the list of values rows can be configured via the
/// [`lint.flake8-pytest-style.parametrize-values-type`] setting, while the
/// style for each row of values can be configured via the
/// [`lint.flake8-pytest-style.parametrize-values-row-type`] setting.
///
/// For example, [`lint.flake8-pytest-style.parametrize-values-type`] will lead to
/// the following expectations:
///
/// - `tuple`: `@pytest.mark.parametrize("value", ("a", "b", "c"))`
/// - `list`: `@pytest.mark.parametrize("value", ["a", "b", "c"])`
///
/// Similarly, [`lint.flake8-pytest-style.parametrize-values-row-type`] will lead to
/// the following expectations:
///
/// - `tuple`: `@pytest.mark.parametrize(("key", "value"), [("a", "b"), ("c", "d")])`
/// - `list`: `@pytest.mark.parametrize(("key", "value"), [["a", "b"], ["c", "d"]])`
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// # expected list, got tuple
/// @pytest.mark.parametrize("param", (1, 2))
/// def test_foo(param): ...
///
///
/// # expected top-level list, got tuple
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// (
/// (1, 2),
/// (3, 4),
/// ),
/// )
/// def test_bar(param1, param2): ...
///
///
/// # expected individual rows to be tuples, got lists
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// [
/// [1, 2],
/// [3, 4],
/// ],
/// )
/// def test_baz(param1, param2): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize("param", [1, 2, 3])
/// def test_foo(param): ...
///
///
/// @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)])
/// def test_bar(param1, param2): ...
/// ```
///
/// ## Options
/// - `lint.flake8-pytest-style.parametrize-values-type`
/// - `lint.flake8-pytest-style.parametrize-values-row-type`
///
/// ## References
/// - [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestParametrizeValuesWrongType {
values: types::ParametrizeValuesType,
row: types::ParametrizeValuesRowType,
}
impl Violation for PytestParametrizeValuesWrongType {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let PytestParametrizeValuesWrongType { values, row } = self;
format!("Wrong values type in `pytest.mark.parametrize` expected `{values}` of `{row}`")
}
fn fix_title(&self) -> Option<String> {
let PytestParametrizeValuesWrongType { values, row } = self;
Some(format!("Use `{values}` of `{row}` for parameter values"))
}
}
/// ## What it does
/// Checks for duplicate test cases in `pytest.mark.parametrize`.
///
/// ## Why is this bad?
/// Duplicate test cases are redundant and should be removed.
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// [
/// (1, 2),
/// (1, 2),
/// ],
/// )
/// def test_foo(param1, param2): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import pytest
///
///
/// @pytest.mark.parametrize(
/// ("param1", "param2"),
/// [
/// (1, 2),
/// ],
/// )
/// def test_foo(param1, param2): ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as tests that rely on mutable global
/// state may be affected by removing duplicate test cases.
///
/// ## References
/// - [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.285")]
pub(crate) struct PytestDuplicateParametrizeTestCases {
index: usize,
}
impl Violation for PytestDuplicateParametrizeTestCases {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let PytestDuplicateParametrizeTestCases { index } = self;
format!("Duplicate of test case at index {index} in `pytest.mark.parametrize`")
}
fn fix_title(&self) -> Option<String> {
Some("Remove duplicate test case".to_string())
}
}
fn elts_to_csv(elts: &[Expr], generator: Generator, flags: StringLiteralFlags) -> Option<String> {
if !elts.iter().all(Expr::is_string_literal_expr) {
return None;
}
let node = Expr::from(ast::StringLiteral {
value: elts
.iter()
.fold(String::new(), |mut acc, elt| {
if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = elt {
if !acc.is_empty() {
acc.push_str(", ");
}
acc.push_str(value.to_str());
}
acc
})
.into_boxed_str(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
flags,
});
Some(generator.expr(&node))
}
/// Returns the range of the `name` argument of `@pytest.mark.parametrize`.
///
/// This accounts for parenthesized expressions. For example, the following code
/// will return the range marked with `^`:
/// ```python
/// @pytest.mark.parametrize(("x"), [(1, 2)])
/// # ^^^^^
/// def test(a, b):
/// ...
/// ```
///
/// This method assumes that the first argument is a string.
fn get_parametrize_name_range(call: &ExprCall, expr: &Expr, tokens: &Tokens) -> Option<TextRange> {
parenthesized_range(expr.into(), (&call.arguments).into(), tokens)
}
/// PT006
fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr) {
let names_type = checker
.settings()
.flake8_pytest_style
.parametrize_names_type;
match expr {
Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => {
let names = split_names(value.to_str());
if names.len() > 1 {
match names_type {
types::ParametrizeNameType::Tuple => {
let name_range = get_parametrize_name_range(call, expr, checker.tokens())
.unwrap_or(expr.range());
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
name_range,
);
let node = Expr::Tuple(ast::ExprTuple {
elts: names
.iter()
.map(|name| {
Expr::from(ast::StringLiteral {
value: Box::from(*name),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
flags: checker.default_string_flags(),
})
})
.collect(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: true,
});
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("({})", checker.generator().expr(&node)),
name_range,
)));
}
types::ParametrizeNameType::List => {
let name_range = get_parametrize_name_range(call, expr, checker.tokens())
.unwrap_or(expr.range());
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
name_range,
);
let node = Expr::List(ast::ExprList {
elts: names
.iter()
.map(|name| {
Expr::from(ast::StringLiteral {
value: Box::from(*name),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
flags: checker.default_string_flags(),
})
})
.collect(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&node),
name_range,
)));
}
types::ParametrizeNameType::Csv => {}
}
}
}
Expr::Tuple(ast::ExprTuple { elts, .. }) => {
if elts.len() == 1 {
handle_single_name(checker, expr, &elts[0], argvalues);
} else {
match names_type {
types::ParametrizeNameType::Tuple => {}
types::ParametrizeNameType::List => {
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
expr.range(),
);
let node = Expr::List(ast::ExprList {
elts: elts.clone(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&node),
expr.range(),
)));
}
types::ParametrizeNameType::Csv => {
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
expr.range(),
);
if let Some(content) =
elts_to_csv(elts, checker.generator(), checker.default_string_flags())
{
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
content,
expr.range(),
)));
}
}
}
}
}
Expr::List(ast::ExprList { elts, .. }) => {
if elts.len() == 1 {
handle_single_name(checker, expr, &elts[0], argvalues);
} else {
match names_type {
types::ParametrizeNameType::List => {}
types::ParametrizeNameType::Tuple => {
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
expr.range(),
);
let node = Expr::Tuple(ast::ExprTuple {
elts: elts.clone(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: true,
});
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("({})", checker.generator().expr(&node)),
expr.range(),
)));
}
types::ParametrizeNameType::Csv => {
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeNamesWrongType {
single_argument: false,
expected: names_type,
},
expr.range(),
);
if let Some(content) =
elts_to_csv(elts, checker.generator(), checker.default_string_flags())
{
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
content,
expr.range(),
)));
}
}
}
}
}
_ => {}
}
}
/// PT007
fn check_values(checker: &Checker, names: &Expr, values: &Expr) {
let values_type = checker
.settings()
.flake8_pytest_style
.parametrize_values_type;
let values_row_type = checker
.settings()
.flake8_pytest_style
.parametrize_values_row_type;
let is_multi_named = if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &names {
split_names(value.to_str()).len() > 1
} else {
true
};
match values {
Expr::List(ast::ExprList { elts, .. }) => {
if values_type != types::ParametrizeValuesType::List {
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeValuesWrongType {
values: values_type,
row: values_row_type,
},
values.range(),
);
diagnostic.set_fix({
// Determine whether the last element has a trailing comma. Single-element
// tuples _require_ a trailing comma, so this is a single-element list
// _without_ a trailing comma, we need to insert one.
let needs_trailing_comma = if let [item] = elts.as_slice() {
SimpleTokenizer::new(
checker.locator().contents(),
TextRange::new(item.end(), values.end()),
)
.all(|token| token.kind != SimpleTokenKind::Comma)
} else {
false
};
// Replace `[` with `(`.
let values_start = Edit::replacement(
"(".into(),
values.start(),
values.start() + TextSize::from(1),
);
// Replace `]` with `)` or `,)`.
let values_end = Edit::replacement(
if needs_trailing_comma {
",)".into()
} else {
")".into()
},
values.end() - TextSize::from(1),
values.end(),
);
Fix::unsafe_edits(values_start, [values_end])
});
}
if is_multi_named {
handle_value_rows(checker, elts, values_type, values_row_type);
}
}
Expr::Tuple(ast::ExprTuple { elts, .. }) => {
if values_type != types::ParametrizeValuesType::Tuple {
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeValuesWrongType {
values: values_type,
row: values_row_type,
},
values.range(),
);
diagnostic.set_fix({
// Determine whether a trailing comma is present due to the _requirement_
// that a single-element tuple must have a trailing comma, e.g., `(1,)`.
//
// If the trailing comma is on its own line, we intentionally ignore it,
// since the expression is already split over multiple lines, as in:
// ```python
// @pytest.mark.parametrize(
// (
// "x",
// ),
// )
// ```
let has_trailing_comma = elts.len() == 1
&& checker.locator().up_to(values.end()).chars().rev().nth(1) == Some(',');
// Replace `(` with `[`.
let values_start = Edit::replacement(
"[".into(),
values.start(),
values.start() + TextSize::from(1),
);
// Replace `)` or `,)` with `]`.
let start = if has_trailing_comma {
values.end() - TextSize::from(2)
} else {
values.end() - TextSize::from(1)
};
let values_end = Edit::replacement("]".into(), start, values.end());
Fix::unsafe_edits(values_start, [values_end])
});
}
if is_multi_named {
handle_value_rows(checker, elts, values_type, values_row_type);
}
}
_ => {}
}
}
/// Given an element in a list, return the comma that follows it:
/// ```python
/// @pytest.mark.parametrize(
/// "x",
/// [.., (elt), ..],
/// ^^^^^
/// Tokenize this range to locate the comma.
/// )
/// ```
fn trailing_comma(element: &Expr, source: &str, max_index: TextSize) -> TextSize {
for token in SimpleTokenizer::starts_at(element.end(), source) {
if matches!(token.kind, SimpleTokenKind::Comma) {
return token.start();
} else if token.start() >= max_index {
return max_index;
}
}
max_index
}
/// PT014
fn check_duplicates(checker: &Checker, values: &Expr) {
let (Expr::List(ast::ExprList { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. })) =
values
else {
return;
};
let mut seen: FxHashMap<ComparableExpr, usize> =
FxHashMap::with_capacity_and_hasher(elts.len(), FxBuildHasher);
let mut prev = None;
for (index, element) in elts.iter().enumerate() {
let expr = ComparableExpr::from(element);
seen.entry(expr)
.and_modify(|index| {
let mut diagnostic = checker.report_diagnostic(
PytestDuplicateParametrizeTestCases { index: *index },
element.range(),
);
if let Some(prev) = prev {
let values_end = values.end() - TextSize::new(1);
let previous_end =
trailing_comma(prev, checker.locator().contents(), values_end);
let element_end =
trailing_comma(element, checker.locator().contents(), values_end);
let deletion_range = TextRange::new(previous_end, element_end);
if !checker.comment_ranges().intersects(deletion_range) {
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_deletion(deletion_range)));
}
}
})
.or_insert(index);
prev = Some(element);
}
}
fn handle_single_name(checker: &Checker, argnames: &Expr, value: &Expr, argvalues: &Expr) {
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeNamesWrongType {
single_argument: true,
expected: types::ParametrizeNameType::Csv,
},
argnames.range(),
);
// If `argnames` and all items in `argvalues` are single-element sequences,
// they all should be unpacked. Here's an example:
//
// ```python
// @pytest.mark.parametrize(("x",), [(1,), (2,)])
// def test_foo(x):
// assert isinstance(x, int)
// ```
//
// The code above should be transformed into:
//
// ```python
// @pytest.mark.parametrize("x", [1, 2])
// def test_foo(x):
// assert isinstance(x, int)
// ```
//
// Only unpacking `argnames` would break the test:
//
// ```python
// @pytest.mark.parametrize("x", [(1,), (2,)])
// def test_foo(x):
// assert isinstance(x, int) # fails because `x` is a tuple, not an int
// ```
let argvalues_edits = unpack_single_element_items(checker, argvalues);
let argnames_edit = Edit::range_replacement(checker.generator().expr(value), argnames.range());
let fix = if checker.comment_ranges().intersects(argnames_edit.range())
|| argvalues_edits
.iter()
.any(|edit| checker.comment_ranges().intersects(edit.range()))
{
Fix::unsafe_edits(argnames_edit, argvalues_edits)
} else {
Fix::safe_edits(argnames_edit, argvalues_edits)
};
diagnostic.set_fix(fix);
}
/// Generate [`Edit`]s to unpack single-element lists or tuples in the given [`Expr`].
/// For instance, `[(1,) (2,)]` will be transformed into `[1, 2]`.
fn unpack_single_element_items(checker: &Checker, expr: &Expr) -> Vec<Edit> {
let (Expr::List(ast::ExprList { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. })) = expr
else {
return vec![];
};
let mut edits = Vec::with_capacity(elts.len());
for value in elts {
let (Expr::List(ast::ExprList { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. })) =
value
else {
return vec![];
};
let [elt] = elts.as_slice() else {
return vec![];
};
if matches!(elt, Expr::Starred(_)) {
return vec![];
}
edits.push(Edit::range_replacement(
checker.generator().expr(elt),
value.range(),
));
}
edits
}
fn handle_value_rows(
checker: &Checker,
elts: &[Expr],
values_type: types::ParametrizeValuesType,
values_row_type: types::ParametrizeValuesRowType,
) {
for elt in elts {
match elt {
Expr::Tuple(ast::ExprTuple { elts, .. }) => {
if values_row_type != types::ParametrizeValuesRowType::Tuple {
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeValuesWrongType {
values: values_type,
row: values_row_type,
},
elt.range(),
);
diagnostic.set_fix({
// Determine whether a trailing comma is present due to the _requirement_
// that a single-element tuple must have a trailing comma, e.g., `(1,)`.
//
// If the trailing comma is on its own line, we intentionally ignore it,
// since the expression is already split over multiple lines, as in:
// ```python
// @pytest.mark.parametrize(
// (
// "x",
// ),
// )
// ```
let has_trailing_comma = elts.len() == 1
&& checker.locator().up_to(elt.end()).chars().rev().nth(1) == Some(',');
// Replace `(` with `[`.
let elt_start = Edit::replacement(
"[".into(),
elt.start(),
elt.start() + TextSize::from(1),
);
// Replace `)` or `,)` with `]`.
let start = if has_trailing_comma {
elt.end() - TextSize::from(2)
} else {
elt.end() - TextSize::from(1)
};
let elt_end = Edit::replacement("]".into(), start, elt.end());
Fix::unsafe_edits(elt_start, [elt_end])
});
}
}
Expr::List(ast::ExprList { elts, .. }) => {
if values_row_type != types::ParametrizeValuesRowType::List {
let mut diagnostic = checker.report_diagnostic(
PytestParametrizeValuesWrongType {
values: values_type,
row: values_row_type,
},
elt.range(),
);
diagnostic.set_fix({
// Determine whether the last element has a trailing comma. Single-element
// tuples _require_ a trailing comma, so this is a single-element list
// _without_ a trailing comma, we need to insert one.
let needs_trailing_comma = if let [item] = elts.as_slice() {
SimpleTokenizer::new(
checker.locator().contents(),
TextRange::new(item.end(), elt.end()),
)
.all(|token| token.kind != SimpleTokenKind::Comma)
} else {
false
};
// Replace `[` with `(`.
let elt_start = Edit::replacement(
"(".into(),
elt.start(),
elt.start() + TextSize::from(1),
);
// Replace `]` with `)` or `,)`.
let elt_end = Edit::replacement(
if needs_trailing_comma {
",)".into()
} else {
")".into()
},
elt.end() - TextSize::from(1),
elt.end(),
);
Fix::unsafe_edits(elt_start, [elt_end])
});
}
}
_ => {}
}
}
}
pub(crate) fn parametrize(checker: &Checker, call: &ExprCall) {
if !is_pytest_parametrize(call, checker.semantic()) {
return;
}
if checker.is_rule_enabled(Rule::PytestParametrizeNamesWrongType) {
let names = call.arguments.find_argument_value("argnames", 0);
let values = call.arguments.find_argument_value("argvalues", 1);
if let (Some(names), Some(values)) = (names, values) {
check_names(checker, call, names, values);
}
}
if checker.is_rule_enabled(Rule::PytestParametrizeValuesWrongType) {
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | true |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/mod.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/mod.rs | pub(crate) use assertion::*;
pub(crate) use fail::*;
pub(crate) use fixture::*;
pub(crate) use imports::*;
pub(crate) use marks::*;
pub(crate) use parametrize::*;
pub(crate) use patch::*;
pub(crate) use raises::*;
pub(crate) use test_functions::*;
pub(crate) use warns::*;
mod assertion;
mod fail;
mod fixture;
mod imports;
mod marks;
mod parametrize;
mod patch;
mod raises;
mod test_functions;
mod unittest_assert;
mod warns;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/marks.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/marks.rs | use ruff_diagnostics::Applicability;
use ruff_python_ast::{self as ast, Arguments, Decorator, Expr};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::rules::flake8_pytest_style::helpers::{Parentheses, get_mark_decorators};
/// ## What it does
/// Checks for argument-free `@pytest.mark.<marker>()` decorators with or
/// without parentheses, depending on the [`lint.flake8-pytest-style.mark-parentheses`]
/// setting.
///
/// The rule defaults to removing unnecessary parentheses,
/// to match the documentation of the official pytest projects.
///
/// ## Why is this bad?
/// If a `@pytest.mark.<marker>()` doesn't take any arguments, the parentheses are
/// optional.
///
/// Either removing those unnecessary parentheses _or_ requiring them for all
/// fixtures is fine, but it's best to be consistent.
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// @pytest.mark.foo()
/// def test_something(): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import pytest
///
///
/// @pytest.mark.foo
/// def test_something(): ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe if there's comments in the
/// `pytest.mark.<marker>` decorator.
/// ```python
/// import pytest
///
///
/// @pytest.mark.foo(
/// # comment
/// )
/// def test_something(): ...
/// ```
///
/// ## Options
/// - `lint.flake8-pytest-style.mark-parentheses`
///
/// ## References
/// - [`pytest` documentation: Marks](https://docs.pytest.org/en/latest/reference/reference.html#marks)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestIncorrectMarkParenthesesStyle {
mark_name: String,
expected_parens: Parentheses,
actual_parens: Parentheses,
}
impl AlwaysFixableViolation for PytestIncorrectMarkParenthesesStyle {
#[derive_message_formats]
fn message(&self) -> String {
let PytestIncorrectMarkParenthesesStyle {
mark_name,
expected_parens,
actual_parens,
} = self;
format!(
"Use `@pytest.mark.{mark_name}{expected_parens}` over \
`@pytest.mark.{mark_name}{actual_parens}`"
)
}
fn fix_title(&self) -> String {
match &self.expected_parens {
Parentheses::None => "Remove parentheses".to_string(),
Parentheses::Empty => "Add parentheses".to_string(),
}
}
}
/// ## What it does
/// Checks for `@pytest.mark.usefixtures()` decorators that aren't passed any
/// arguments.
///
/// ## Why is this bad?
/// A `@pytest.mark.usefixtures()` decorator that isn't passed any arguments is
/// useless and should be removed.
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// @pytest.mark.usefixtures()
/// def test_something(): ...
/// ```
///
/// Use instead:
///
/// ```python
/// def test_something(): ...
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.mark.usefixtures`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-mark-usefixtures)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestUseFixturesWithoutParameters;
impl AlwaysFixableViolation for PytestUseFixturesWithoutParameters {
#[derive_message_formats]
fn message(&self) -> String {
"Useless `pytest.mark.usefixtures` without parameters".to_string()
}
fn fix_title(&self) -> String {
"Remove `usefixtures` decorator or pass parameters".to_string()
}
}
fn pytest_mark_parentheses(
checker: &Checker,
decorator: &Decorator,
marker: &str,
fix: Fix,
preferred: Parentheses,
actual: Parentheses,
) {
let mut diagnostic = checker.report_diagnostic(
PytestIncorrectMarkParenthesesStyle {
mark_name: marker.to_string(),
expected_parens: preferred,
actual_parens: actual,
},
decorator.range(),
);
diagnostic.set_fix(fix);
}
fn check_mark_parentheses(checker: &Checker, decorator: &Decorator, marker: &str) {
match &decorator.expression {
Expr::Call(ast::ExprCall {
func: _,
arguments,
range: _,
node_index: _,
}) => {
if !checker.settings().flake8_pytest_style.mark_parentheses
&& arguments.args.is_empty()
&& arguments.keywords.is_empty()
{
let fix = Fix::applicable_edit(
Edit::range_deletion(arguments.range()),
if checker.comment_ranges().intersects(arguments.range()) {
Applicability::Unsafe
} else {
Applicability::Safe
},
);
pytest_mark_parentheses(
checker,
decorator,
marker,
fix,
Parentheses::None,
Parentheses::Empty,
);
}
}
_ => {
if checker.settings().flake8_pytest_style.mark_parentheses {
let fix = Fix::safe_edit(Edit::insertion(
Parentheses::Empty.to_string(),
decorator.end(),
));
pytest_mark_parentheses(
checker,
decorator,
marker,
fix,
Parentheses::Empty,
Parentheses::None,
);
}
}
}
}
fn check_useless_usefixtures(checker: &Checker, decorator: &Decorator, marker: &str) {
if marker != "usefixtures" {
return;
}
match &decorator.expression {
// @pytest.mark.usefixtures
Expr::Attribute(..) => {}
// @pytest.mark.usefixtures(...)
Expr::Call(ast::ExprCall {
arguments: Arguments { args, keywords, .. },
..
}) => {
if !args.is_empty() || !keywords.is_empty() {
return;
}
}
_ => return,
}
let mut diagnostic =
checker.report_diagnostic(PytestUseFixturesWithoutParameters, decorator.range());
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_deletion(decorator.range())));
}
/// PT023, PT026
pub(crate) fn marks(checker: &Checker, decorators: &[Decorator]) {
let enforce_parentheses = checker.is_rule_enabled(Rule::PytestIncorrectMarkParenthesesStyle);
let enforce_useless_usefixtures =
checker.is_rule_enabled(Rule::PytestUseFixturesWithoutParameters);
for (decorator, marker) in get_mark_decorators(decorators, checker.semantic()) {
if enforce_parentheses {
check_mark_parentheses(checker, decorator, marker);
}
if enforce_useless_usefixtures {
check_useless_usefixtures(checker, decorator, marker);
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_pytest_style/rules/patch.rs | crates/ruff_linter/src/rules/flake8_pytest_style/rules/patch.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::UnqualifiedName;
use ruff_python_ast::visitor;
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{self as ast, Expr, Parameters};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for mocked calls that use a dummy `lambda` function instead of
/// `return_value`.
///
/// ## Why is this bad?
/// When patching calls, an explicit `return_value` better conveys the intent
/// than a `lambda` function, assuming the `lambda` does not use the arguments
/// passed to it.
///
/// `return_value` is also robust to changes in the patched function's
/// signature, and enables additional assertions to verify behavior. For
/// example, `return_value` allows for verification of the number of calls or
/// the arguments passed to the patched function via `assert_called_once_with`
/// and related methods.
///
/// ## Example
/// ```python
/// def test_foo(mocker):
/// mocker.patch("module.target", lambda x, y: 7)
/// ```
///
/// Use instead:
/// ```python
/// def test_foo(mocker):
/// mocker.patch("module.target", return_value=7)
///
/// # If the lambda makes use of the arguments, no diagnostic is emitted.
/// mocker.patch("module.other_target", lambda x, y: x)
/// ```
///
/// ## References
/// - [Python documentation: `unittest.mock.patch`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch)
/// - [PyPI: `pytest-mock`](https://pypi.org/project/pytest-mock/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct PytestPatchWithLambda;
impl Violation for PytestPatchWithLambda {
#[derive_message_formats]
fn message(&self) -> String {
"Use `return_value=` instead of patching with `lambda`".to_string()
}
}
/// Visitor that checks references the argument names in the lambda body.
#[derive(Debug)]
struct LambdaBodyVisitor<'a> {
parameters: &'a Parameters,
uses_args: bool,
}
impl<'a> Visitor<'a> for LambdaBodyVisitor<'a> {
fn visit_expr(&mut self, expr: &'a Expr) {
match expr {
Expr::Name(ast::ExprName { id, .. }) => {
if self.parameters.includes(id) {
self.uses_args = true;
}
}
_ => {
if !self.uses_args {
visitor::walk_expr(self, expr);
}
}
}
}
}
fn check_patch_call(checker: &Checker, call: &ast::ExprCall, index: usize) {
if call.arguments.find_keyword("return_value").is_some() {
return;
}
let Some(ast::ExprLambda {
parameters,
body,
range: _,
node_index: _,
}) = call
.arguments
.find_argument_value("new", index)
.and_then(|expr| expr.as_lambda_expr())
else {
return;
};
// Walk the lambda body. If the lambda uses the arguments, then it's valid.
if let Some(parameters) = parameters {
let mut visitor = LambdaBodyVisitor {
parameters,
uses_args: false,
};
visitor.visit_expr(body);
if visitor.uses_args {
return;
}
}
checker.report_diagnostic(PytestPatchWithLambda, call.func.range());
}
/// PT008
pub(crate) fn patch_with_lambda(checker: &Checker, call: &ast::ExprCall) {
let Some(name) = UnqualifiedName::from_expr(&call.func) else {
return;
};
if matches!(
name.segments(),
[
"mocker"
| "class_mocker"
| "module_mocker"
| "package_mocker"
| "session_mocker"
| "mock",
"patch"
] | ["unittest", "mock", "patch"]
) {
check_patch_call(checker, call, 1);
} else if matches!(
name.segments(),
[
"mocker"
| "class_mocker"
| "module_mocker"
| "package_mocker"
| "session_mocker"
| "mock",
"patch",
"object"
] | ["unittest", "mock", "patch", "object"]
) {
check_patch_call(checker, call, 2);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/categorize.rs | crates/ruff_linter/src/rules/isort/categorize.rs | use std::collections::BTreeMap;
use std::fmt;
use std::iter;
use std::path::{Path, PathBuf};
use log::debug;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use strum_macros::EnumIter;
use crate::package::PackageRoot;
use crate::warn_user_once;
use ruff_macros::CacheKey;
use ruff_python_ast::PythonVersion;
use ruff_python_stdlib::sys::is_known_standard_library;
use super::types::{ImportBlock, Importable};
#[derive(
Debug,
PartialOrd,
Ord,
PartialEq,
Eq,
Copy,
Clone,
Hash,
Serialize,
Deserialize,
CacheKey,
EnumIter,
)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum ImportType {
Future,
StandardLibrary,
ThirdParty,
FirstParty,
LocalFolder,
}
impl fmt::Display for ImportType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Future => write!(f, "future"),
Self::StandardLibrary => write!(f, "standard_library"),
Self::ThirdParty => write!(f, "third_party"),
Self::FirstParty => write!(f, "first_party"),
Self::LocalFolder => write!(f, "local_folder"),
}
}
}
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Hash, Serialize, Deserialize, CacheKey)]
#[serde(untagged)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum ImportSection {
Known(ImportType),
UserDefined(String),
}
impl fmt::Display for ImportSection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Known(import_type) => write!(f, "known {{ type = {import_type} }}",),
Self::UserDefined(string) => fmt::Debug::fmt(string, f),
}
}
}
#[derive(Debug)]
enum Reason<'a> {
NonZeroLevel,
KnownFirstParty,
KnownThirdParty,
KnownLocalFolder,
ExtraStandardLibrary,
Future,
KnownStandardLibrary,
SamePackage,
#[expect(dead_code)]
SourceMatch(&'a Path),
NoMatch,
UserDefinedSection,
NoSections,
#[expect(dead_code)]
DisabledSection(&'a ImportSection),
}
#[expect(clippy::too_many_arguments)]
pub(crate) fn categorize<'a>(
module_name: &str,
is_relative: bool,
src: &[PathBuf],
package: Option<PackageRoot<'_>>,
detect_same_package: bool,
known_modules: &'a KnownModules,
target_version: PythonVersion,
no_sections: bool,
section_order: &'a [ImportSection],
default_section: &'a ImportSection,
) -> &'a ImportSection {
let module_base = module_name.split('.').next().unwrap();
let (mut import_type, mut reason) = {
if !is_relative && module_base == "__future__" {
(&ImportSection::Known(ImportType::Future), Reason::Future)
} else if no_sections {
(
&ImportSection::Known(ImportType::FirstParty),
Reason::NoSections,
)
} else if is_relative {
(
&ImportSection::Known(ImportType::LocalFolder),
Reason::NonZeroLevel,
)
} else if let Some((import_type, reason)) = known_modules.categorize(module_name) {
(import_type, reason)
} else if is_known_standard_library(target_version.minor, module_base) {
(
&ImportSection::Known(ImportType::StandardLibrary),
Reason::KnownStandardLibrary,
)
} else if detect_same_package && same_package(package, module_base) {
(
&ImportSection::Known(ImportType::FirstParty),
Reason::SamePackage,
)
} else if let Some(src) = match_sources(src, module_name) {
(
&ImportSection::Known(ImportType::FirstParty),
Reason::SourceMatch(src),
)
} else if !is_relative && module_name == "__main__" {
(
&ImportSection::Known(ImportType::FirstParty),
Reason::KnownFirstParty,
)
} else {
(default_section, Reason::NoMatch)
}
};
// If a value is not in `section_order` then map it to `default_section`.
if !section_order.contains(import_type) {
reason = Reason::DisabledSection(import_type);
import_type = default_section;
}
debug!("Categorized '{module_name}' as {import_type:?} ({reason:?})");
import_type
}
fn same_package(package: Option<PackageRoot<'_>>, module_base: &str) -> bool {
package
.map(PackageRoot::path)
.is_some_and(|package| package.ends_with(module_base))
}
/// Returns the source path with respect to which the module `name`
/// should be considered first party, or `None` if no path is found.
///
/// # Examples
///
/// - The module named `foo` will match `[SRC]` if `[SRC]/foo` is a directory
///
/// - The module named `foo.baz` will match `[SRC]` only if `[SRC]/foo/baz`
/// is a directory, or `[SRC]/foo/baz.py` exists,
/// or `[SRC]/foo/baz.pyi` exists.
fn match_sources<'a>(paths: &'a [PathBuf], name: &str) -> Option<&'a Path> {
let relative_path: PathBuf = name.split('.').collect();
relative_path.components().next()?;
for root in paths {
let candidate = root.join(&relative_path);
if candidate.is_dir() {
return Some(root);
}
if ["py", "pyi"]
.into_iter()
.any(|extension| candidate.with_extension(extension).is_file())
{
return Some(root);
}
}
None
}
#[expect(clippy::too_many_arguments)]
pub(crate) fn categorize_imports<'a>(
block: ImportBlock<'a>,
src: &[PathBuf],
package: Option<PackageRoot<'_>>,
detect_same_package: bool,
known_modules: &'a KnownModules,
target_version: PythonVersion,
no_sections: bool,
section_order: &'a [ImportSection],
default_section: &'a ImportSection,
) -> BTreeMap<&'a ImportSection, ImportBlock<'a>> {
let mut block_by_type: BTreeMap<&ImportSection, ImportBlock> = BTreeMap::default();
// Categorize `Stmt::Import`.
for (alias, comments) in block.import {
let import_type = categorize(
&alias.module_name(),
false,
src,
package,
detect_same_package,
known_modules,
target_version,
no_sections,
section_order,
default_section,
);
block_by_type
.entry(import_type)
.or_default()
.import
.insert(alias, comments);
}
// Categorize `Stmt::ImportFrom` (without re-export).
for (import_from, aliases) in block.import_from {
let classification = categorize(
&import_from.module_name(),
import_from.level > 0,
src,
package,
detect_same_package,
known_modules,
target_version,
no_sections,
section_order,
default_section,
);
block_by_type
.entry(classification)
.or_default()
.import_from
.insert(import_from, aliases);
}
// Categorize `Stmt::ImportFrom` (with re-export).
for ((import_from, alias), aliases) in block.import_from_as {
let classification = categorize(
&import_from.module_name(),
import_from.level > 0,
src,
package,
detect_same_package,
known_modules,
target_version,
no_sections,
section_order,
default_section,
);
block_by_type
.entry(classification)
.or_default()
.import_from_as
.insert((import_from, alias), aliases);
}
// Categorize `Stmt::ImportFrom` (with star).
for (import_from, comments) in block.import_from_star {
let classification = categorize(
&import_from.module_name(),
import_from.level > 0,
src,
package,
detect_same_package,
known_modules,
target_version,
no_sections,
section_order,
default_section,
);
block_by_type
.entry(classification)
.or_default()
.import_from_star
.insert(import_from, comments);
}
block_by_type
}
#[derive(Debug, Clone, Default, CacheKey)]
pub struct KnownModules {
/// A map of known modules to their section.
known: Vec<(glob::Pattern, ImportSection)>,
/// Whether any of the known modules are submodules (e.g., `foo.bar`, as opposed to `foo`).
has_submodules: bool,
}
impl KnownModules {
pub fn new(
first_party: Vec<glob::Pattern>,
third_party: Vec<glob::Pattern>,
local_folder: Vec<glob::Pattern>,
standard_library: Vec<glob::Pattern>,
user_defined: FxHashMap<String, Vec<glob::Pattern>>,
) -> Self {
let known: Vec<(glob::Pattern, ImportSection)> = user_defined
.into_iter()
.flat_map(|(section, modules)| {
modules
.into_iter()
.map(move |module| (module, ImportSection::UserDefined(section.clone())))
})
.chain(
first_party
.into_iter()
.map(|module| (module, ImportSection::Known(ImportType::FirstParty))),
)
.chain(
third_party
.into_iter()
.map(|module| (module, ImportSection::Known(ImportType::ThirdParty))),
)
.chain(
local_folder
.into_iter()
.map(|module| (module, ImportSection::Known(ImportType::LocalFolder))),
)
.chain(
standard_library
.into_iter()
.map(|module| (module, ImportSection::Known(ImportType::StandardLibrary))),
)
.collect();
// Warn in the case of duplicate modules.
let mut seen = FxHashSet::with_capacity_and_hasher(known.len(), FxBuildHasher);
for (module, _) in &known {
if !seen.insert(module) {
warn_user_once!(
"One or more modules are part of multiple import sections, including: `{module}`"
);
break;
}
}
// Check if any of the known modules are submodules.
let has_submodules = known
.iter()
.any(|(module, _)| module.as_str().contains('.'));
Self {
known,
has_submodules,
}
}
/// Return the [`ImportSection`] for a given module, if it's been categorized as a known module
/// by the user.
fn categorize(&self, module_name: &str) -> Option<(&ImportSection, Reason<'_>)> {
if self.has_submodules {
// Check all module prefixes from the longest to the shortest (e.g., given
// `foo.bar.baz`, check `foo.bar.baz`, then `foo.bar`, then `foo`, taking the first,
// most precise match).
for i in module_name
.match_indices('.')
.map(|(i, _)| i)
.chain(iter::once(module_name.len()))
.rev()
{
let submodule = &module_name[0..i];
if let Some(result) = self.categorize_submodule(submodule) {
return Some(result);
}
}
None
} else {
// Happy path: no submodules, so we can check the module base and be done.
let module_base = module_name.split('.').next().unwrap();
self.categorize_submodule(module_base)
}
}
fn categorize_submodule(&self, submodule: &str) -> Option<(&ImportSection, Reason<'_>)> {
let section = self.known.iter().find_map(|(pattern, section)| {
if pattern.matches(submodule) {
Some(section)
} else {
None
}
})?;
let reason = match section {
ImportSection::UserDefined(_) => Reason::UserDefinedSection,
ImportSection::Known(ImportType::FirstParty) => Reason::KnownFirstParty,
ImportSection::Known(ImportType::ThirdParty) => Reason::KnownThirdParty,
ImportSection::Known(ImportType::LocalFolder) => Reason::KnownLocalFolder,
ImportSection::Known(ImportType::StandardLibrary) => Reason::ExtraStandardLibrary,
ImportSection::Known(ImportType::Future) => {
unreachable!("__future__ imports are not known")
}
};
Some((section, reason))
}
/// Return the list of user-defined modules, indexed by section.
pub fn user_defined(&self) -> FxHashMap<&str, Vec<&glob::Pattern>> {
let mut user_defined: FxHashMap<&str, Vec<&glob::Pattern>> = FxHashMap::default();
for (module, section) in &self.known {
if let ImportSection::UserDefined(section_name) = section {
user_defined
.entry(section_name.as_str())
.or_default()
.push(module);
}
}
user_defined
}
}
impl fmt::Display for KnownModules {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.known.is_empty() {
write!(f, "{{}}")?;
} else {
writeln!(f, "{{")?;
for (pattern, import_section) in &self.known {
writeln!(f, "\t{pattern} => {import_section:?},")?;
}
write!(f, "}}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::rules::isort::categorize::match_sources;
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::tempdir;
/// Helper function to create a file with parent directories
fn create_file<P: AsRef<Path>>(path: P) {
let path = path.as_ref();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(path, "").unwrap();
}
/// Helper function to create a directory and all parent directories
fn create_dir<P: AsRef<Path>>(path: P) {
fs::create_dir_all(path).unwrap();
}
/// Tests a traditional Python package layout:
/// ```
/// project/
/// βββ mypackage/
/// βββ __init__.py
/// βββ module1.py
/// βββ module2.py
/// ```
#[test]
fn test_traditional_layout() {
let temp_dir = tempdir().unwrap();
let project_dir = temp_dir.path().join("project");
// Create traditional layout
create_dir(project_dir.join("mypackage"));
create_file(project_dir.join("mypackage/__init__.py"));
create_file(project_dir.join("mypackage/module1.py"));
create_file(project_dir.join("mypackage/module2.py"));
let paths = vec![project_dir.clone()];
assert_eq!(
match_sources(&paths, "mypackage"),
Some(project_dir.as_path())
);
assert_eq!(
match_sources(&paths, "mypackage.module1"),
Some(project_dir.as_path())
);
assert_eq!(match_sources(&paths, "mypackage.nonexistent",), None);
}
/// Tests a src-based Python package layout:
/// ```
/// project/
/// βββ src/
/// βββ mypackage/
/// βββ __init__.py
/// βββ module1.py
/// ```
#[test]
fn test_src_layout() {
let temp_dir = tempdir().unwrap();
let project_dir = temp_dir.path().join("project");
let src_dir = project_dir.join("src");
// Create src layout
create_dir(src_dir.join("mypackage"));
create_file(src_dir.join("mypackage/__init__.py"));
create_file(src_dir.join("mypackage/module1.py"));
let paths = vec![src_dir.clone()];
assert_eq!(
match_sources(&paths, "mypackage.module1"),
Some(src_dir.as_path())
);
assert_eq!(match_sources(&paths, "mypackage.nonexistent"), None);
}
/// Tests a nested package layout:
/// ```
/// project/
/// βββ mypackage/
/// βββ __init__.py
/// βββ module1.py
/// βββ subpackage/
/// βββ __init__.py
/// βββ module2.py
/// ```
#[test]
fn test_nested_packages() {
let temp_dir = tempdir().unwrap();
let project_dir = temp_dir.path().join("project");
// Create nested package layout
create_dir(project_dir.join("mypackage/subpackage"));
create_file(project_dir.join("mypackage/__init__.py"));
create_file(project_dir.join("mypackage/module1.py"));
create_file(project_dir.join("mypackage/subpackage/__init__.py"));
create_file(project_dir.join("mypackage/subpackage/module2.py"));
let paths = vec![project_dir.clone()];
assert_eq!(
match_sources(&paths, "mypackage.subpackage.module2"),
Some(project_dir.as_path())
);
assert_eq!(
match_sources(&paths, "mypackage.subpackage.nonexistent"),
None
);
}
/// Tests a namespace package layout (PEP 420):
/// ```
/// project/
/// βββ namespace/ # No __init__.py (namespace package)
/// βββ package1/
/// βββ __init__.py
/// βββ module1.py
/// ```
#[test]
fn test_namespace_packages() {
let temp_dir = tempdir().unwrap();
let project_dir = temp_dir.path().join("project");
// Create namespace package layout
create_dir(project_dir.join("namespace/package1"));
create_file(project_dir.join("namespace/package1/__init__.py"));
create_file(project_dir.join("namespace/package1/module1.py"));
let paths = vec![project_dir.clone()];
assert_eq!(
match_sources(&paths, "namespace.package1"),
Some(project_dir.as_path())
);
assert_eq!(
match_sources(&paths, "namespace.package1.module1"),
Some(project_dir.as_path())
);
assert_eq!(match_sources(&paths, "namespace.package2.module1"), None);
}
/// Tests a package with type stubs (.pyi files):
/// ```
/// project/
/// βββ mypackage/
/// βββ __init__.py
/// βββ module1.pyi # Only .pyi file, no .py
/// ```
#[test]
fn test_type_stubs() {
let temp_dir = tempdir().unwrap();
let project_dir = temp_dir.path().join("project");
// Create package with type stub
create_dir(project_dir.join("mypackage"));
create_file(project_dir.join("mypackage/__init__.py"));
create_file(project_dir.join("mypackage/module1.pyi")); // Only create .pyi file, not .py
let paths = vec![project_dir.clone()];
// Module "mypackage.module1" should match project_dir using .pyi file
assert_eq!(
match_sources(&paths, "mypackage.module1"),
Some(project_dir.as_path())
);
}
/// Tests a package with both a module and a directory having the same name:
/// ```
/// project/
/// βββ mypackage/
/// βββ __init__.py
/// βββ feature.py # Module with same name as directory
/// βββ feature/ # Directory with same name as module
/// βββ __init__.py
/// βββ submodule.py
/// ```
#[test]
fn test_same_name_module_and_directory() {
let temp_dir = tempdir().unwrap();
let project_dir = temp_dir.path().join("project");
// Create package with module and directory of the same name
create_dir(project_dir.join("mypackage/feature"));
create_file(project_dir.join("mypackage/__init__.py"));
create_file(project_dir.join("mypackage/feature.py")); // Module with same name as directory
create_file(project_dir.join("mypackage/feature/__init__.py"));
create_file(project_dir.join("mypackage/feature/submodule.py"));
let paths = vec![project_dir.clone()];
// Module "mypackage.feature" should match project_dir
assert_eq!(
match_sources(&paths, "mypackage.feature"),
Some(project_dir.as_path())
);
// Module "mypackage.feature.submodule" should match project_dir
assert_eq!(
match_sources(&paths, "mypackage.feature.submodule"),
Some(project_dir.as_path())
);
}
/// Tests multiple source directories with different packages:
/// ```
/// project1/
/// βββ package1/
/// βββ __init__.py
/// βββ module1.py
///
/// project2/
/// βββ package2/
/// βββ __init__.py
/// βββ module2.py
/// ```
#[test]
fn test_multiple_source_paths() {
let temp_dir = tempdir().unwrap();
let project1_dir = temp_dir.path().join("project1");
let project2_dir = temp_dir.path().join("project2");
// Create files in project1
create_dir(project1_dir.join("package1"));
create_file(project1_dir.join("package1/__init__.py"));
create_file(project1_dir.join("package1/module1.py"));
// Create files in project2
create_dir(project2_dir.join("package2"));
create_file(project2_dir.join("package2/__init__.py"));
create_file(project2_dir.join("package2/module2.py"));
// Test with multiple paths in search order
let paths = vec![project1_dir.clone(), project2_dir.clone()];
// Module "package1" should match project1_dir
assert_eq!(
match_sources(&paths, "package1"),
Some(project1_dir.as_path())
);
// Module "package2" should match project2_dir
assert_eq!(
match_sources(&paths, "package2"),
Some(project2_dir.as_path())
);
// Try with reversed order to check search order
let paths_reversed = vec![project2_dir, project1_dir.clone()];
// Module "package1" should still match project1_dir
assert_eq!(
match_sources(&paths_reversed, "package1"),
Some(project1_dir.as_path())
);
}
/// Tests behavior with an empty module name
/// ```
/// project/
/// βββ mypackage/
/// ```
///
/// In theory this should never happen since we expect
/// module names to have been normalized by the time we
/// call `match_sources`.
#[test]
fn test_empty_module_name() {
let temp_dir = tempdir().unwrap();
let project_dir = temp_dir.path().join("project");
create_dir(project_dir.join("mypackage"));
let paths = vec![project_dir];
assert_eq!(match_sources(&paths, ""), None);
}
/// Tests behavior with an empty list of source paths
#[test]
fn test_empty_paths() {
let paths: Vec<PathBuf> = vec![];
assert_eq!(match_sources(&paths, "mypackage"), None);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/settings.rs | crates/ruff_linter/src/rules/isort/settings.rs | //! Settings for the `isort` plugin.
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
use std::fmt::{Display, Formatter};
use rustc_hash::FxHashSet;
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
use crate::display_settings;
use crate::rules::isort::ImportType;
use crate::rules::isort::categorize::KnownModules;
use ruff_macros::CacheKey;
use ruff_python_semantic::{Alias, MemberNameImport, ModuleNameImport, NameImport};
use super::categorize::ImportSection;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, CacheKey)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Default)]
pub enum RelativeImportsOrder {
/// Place "closer" imports (fewer `.` characters, most local) before
/// "further" imports (more `.` characters, least local).
ClosestToFurthest,
/// Place "further" imports (more `.` characters, least local) imports
/// before "closer" imports (fewer `.` characters, most local).
#[default]
FurthestToClosest,
}
impl Display for RelativeImportsOrder {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::ClosestToFurthest => write!(f, "closest_to_furthest"),
Self::FurthestToClosest => write!(f, "furthest_to_closest"),
}
}
}
#[derive(Debug, Clone, CacheKey)]
#[expect(clippy::struct_excessive_bools)]
pub struct Settings {
pub required_imports: BTreeSet<NameImport>,
pub combine_as_imports: bool,
pub force_single_line: bool,
pub force_sort_within_sections: bool,
pub case_sensitive: bool,
pub force_wrap_aliases: bool,
pub force_to_top: FxHashSet<String>,
pub known_modules: KnownModules,
pub detect_same_package: bool,
pub order_by_type: bool,
pub relative_imports_order: RelativeImportsOrder,
pub single_line_exclusions: FxHashSet<String>,
pub split_on_trailing_comma: bool,
pub classes: FxHashSet<String>,
pub constants: FxHashSet<String>,
pub variables: FxHashSet<String>,
pub no_lines_before: FxHashSet<ImportSection>,
pub lines_after_imports: isize,
pub lines_between_types: usize,
pub forced_separate: Vec<String>,
pub section_order: Vec<ImportSection>,
pub default_section: ImportSection,
pub no_sections: bool,
pub from_first: bool,
pub length_sort: bool,
pub length_sort_straight: bool,
}
impl Settings {
pub fn requires_module_import(&self, name: String, as_name: Option<String>) -> bool {
self.required_imports
.contains(&NameImport::Import(ModuleNameImport {
name: Alias { name, as_name },
}))
}
pub fn requires_member_import(
&self,
module: Option<String>,
name: String,
as_name: Option<String>,
level: u32,
) -> bool {
self.required_imports
.contains(&NameImport::ImportFrom(MemberNameImport {
module,
name: Alias { name, as_name },
level,
}))
}
}
impl Default for Settings {
fn default() -> Self {
Self {
required_imports: BTreeSet::default(),
combine_as_imports: false,
force_single_line: false,
force_sort_within_sections: false,
detect_same_package: true,
case_sensitive: false,
force_wrap_aliases: false,
force_to_top: FxHashSet::default(),
known_modules: KnownModules::default(),
order_by_type: true,
relative_imports_order: RelativeImportsOrder::default(),
single_line_exclusions: FxHashSet::default(),
split_on_trailing_comma: true,
classes: FxHashSet::default(),
constants: FxHashSet::default(),
variables: FxHashSet::default(),
no_lines_before: FxHashSet::default(),
lines_after_imports: -1,
lines_between_types: 0,
forced_separate: Vec::new(),
section_order: ImportType::iter().map(ImportSection::Known).collect(),
default_section: ImportSection::Known(ImportType::ThirdParty),
no_sections: false,
from_first: false,
length_sort: false,
length_sort_straight: false,
}
}
}
impl Display for Settings {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.isort",
fields = [
self.required_imports | set,
self.combine_as_imports,
self.force_single_line,
self.force_sort_within_sections,
self.detect_same_package,
self.case_sensitive,
self.force_wrap_aliases,
self.force_to_top | set,
self.known_modules,
self.order_by_type,
self.relative_imports_order,
self.single_line_exclusions | set,
self.split_on_trailing_comma,
self.classes | set,
self.constants | set,
self.variables | set,
self.no_lines_before | set,
self.lines_after_imports,
self.lines_between_types,
self.forced_separate | array,
self.section_order | array,
self.default_section,
self.no_sections,
self.from_first,
self.length_sort,
self.length_sort_straight
]
}
Ok(())
}
}
/// Error returned by the [`TryFrom`] implementation of [`Settings`].
#[derive(Debug)]
pub enum SettingsError {
InvalidKnownFirstParty(glob::PatternError),
InvalidKnownThirdParty(glob::PatternError),
InvalidKnownLocalFolder(glob::PatternError),
InvalidExtraStandardLibrary(glob::PatternError),
InvalidUserDefinedSection(glob::PatternError),
}
impl Display for SettingsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SettingsError::InvalidKnownThirdParty(err) => {
write!(f, "invalid known third-party pattern: {err}")
}
SettingsError::InvalidKnownFirstParty(err) => {
write!(f, "invalid known first-party pattern: {err}")
}
SettingsError::InvalidKnownLocalFolder(err) => {
write!(f, "invalid known local folder pattern: {err}")
}
SettingsError::InvalidExtraStandardLibrary(err) => {
write!(f, "invalid extra standard library pattern: {err}")
}
SettingsError::InvalidUserDefinedSection(err) => {
write!(f, "invalid user-defined section pattern: {err}")
}
}
}
}
impl Error for SettingsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
SettingsError::InvalidKnownThirdParty(err) => Some(err),
SettingsError::InvalidKnownFirstParty(err) => Some(err),
SettingsError::InvalidKnownLocalFolder(err) => Some(err),
SettingsError::InvalidExtraStandardLibrary(err) => Some(err),
SettingsError::InvalidUserDefinedSection(err) => Some(err),
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/comments.rs | crates/ruff_linter/src/rules/isort/comments.rs | use std::borrow::Cow;
use ruff_python_trivia::CommentRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
#[derive(Debug)]
pub(crate) struct Comment<'a> {
pub(crate) value: Cow<'a, str>,
pub(crate) range: TextRange,
}
impl Ranged for Comment<'_> {
fn range(&self) -> TextRange {
self.range
}
}
/// Collect all comments in an import block.
pub(crate) fn collect_comments<'a>(
range: TextRange,
locator: &'a Locator,
comment_ranges: &'a CommentRanges,
) -> Vec<Comment<'a>> {
comment_ranges
.comments_in_range(range)
.iter()
.map(|range| Comment {
value: locator.slice(*range).into(),
range: *range,
})
.collect()
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/sorting.rs | crates/ruff_linter/src/rules/isort/sorting.rs | //! See: <https://github.com/PyCQA/isort/blob/12cc5fbd67eebf92eb2213b03c07b138ae1fb448/isort/sorting.py#L13>
use std::{borrow::Cow, cmp::Ordering, cmp::Reverse};
use natord;
use unicode_width::UnicodeWidthChar;
use ruff_python_stdlib::str;
use super::settings::{RelativeImportsOrder, Settings};
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Copy, Clone)]
pub(crate) enum MemberType {
Constant,
Class,
Variable,
}
fn member_type(name: &str, settings: &Settings) -> MemberType {
if settings.constants.contains(name) {
// Ex) `CONSTANT`
MemberType::Constant
} else if settings.classes.contains(name) {
// Ex) `CLASS`
MemberType::Class
} else if settings.variables.contains(name) {
// Ex) `variable`
MemberType::Variable
} else if name.len() > 1 && str::is_cased_uppercase(name) {
// Ex) `CONSTANT`
MemberType::Constant
} else if name.chars().next().is_some_and(char::is_uppercase) {
// Ex) `Class`
MemberType::Class
} else {
// Ex) `variable`
MemberType::Variable
}
}
#[derive(Eq, PartialEq, Debug)]
pub(crate) struct NatOrdStr<'a>(Cow<'a, str>);
impl Ord for NatOrdStr<'_> {
fn cmp(&self, other: &Self) -> Ordering {
natord::compare(&self.0, &other.0)
}
}
impl PartialOrd for NatOrdStr<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> From<&'a str> for NatOrdStr<'a> {
fn from(s: &'a str) -> Self {
NatOrdStr(Cow::Borrowed(s))
}
}
impl From<String> for NatOrdStr<'_> {
fn from(s: String) -> Self {
NatOrdStr(Cow::Owned(s))
}
}
#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq)]
pub(crate) enum Distance {
Nearest(u32),
Furthest(Reverse<u32>),
None,
}
#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq)]
pub(crate) enum ImportStyle {
// Ex) `import foo`
Straight,
// Ex) `from foo import bar`
From,
}
/// A comparable key to capture the desired sorting order for an imported module (e.g.,
/// `foo` in `from foo import bar`).
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq)]
pub(crate) struct ModuleKey<'a> {
force_to_top: bool,
maybe_length: Option<usize>,
distance: Distance,
maybe_lowercase_name: Option<NatOrdStr<'a>>,
module_name: Option<NatOrdStr<'a>>,
first_alias: Option<MemberKey<'a>>,
asname: Option<NatOrdStr<'a>>,
}
impl<'a> ModuleKey<'a> {
pub(crate) fn from_module(
name: Option<&'a str>,
asname: Option<&'a str>,
level: u32,
first_alias: Option<(&'a str, Option<&'a str>)>,
style: ImportStyle,
settings: &Settings,
) -> Self {
let force_to_top = !name.is_some_and(|name| settings.force_to_top.contains(name)); // `false` < `true` so we get forced to top first
let maybe_length = (settings.length_sort
|| (settings.length_sort_straight && style == ImportStyle::Straight))
.then_some(
name.map(|name| name.chars().map(|c| c.width().unwrap_or(0)).sum::<usize>())
.unwrap_or_default()
+ level as usize,
);
let distance = match level {
0 => Distance::None,
_ => match settings.relative_imports_order {
RelativeImportsOrder::ClosestToFurthest => Distance::Nearest(level),
RelativeImportsOrder::FurthestToClosest => Distance::Furthest(Reverse(level)),
},
};
let maybe_lowercase_name = name.and_then(|name| {
(!settings.case_sensitive).then_some(NatOrdStr(maybe_lowercase(name)))
});
let module_name = name.map(NatOrdStr::from);
let asname = asname.map(NatOrdStr::from);
let first_alias =
first_alias.map(|(name, asname)| MemberKey::from_member(name, asname, settings));
Self {
force_to_top,
maybe_length,
distance,
maybe_lowercase_name,
module_name,
first_alias,
asname,
}
}
}
/// A comparable key to capture the desired sorting order for an imported member (e.g., `bar` in
/// `from foo import bar`).
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq)]
pub(crate) struct MemberKey<'a> {
not_star_import: bool,
member_type: Option<MemberType>,
maybe_length: Option<usize>,
maybe_lowercase_name: Option<NatOrdStr<'a>>,
module_name: NatOrdStr<'a>,
asname: Option<NatOrdStr<'a>>,
}
impl<'a> MemberKey<'a> {
pub(crate) fn from_member(name: &'a str, asname: Option<&'a str>, settings: &Settings) -> Self {
let not_star_import = name != "*"; // `false` < `true` so we get star imports first
let member_type = settings
.order_by_type
.then_some(member_type(name, settings));
let maybe_length = settings
.length_sort
.then(|| name.chars().map(|c| c.width().unwrap_or(0)).sum());
let maybe_lowercase_name =
(!settings.case_sensitive).then_some(NatOrdStr(maybe_lowercase(name)));
let module_name = NatOrdStr::from(name);
let asname = asname.map(NatOrdStr::from);
Self {
not_star_import,
member_type,
maybe_length,
maybe_lowercase_name,
module_name,
asname,
}
}
}
/// Lowercase the given string, if it contains any uppercase characters.
fn maybe_lowercase(name: &str) -> Cow<'_, str> {
if name.chars().all(char::is_lowercase) {
Cow::Borrowed(name)
} else {
Cow::Owned(name.to_lowercase())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/helpers.rs | crates/ruff_linter/src/rules/isort/helpers.rs | use ruff_python_ast::Stmt;
use ruff_python_ast::token::{TokenKind, Tokens};
use ruff_python_trivia::PythonWhitespace;
use ruff_source_file::UniversalNewlines;
use ruff_text_size::Ranged;
use crate::Locator;
use crate::rules::isort::types::TrailingComma;
/// Return `true` if a `Stmt::ImportFrom` statement ends with a magic
/// trailing comma.
pub(super) fn trailing_comma(stmt: &Stmt, tokens: &Tokens) -> TrailingComma {
let mut count = 0u32;
let mut trailing_comma = TrailingComma::Absent;
for token in tokens.in_range(stmt.range()) {
match token.kind() {
TokenKind::Lpar => count = count.saturating_add(1),
TokenKind::Rpar => count = count.saturating_sub(1),
_ => {}
}
if count == 1 {
match token.kind() {
TokenKind::NonLogicalNewline
| TokenKind::Indent
| TokenKind::Dedent
| TokenKind::Comment => continue,
TokenKind::Comma => trailing_comma = TrailingComma::Present,
_ => trailing_comma = TrailingComma::Absent,
}
}
}
trailing_comma
}
/// Return `true` if a [`Stmt`] is preceded by a "comment break"
pub(super) fn has_comment_break(stmt: &Stmt, locator: &Locator) -> bool {
// Starting from the `Stmt` (`def f(): pass`), we want to detect patterns like
// this:
//
// import os
//
// # Detached comment.
//
// def f(): pass
// This should also be detected:
//
// import os
//
// # Detached comment.
//
// # Direct comment.
// def f(): pass
// But this should not:
//
// import os
//
// # Direct comment.
// def f(): pass
let mut seen_blank = false;
for line in locator.up_to(stmt.start()).universal_newlines().rev() {
let line = line.trim_whitespace();
if seen_blank {
if line.starts_with('#') {
return true;
} else if !line.is_empty() {
break;
}
} else {
if line.is_empty() {
seen_blank = true;
} else if line.starts_with('#') || line.starts_with('@') {
continue;
} else {
break;
}
}
}
false
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/order.rs | crates/ruff_linter/src/rules/isort/order.rs | use crate::rules::isort::sorting::ImportStyle;
use crate::rules::isort::{ImportSection, ImportType};
use itertools::Itertools;
use super::settings::Settings;
use super::sorting::{MemberKey, ModuleKey};
use super::types::EitherImport::{self, Import, ImportFrom};
use super::types::{AliasData, ImportBlock, ImportFromCommentSet, ImportFromStatement};
pub(crate) fn order_imports<'a>(
block: ImportBlock<'a>,
section: &ImportSection,
settings: &Settings,
) -> Vec<EitherImport<'a>> {
let straight_imports = block.import.into_iter();
let from_imports =
// Include all non-re-exports.
block
.import_from
.into_iter()
.chain(
// Include all re-exports.
block
.import_from_as
.into_iter()
.map(|((import_from, ..), body)| (import_from, body)),
)
.chain(
// Include all star imports.
block.import_from_star,
)
.map(
|(
import_from,
ImportFromStatement {
comments,
aliases,
trailing_comma,
},
)| {
// Within each `Stmt::ImportFrom`, sort the members.
(
import_from,
comments,
trailing_comma,
aliases
.into_iter()
.sorted_by_cached_key(|(alias, _)| {
MemberKey::from_member(alias.name, alias.asname, settings)
})
.collect::<Vec<(AliasData, ImportFromCommentSet)>>(),
)
},
);
if matches!(section, ImportSection::Known(ImportType::Future)) {
from_imports
.sorted_by_cached_key(|(import_from, _, _, aliases)| {
ModuleKey::from_module(
import_from.module,
None,
import_from.level,
aliases.first().map(|(alias, _)| (alias.name, alias.asname)),
ImportStyle::From,
settings,
)
})
.map(ImportFrom)
.chain(
straight_imports
.sorted_by_cached_key(|(alias, _)| {
ModuleKey::from_module(
Some(alias.name),
alias.asname,
0,
None,
ImportStyle::Straight,
settings,
)
})
.map(Import),
)
.collect()
} else if settings.force_sort_within_sections {
straight_imports
.map(Import)
.chain(from_imports.map(ImportFrom))
.sorted_by_cached_key(|import| match import {
Import((alias, _)) => ModuleKey::from_module(
Some(alias.name),
alias.asname,
0,
None,
ImportStyle::Straight,
settings,
),
ImportFrom((import_from, _, _, aliases)) => ModuleKey::from_module(
import_from.module,
None,
import_from.level,
aliases.first().map(|(alias, _)| (alias.name, alias.asname)),
ImportStyle::From,
settings,
),
})
.collect()
} else {
let ordered_straight_imports = straight_imports.sorted_by_cached_key(|(alias, _)| {
ModuleKey::from_module(
Some(alias.name),
alias.asname,
0,
None,
ImportStyle::Straight,
settings,
)
});
let ordered_from_imports =
from_imports.sorted_by_cached_key(|(import_from, _, _, aliases)| {
ModuleKey::from_module(
import_from.module,
None,
import_from.level,
aliases.first().map(|(alias, _)| (alias.name, alias.asname)),
ImportStyle::From,
settings,
)
});
if settings.from_first {
ordered_from_imports
.into_iter()
.map(ImportFrom)
.chain(ordered_straight_imports.into_iter().map(Import))
.collect()
} else {
ordered_straight_imports
.into_iter()
.map(Import)
.chain(ordered_from_imports.into_iter().map(ImportFrom))
.collect()
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/block.rs | crates/ruff_linter/src/rules/isort/block.rs | use std::iter::Peekable;
use std::slice;
use ruff_notebook::CellOffsets;
use ruff_python_ast::statement_visitor::StatementVisitor;
use ruff_python_ast::{self as ast, ElifElseClause, ExceptHandler, MatchCase, Stmt};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::Locator;
use crate::directives::IsortDirectives;
use crate::rules::isort::helpers;
/// A block of imports within a Python module.
#[derive(Debug, Default)]
pub(crate) struct Block<'a> {
pub(crate) nested: bool,
pub(crate) imports: Vec<&'a Stmt>,
pub(crate) trailer: Option<Trailer>,
}
/// The type of trailer that should follow an import block.
#[derive(Debug, Copy, Clone)]
pub(crate) enum Trailer {
Sibling,
ClassDef,
FunctionDef,
}
/// A builder for identifying and constructing import blocks within a Python module.
pub(crate) struct BlockBuilder<'a> {
locator: &'a Locator<'a>,
is_stub: bool,
blocks: Vec<Block<'a>>,
splits: Peekable<slice::Iter<'a, TextSize>>,
cell_offsets: Option<Peekable<slice::Iter<'a, TextSize>>>,
exclusions: &'a [TextRange],
nested: bool,
}
impl<'a> BlockBuilder<'a> {
pub(crate) fn new(
locator: &'a Locator<'a>,
directives: &'a IsortDirectives,
is_stub: bool,
cell_offsets: Option<&'a CellOffsets>,
) -> Self {
Self {
locator,
is_stub,
blocks: vec![Block::default()],
splits: directives.splits.iter().peekable(),
exclusions: &directives.exclusions,
nested: false,
cell_offsets: cell_offsets.map(|offsets| offsets.iter().peekable()),
}
}
fn track_import(&mut self, stmt: &'a Stmt) {
let index = self.blocks.len() - 1;
self.blocks[index].imports.push(stmt);
self.blocks[index].nested = self.nested;
}
fn trailer_for(&self, stmt: &'a Stmt) -> Option<Trailer> {
// No need to compute trailers if we won't be finalizing anything.
let index = self.blocks.len() - 1;
if self.blocks[index].imports.is_empty() {
return None;
}
// Similar to isort, avoid enforcing any newline behaviors in nested blocks.
if self.nested {
return None;
}
Some(if self.is_stub {
// Black treats interface files differently, limiting to one newline
// (`Trailing::Sibling`).
Trailer::Sibling
} else {
// If the import block is followed by a class or function, we want to enforce
// two blank lines. The exception: if, between the import and the class or
// function, we have at least one commented line, followed by at
// least one blank line. In that case, we treat it as a regular
// sibling (i.e., as if the comment is the next statement, as
// opposed to the class or function).
match stmt {
Stmt::FunctionDef(_) => {
if helpers::has_comment_break(stmt, self.locator) {
Trailer::Sibling
} else {
Trailer::FunctionDef
}
}
Stmt::ClassDef(_) => {
if helpers::has_comment_break(stmt, self.locator) {
Trailer::Sibling
} else {
Trailer::ClassDef
}
}
_ => Trailer::Sibling,
}
})
}
fn finalize(&mut self, trailer: Option<Trailer>) {
let index = self.blocks.len() - 1;
if !self.blocks[index].imports.is_empty() {
self.blocks[index].trailer = trailer;
self.blocks.push(Block::default());
}
}
pub(crate) fn iter<'b>(&'a self) -> impl Iterator<Item = &'b Block<'a>>
where
'a: 'b,
{
self.blocks.iter()
}
}
impl<'a> StatementVisitor<'a> for BlockBuilder<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
// Track manual splits (e.g., `# isort: split`).
if self
.splits
.next_if(|split| stmt.start() >= **split)
.is_some()
{
// Skip any other splits that occur before the current statement, to support, e.g.:
// ```python
// # isort: split
// # isort: split
// import foo
// ```
while self
.splits
.peek()
.is_some_and(|split| stmt.start() >= **split)
{
self.splits.next();
}
self.finalize(self.trailer_for(stmt));
}
// Track Jupyter notebook cell offsets as splits. This will make sure
// that each cell is considered as an individual block to organize the
// imports in. Thus, not creating an edit which spans across multiple
// cells.
if let Some(cell_offsets) = self.cell_offsets.as_mut() {
if cell_offsets
.next_if(|cell_offset| stmt.start() >= **cell_offset)
.is_some()
{
// Skip any other cell offsets that occur before the current statement (e.g., in
// the case of multiple empty cells).
while cell_offsets
.peek()
.is_some_and(|split| stmt.start() >= **split)
{
cell_offsets.next();
}
self.finalize(None);
}
}
// Track imports.
if matches!(stmt, Stmt::Import(_) | Stmt::ImportFrom(_))
&& !self
.exclusions
.iter()
.any(|exclusion| exclusion.contains(stmt.start()))
{
self.track_import(stmt);
} else {
self.finalize(self.trailer_for(stmt));
}
// Track scope.
let prev_nested = self.nested;
self.nested = true;
match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef { body, .. }) => {
for stmt in body {
self.visit_stmt(stmt);
}
self.finalize(None);
}
Stmt::ClassDef(ast::StmtClassDef { body, .. }) => {
for stmt in body {
self.visit_stmt(stmt);
}
self.finalize(None);
}
Stmt::For(ast::StmtFor { body, orelse, .. }) => {
for stmt in body {
self.visit_stmt(stmt);
}
self.finalize(None);
for stmt in orelse {
self.visit_stmt(stmt);
}
self.finalize(None);
}
Stmt::While(ast::StmtWhile { body, orelse, .. }) => {
for stmt in body {
self.visit_stmt(stmt);
}
self.finalize(None);
for stmt in orelse {
self.visit_stmt(stmt);
}
self.finalize(None);
}
Stmt::If(ast::StmtIf {
body,
elif_else_clauses,
..
}) => {
for stmt in body {
self.visit_stmt(stmt);
}
self.finalize(None);
for clause in elif_else_clauses {
self.visit_elif_else_clause(clause);
}
}
Stmt::With(ast::StmtWith { body, .. }) => {
for stmt in body {
self.visit_stmt(stmt);
}
self.finalize(None);
}
Stmt::Match(ast::StmtMatch { cases, .. }) => {
for match_case in cases {
self.visit_match_case(match_case);
}
}
Stmt::Try(ast::StmtTry {
body,
handlers,
orelse,
finalbody,
..
}) => {
for except_handler in handlers {
self.visit_except_handler(except_handler);
}
for stmt in body {
self.visit_stmt(stmt);
}
self.finalize(None);
for stmt in orelse {
self.visit_stmt(stmt);
}
self.finalize(None);
for stmt in finalbody {
self.visit_stmt(stmt);
}
self.finalize(None);
}
_ => {}
}
self.nested = prev_nested;
}
fn visit_except_handler(&mut self, except_handler: &'a ExceptHandler) {
let prev_nested = self.nested;
self.nested = true;
let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) =
except_handler;
for stmt in body {
self.visit_stmt(stmt);
}
self.finalize(None);
self.nested = prev_nested;
}
fn visit_match_case(&mut self, match_case: &'a MatchCase) {
for stmt in &match_case.body {
self.visit_stmt(stmt);
}
self.finalize(None);
}
fn visit_elif_else_clause(&mut self, elif_else_clause: &'a ElifElseClause) {
for stmt in &elif_else_clause.body {
self.visit_stmt(stmt);
}
self.finalize(None);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/types.rs | crates/ruff_linter/src/rules/isort/types.rs | use std::borrow::Cow;
use rustc_hash::FxHashMap;
use ruff_python_ast::helpers::format_import_from;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TrailingComma {
Present,
#[default]
Absent,
}
#[derive(Debug, Hash, Ord, PartialOrd, Eq, PartialEq, Clone)]
pub(crate) struct ImportFromData<'a> {
pub(crate) module: Option<&'a str>,
pub(crate) level: u32,
}
#[derive(Debug, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub(crate) struct AliasData<'a> {
pub(crate) name: &'a str,
pub(crate) asname: Option<&'a str>,
}
#[derive(Debug, Default, Clone)]
pub(crate) struct ImportCommentSet<'a> {
pub(crate) atop: Vec<Cow<'a, str>>,
pub(crate) inline: Vec<Cow<'a, str>>,
}
#[derive(Debug, Default, Clone)]
pub(crate) struct ImportFromCommentSet<'a> {
pub(crate) atop: Vec<Cow<'a, str>>,
pub(crate) inline: Vec<Cow<'a, str>>,
pub(crate) trailing: Vec<Cow<'a, str>>,
}
pub(crate) trait Importable<'a> {
fn module_name(&self) -> Cow<'a, str>;
fn module_base(&self) -> Cow<'a, str> {
match self.module_name() {
Cow::Borrowed(module_name) => Cow::Borrowed(
module_name
.split('.')
.next()
.expect("module to include at least one segment"),
),
Cow::Owned(module_name) => Cow::Owned(
module_name
.split('.')
.next()
.expect("module to include at least one segment")
.to_owned(),
),
}
}
}
impl<'a> Importable<'a> for AliasData<'a> {
fn module_name(&self) -> Cow<'a, str> {
Cow::Borrowed(self.name)
}
}
impl<'a> Importable<'a> for ImportFromData<'a> {
fn module_name(&self) -> Cow<'a, str> {
format_import_from(self.level, self.module)
}
}
#[derive(Debug, Default)]
pub(crate) struct ImportFromStatement<'a> {
pub(crate) comments: ImportFromCommentSet<'a>,
pub(crate) aliases: FxHashMap<AliasData<'a>, ImportFromCommentSet<'a>>,
pub(crate) trailing_comma: TrailingComma,
}
#[derive(Debug, Default)]
pub(crate) struct ImportBlock<'a> {
// Set of (name, asname), used to track regular imports.
// Ex) `import module`
pub(crate) import: FxHashMap<AliasData<'a>, ImportCommentSet<'a>>,
// Map from (module, level) to `AliasData`, used to track 'from' imports.
// Ex) `from module import member`
pub(crate) import_from: FxHashMap<ImportFromData<'a>, ImportFromStatement<'a>>,
// Set of (module, level, name, asname), used to track re-exported 'from' imports.
// Ex) `from module import member as member`
pub(crate) import_from_as:
FxHashMap<(ImportFromData<'a>, AliasData<'a>), ImportFromStatement<'a>>,
// Map from (module, level) to `AliasData`, used to track star imports.
// Ex) `from module import *`
pub(crate) import_from_star: FxHashMap<ImportFromData<'a>, ImportFromStatement<'a>>,
}
type Import<'a> = (AliasData<'a>, ImportCommentSet<'a>);
type ImportFrom<'a> = (
ImportFromData<'a>,
ImportFromCommentSet<'a>,
TrailingComma,
Vec<(AliasData<'a>, ImportFromCommentSet<'a>)>,
);
#[derive(Debug)]
pub(crate) enum EitherImport<'a> {
Import(Import<'a>),
ImportFrom(ImportFrom<'a>),
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/mod.rs | crates/ruff_linter/src/rules/isort/mod.rs | //! Rules from [isort](https://pypi.org/project/isort/).
use std::path::PathBuf;
use annotate::annotate_imports;
use block::{Block, Trailer};
pub(crate) use categorize::categorize;
use categorize::categorize_imports;
pub use categorize::{ImportSection, ImportType};
use comments::Comment;
use normalize::normalize_imports;
use order::order_imports;
use ruff_python_ast::PySourceType;
use ruff_python_ast::token::Tokens;
use ruff_python_codegen::Stylist;
use settings::Settings;
use types::EitherImport::{Import, ImportFrom};
use types::{AliasData, ImportBlock, TrailingComma};
use crate::Locator;
use crate::line_width::{LineLength, LineWidthBuilder};
use crate::package::PackageRoot;
use ruff_python_ast::PythonVersion;
mod annotate;
pub(crate) mod block;
pub mod categorize;
mod comments;
mod format;
mod helpers;
mod normalize;
mod order;
pub(crate) mod rules;
pub mod settings;
mod sorting;
mod split;
mod types;
#[derive(Debug)]
pub(crate) struct AnnotatedAliasData<'a> {
pub(crate) name: &'a str,
pub(crate) asname: Option<&'a str>,
pub(crate) atop: Vec<Comment<'a>>,
pub(crate) inline: Vec<Comment<'a>>,
pub(crate) trailing: Vec<Comment<'a>>,
}
#[derive(Debug)]
pub(crate) enum AnnotatedImport<'a> {
Import {
names: Vec<AliasData<'a>>,
atop: Vec<Comment<'a>>,
inline: Vec<Comment<'a>>,
},
ImportFrom {
module: Option<&'a str>,
names: Vec<AnnotatedAliasData<'a>>,
level: u32,
atop: Vec<Comment<'a>>,
inline: Vec<Comment<'a>>,
trailing: Vec<Comment<'a>>,
trailing_comma: TrailingComma,
},
}
#[expect(clippy::too_many_arguments)]
pub(crate) fn format_imports(
block: &Block,
comments: Vec<Comment>,
locator: &Locator,
line_length: LineLength,
indentation_width: LineWidthBuilder,
stylist: &Stylist,
src: &[PathBuf],
package: Option<PackageRoot<'_>>,
source_type: PySourceType,
target_version: PythonVersion,
settings: &Settings,
tokens: &Tokens,
) -> String {
let trailer = &block.trailer;
let block = annotate_imports(
&block.imports,
comments,
locator,
settings.split_on_trailing_comma,
tokens,
);
// Normalize imports (i.e., deduplicate, aggregate `from` imports).
let block = normalize_imports(block, settings);
// Categorize imports.
let mut output = String::new();
for block in split::split_by_forced_separate(block, &settings.forced_separate) {
let block_output = format_import_block(
block,
line_length,
indentation_width,
stylist,
src,
package,
target_version,
settings,
);
if !block_output.is_empty() && !output.is_empty() {
// If we are about to output something, and had already
// output a block, separate them.
output.push_str(&stylist.line_ending());
}
output.push_str(block_output.as_str());
}
let lines_after_imports = if source_type.is_stub() {
// Limit the number of lines after imports in stub files to at most 1 to be compatible with the formatter.
// `isort` does the same when using the profile `isort`
match settings.lines_after_imports {
0 => 0,
_ => 1,
}
} else {
settings.lines_after_imports
};
match trailer {
None => {}
Some(Trailer::Sibling) => {
if lines_after_imports >= 0 {
for _ in 0..lines_after_imports {
output.push_str(&stylist.line_ending());
}
} else {
output.push_str(&stylist.line_ending());
}
}
Some(Trailer::FunctionDef | Trailer::ClassDef) => {
if lines_after_imports >= 0 {
for _ in 0..lines_after_imports {
output.push_str(&stylist.line_ending());
}
} else {
output.push_str(&stylist.line_ending());
output.push_str(&stylist.line_ending());
}
}
}
output
}
#[expect(clippy::too_many_arguments)]
fn format_import_block(
block: ImportBlock,
line_length: LineLength,
indentation_width: LineWidthBuilder,
stylist: &Stylist,
src: &[PathBuf],
package: Option<PackageRoot<'_>>,
target_version: PythonVersion,
settings: &Settings,
) -> String {
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum LineInsertion {
/// A blank line should be inserted as soon as the next import is
/// of a different type (i.e., direct vs. `from`).
Necessary,
/// A blank line has already been inserted.
Inserted,
}
let mut block_by_type = categorize_imports(
block,
src,
package,
settings.detect_same_package,
&settings.known_modules,
target_version,
settings.no_sections,
&settings.section_order,
&settings.default_section,
);
let mut output = String::new();
// Generate replacement source code.
let mut is_first_block = true;
let mut pending_lines_before = false;
for import_section in &settings.section_order {
let import_block = block_by_type.remove(import_section);
if !settings.no_lines_before.contains(import_section) {
pending_lines_before = true;
}
let Some(import_block) = import_block else {
continue;
};
let imports = order_imports(import_block, import_section, settings);
// Add a blank line between every section.
if is_first_block {
is_first_block = false;
pending_lines_before = false;
} else if pending_lines_before {
output.push_str(&stylist.line_ending());
pending_lines_before = false;
}
let mut line_insertion = None;
let mut is_first_statement = true;
let lines_between_types = settings.lines_between_types;
for import in imports {
match import {
Import((alias, comments)) => {
// Add a blank lines between direct and from imports.
if settings.from_first
&& lines_between_types > 0
&& !settings.force_sort_within_sections
&& line_insertion == Some(LineInsertion::Necessary)
{
for _ in 0..lines_between_types {
output.push_str(&stylist.line_ending());
}
line_insertion = Some(LineInsertion::Inserted);
}
output.push_str(&format::format_import(
&alias,
&comments,
is_first_statement,
stylist,
));
if !settings.from_first {
line_insertion = Some(LineInsertion::Necessary);
}
}
ImportFrom((import_from, comments, trailing_comma, aliases)) => {
// Add a blank lines between direct and from imports.
if !settings.from_first
&& lines_between_types > 0
&& !settings.force_sort_within_sections
&& line_insertion == Some(LineInsertion::Necessary)
{
for _ in 0..lines_between_types {
output.push_str(&stylist.line_ending());
}
line_insertion = Some(LineInsertion::Inserted);
}
output.push_str(&format::format_import_from(
&import_from,
&comments,
&aliases,
line_length,
indentation_width,
stylist,
settings.force_wrap_aliases,
is_first_statement,
settings.split_on_trailing_comma
&& matches!(trailing_comma, TrailingComma::Present),
));
if settings.from_first {
line_insertion = Some(LineInsertion::Necessary);
}
}
}
is_first_statement = false;
}
}
output
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use std::path::Path;
use anyhow::Result;
use rustc_hash::{FxHashMap, FxHashSet};
use test_case::test_case;
use ruff_python_semantic::{MemberNameImport, ModuleNameImport, NameImport};
use crate::assert_diagnostics;
use crate::registry::Rule;
use crate::rules::isort::categorize::{ImportSection, KnownModules};
use crate::settings::LinterSettings;
use crate::test::{test_path, test_resource_path};
use super::categorize::ImportType;
use super::settings::RelativeImportsOrder;
#[test_case(Path::new("add_newline_before_comments.py"))]
#[test_case(Path::new("as_imports_comments.py"))]
#[test_case(Path::new("bom_sorted.py"))]
#[test_case(Path::new("bom_unsorted.py"))]
#[test_case(Path::new("combine_as_imports.py"))]
#[test_case(Path::new("combine_import_from.py"))]
#[test_case(Path::new("comments.py"))]
#[test_case(Path::new("deduplicate_imports.py"))]
#[test_case(Path::new("fit_line_length.py"))]
#[test_case(Path::new("fit_line_length_comment.py"))]
#[test_case(Path::new("force_sort_within_sections.py"))]
#[test_case(Path::new("force_to_top.py"))]
#[test_case(Path::new("force_wrap_aliases.py"))]
#[test_case(Path::new("future_from.py"))]
#[test_case(Path::new("if_elif_else.py"))]
#[test_case(Path::new("import_from_after_import.py"))]
#[test_case(Path::new("inline_comments.py"))]
#[test_case(Path::new("insert_empty_lines.py"))]
#[test_case(Path::new("insert_empty_lines.pyi"))]
#[test_case(Path::new("isort_skip_file.py"))]
#[test_case(Path::new("leading_prefix.py"))]
#[test_case(Path::new("magic_trailing_comma.py"))]
#[test_case(Path::new("match_case.py"))]
#[test_case(Path::new("natural_order.py"))]
#[test_case(Path::new("no_lines_before.py"))]
#[test_case(Path::new("no_reorder_within_section.py"))]
#[test_case(Path::new("no_wrap_star.py"))]
#[test_case(Path::new("order_by_type.py"))]
#[test_case(Path::new("order_by_type_with_custom_classes.py"))]
#[test_case(Path::new("order_by_type_with_custom_constants.py"))]
#[test_case(Path::new("order_by_type_with_custom_variables.py"))]
#[test_case(Path::new("order_relative_imports_by_level.py"))]
#[test_case(Path::new("preserve_comment_order.py"))]
#[test_case(Path::new("preserve_import_star.py"))]
#[test_case(Path::new("preserve_indentation.py"))]
#[test_case(Path::new("preserve_tabs.py"))]
#[test_case(Path::new("preserve_tabs_2.py"))]
#[test_case(Path::new("relative_imports_order.py"))]
#[test_case(Path::new("reorder_within_section.py"))]
#[test_case(Path::new("ruff_skip_file.py"))]
#[test_case(Path::new("separate_first_party_imports.py"))]
#[test_case(Path::new("separate_future_imports.py"))]
#[test_case(Path::new("separate_local_folder_imports.py"))]
#[test_case(Path::new("separate_third_party_imports.py"))]
#[test_case(Path::new("skip.py"))]
#[test_case(Path::new("sort_similar_imports.py"))]
#[test_case(Path::new("split.py"))]
#[test_case(Path::new("star_before_others.py"))]
#[test_case(Path::new("trailing_comment.py"))]
#[test_case(Path::new("trailing_suffix.py"))]
#[test_case(Path::new("two_space.py"))]
#[test_case(Path::new("type_comments.py"))]
#[test_case(Path::new("unicode.py"))]
fn default(path: &Path) -> Result<()> {
let snapshot = format!("{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
fn pattern(pattern: &str) -> glob::Pattern {
glob::Pattern::new(pattern).unwrap()
}
#[test_case(Path::new("separate_subpackage_first_and_third_party_imports.py"))]
fn separate_modules(path: &Path) -> Result<()> {
let snapshot = format!("1_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
known_modules: KnownModules::new(
vec![pattern("foo.bar"), pattern("baz")],
vec![pattern("foo"), pattern("__future__")],
vec![],
vec![],
FxHashMap::default(),
),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("separate_subpackage_first_and_third_party_imports.py"))]
fn separate_modules_glob(path: &Path) -> Result<()> {
let snapshot = format!("glob_1_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
known_modules: KnownModules::new(
vec![pattern("foo.*"), pattern("baz")],
vec![pattern("foo"), pattern("__future__")],
vec![],
vec![],
FxHashMap::default(),
),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("separate_subpackage_first_and_third_party_imports.py"))]
fn separate_modules_first_party(path: &Path) -> Result<()> {
let snapshot = format!("2_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
known_modules: KnownModules::new(
vec![pattern("foo")],
vec![pattern("foo.bar")],
vec![],
vec![],
FxHashMap::default(),
),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("line_ending_crlf.py"))]
#[test_case(Path::new("line_ending_lf.py"))]
fn source_code_style(path: &Path) -> Result<()> {
let snapshot = format!("{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
crate::assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("separate_local_folder_imports.py"))]
fn known_local_folder(path: &Path) -> Result<()> {
let snapshot = format!("known_local_folder_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
known_modules: KnownModules::new(
vec![],
vec![],
vec![pattern("ruff")],
vec![],
FxHashMap::default(),
),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("separate_local_folder_imports.py"))]
fn known_local_folder_closest(path: &Path) -> Result<()> {
let snapshot = format!("known_local_folder_closest_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
known_modules: KnownModules::new(
vec![],
vec![],
vec![pattern("ruff")],
vec![],
FxHashMap::default(),
),
relative_imports_order: RelativeImportsOrder::ClosestToFurthest,
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("case_sensitive.py"))]
fn case_sensitive(path: &Path) -> Result<()> {
let snapshot = format!("case_sensitive_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
case_sensitive: true,
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("force_to_top.py"))]
fn force_to_top(path: &Path) -> Result<()> {
let snapshot = format!("force_to_top_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
force_to_top: FxHashSet::from_iter([
"z".to_string(),
"lib1".to_string(),
"lib3".to_string(),
"lib5".to_string(),
"lib3.lib4".to_string(),
]),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("combine_as_imports.py"))]
fn combine_as_imports(path: &Path) -> Result<()> {
let snapshot = format!("combine_as_imports_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
combine_as_imports: true,
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("force_wrap_aliases.py"))]
fn force_wrap_aliases(path: &Path) -> Result<()> {
let snapshot = format!("force_wrap_aliases_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
force_wrap_aliases: true,
combine_as_imports: true,
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("magic_trailing_comma.py"))]
fn no_split_on_trailing_comma(path: &Path) -> Result<()> {
let snapshot = format!("split_on_trailing_comma_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
split_on_trailing_comma: false,
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("force_single_line.py"))]
fn force_single_line(path: &Path) -> Result<()> {
let snapshot = format!("force_single_line_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
force_single_line: true,
single_line_exclusions: FxHashSet::from_iter([
"os".to_string(),
"logging.handlers".to_string(),
]),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("propagate_inline_comments.py"))]
fn propagate_inline_comments(path: &Path) -> Result<()> {
let snapshot = format!("propagate_inline_comments_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
force_single_line: true,
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("order_by_type.py"))]
fn order_by_type(path: &Path) -> Result<()> {
let snapshot = format!("order_by_type_false_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
order_by_type: false,
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("order_by_type_with_custom_classes.py"))]
fn order_by_type_with_custom_classes(path: &Path) -> Result<()> {
let snapshot = format!(
"order_by_type_with_custom_classes_{}",
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
order_by_type: true,
classes: FxHashSet::from_iter([
"SVC".to_string(),
"SELU".to_string(),
"N_CLASS".to_string(),
"CLASS".to_string(),
]),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("order_by_type_with_custom_constants.py"))]
fn order_by_type_with_custom_constants(path: &Path) -> Result<()> {
let snapshot = format!(
"order_by_type_with_custom_constants_{}",
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
order_by_type: true,
constants: FxHashSet::from_iter([
"Const".to_string(),
"constant".to_string(),
"First".to_string(),
"Last".to_string(),
"A_constant".to_string(),
"konst".to_string(),
]),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("order_by_type_with_custom_variables.py"))]
fn order_by_type_with_custom_variables(path: &Path) -> Result<()> {
let snapshot = format!(
"order_by_type_with_custom_variables_{}",
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
order_by_type: true,
variables: FxHashSet::from_iter([
"VAR".to_string(),
"Variable".to_string(),
"MyVar".to_string(),
"var_ABC".to_string(),
]),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("force_sort_within_sections.py"))]
#[test_case(Path::new("force_sort_within_sections_with_as_names.py"))]
#[test_case(Path::new("force_sort_within_sections_future.py"))]
fn force_sort_within_sections(path: &Path) -> Result<()> {
let snapshot = format!("force_sort_within_sections_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
force_sort_within_sections: true,
force_to_top: FxHashSet::from_iter(["z".to_string()]),
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("force_sort_within_sections_lines_between.py"))]
fn force_sort_within_sections_lines_between(path: &Path) -> Result<()> {
let snapshot = format!("force_sort_within_sections_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
isort: super::settings::Settings {
force_sort_within_sections: true,
lines_between_types: 2,
..super::settings::Settings::default()
},
src: vec![test_resource_path("fixtures/isort")],
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("comment.py"))]
#[test_case(Path::new("comments_and_newlines.py"))]
#[test_case(Path::new("docstring.py"))]
#[test_case(Path::new("docstring.pyi"))]
#[test_case(Path::new("docstring_followed_by_continuation.py"))]
#[test_case(Path::new("docstring_only.py"))]
#[test_case(Path::new("docstring_with_continuation.py"))]
#[test_case(Path::new("docstring_with_multiple_continuations.py"))]
#[test_case(Path::new("docstring_with_semicolon.py"))]
#[test_case(Path::new("empty.py"))]
#[test_case(Path::new("existing_import.py"))]
#[test_case(Path::new("multiline_docstring.py"))]
#[test_case(Path::new("off.py"))]
#[test_case(Path::new("whitespace.py"))]
fn required_import(path: &Path) -> Result<()> {
let snapshot = format!("required_import_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort/required_imports").join(path).as_path(),
&LinterSettings {
src: vec![test_resource_path("fixtures/isort")],
isort: super::settings::Settings {
required_imports: BTreeSet::from_iter([NameImport::ImportFrom(
MemberNameImport::member(
"__future__".to_string(),
"annotations".to_string(),
),
)]),
..super::settings::Settings::default()
},
..LinterSettings::for_rule(Rule::MissingRequiredImport)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("comment.py"))]
#[test_case(Path::new("comments_and_newlines.py"))]
#[test_case(Path::new("docstring.py"))]
#[test_case(Path::new("docstring.pyi"))]
#[test_case(Path::new("docstring_followed_by_continuation.py"))]
#[test_case(Path::new("docstring_only.py"))]
#[test_case(Path::new("docstring_with_continuation.py"))]
#[test_case(Path::new("docstring_with_multiple_continuations.py"))]
#[test_case(Path::new("docstring_with_semicolon.py"))]
#[test_case(Path::new("empty.py"))]
#[test_case(Path::new("existing_import.py"))]
#[test_case(Path::new("multiline_docstring.py"))]
#[test_case(Path::new("off.py"))]
fn required_import_with_alias(path: &Path) -> Result<()> {
let snapshot = format!("required_import_with_alias_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort/required_imports").join(path).as_path(),
&LinterSettings {
src: vec![test_resource_path("fixtures/isort")],
isort: super::settings::Settings {
required_imports: BTreeSet::from_iter([NameImport::ImportFrom(
MemberNameImport::alias(
"__future__".to_string(),
"annotations".to_string(),
"_annotations".to_string(),
),
)]),
..super::settings::Settings::default()
},
..LinterSettings::for_rule(Rule::MissingRequiredImport)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | true |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/format.rs | crates/ruff_linter/src/rules/isort/format.rs | use ruff_python_codegen::Stylist;
use crate::line_width::{LineLength, LineWidthBuilder};
use super::types::{AliasData, ImportCommentSet, ImportFromCommentSet, ImportFromData, Importable};
// Guess a capacity to use for string allocation.
const CAPACITY: usize = 200;
/// Add a plain import statement to the [`RopeBuilder`].
pub(crate) fn format_import(
alias: &AliasData,
comments: &ImportCommentSet,
is_first: bool,
stylist: &Stylist,
) -> String {
let mut output = String::with_capacity(CAPACITY);
if !is_first && !comments.atop.is_empty() {
output.push_str(&stylist.line_ending());
}
for comment in &comments.atop {
output.push_str(comment);
output.push_str(&stylist.line_ending());
}
if let Some(asname) = alias.asname {
output.push_str("import ");
output.push_str(alias.name);
output.push_str(" as ");
output.push_str(asname);
} else {
output.push_str("import ");
output.push_str(alias.name);
}
for comment in &comments.inline {
output.push_str(" ");
output.push_str(comment);
}
output.push_str(&stylist.line_ending());
output
}
/// Add an import-from statement to the [`RopeBuilder`].
#[expect(clippy::too_many_arguments)]
pub(crate) fn format_import_from(
import_from: &ImportFromData,
comments: &ImportFromCommentSet,
aliases: &[(AliasData, ImportFromCommentSet)],
line_length: LineLength,
indentation_width: LineWidthBuilder,
stylist: &Stylist,
force_wrap_aliases: bool,
is_first: bool,
trailing_comma: bool,
) -> String {
if aliases.len() == 1
&& aliases
.iter()
.all(|(alias, _)| alias.name == "*" && alias.asname.is_none())
{
let (single_line, ..) = format_single_line(
import_from,
comments,
aliases,
is_first,
stylist,
indentation_width,
);
return single_line;
}
// We can only inline if none of the aliases have comments.
if !trailing_comma
&& (aliases.len() == 1
|| aliases.iter().all(
|(
_,
ImportFromCommentSet {
atop,
inline,
trailing,
},
)| atop.is_empty() && inline.is_empty() && trailing.is_empty(),
))
&& (!force_wrap_aliases
|| aliases.len() == 1
|| aliases.iter().all(|(alias, _)| alias.asname.is_none()))
{
let (single_line, import_width) = format_single_line(
import_from,
comments,
aliases,
is_first,
stylist,
indentation_width,
);
if import_width <= line_length || aliases.iter().any(|(alias, _)| alias.name == "*") {
return single_line;
}
}
format_multi_line(import_from, comments, aliases, is_first, stylist)
}
/// Format an import-from statement in single-line format.
///
/// This method assumes that the output source code is syntactically valid.
fn format_single_line(
import_from: &ImportFromData,
comments: &ImportFromCommentSet,
aliases: &[(AliasData, ImportFromCommentSet)],
is_first: bool,
stylist: &Stylist,
indentation_width: LineWidthBuilder,
) -> (String, LineWidthBuilder) {
let mut output = String::with_capacity(CAPACITY);
let mut line_width = indentation_width;
if !is_first && !comments.atop.is_empty() {
output.push_str(&stylist.line_ending());
}
for comment in &comments.atop {
output.push_str(comment);
output.push_str(&stylist.line_ending());
}
let module_name = import_from.module_name();
output.push_str("from ");
output.push_str(&module_name);
output.push_str(" import ");
line_width = line_width.add_width(5).add_str(&module_name).add_width(8);
for (index, (AliasData { name, asname }, _)) in aliases.iter().enumerate() {
if let Some(asname) = asname {
output.push_str(name);
output.push_str(" as ");
output.push_str(asname);
line_width = line_width.add_str(name).add_width(4).add_str(asname);
} else {
output.push_str(name);
line_width = line_width.add_str(name);
}
if index < aliases.len() - 1 {
output.push_str(", ");
line_width = line_width.add_width(2);
}
}
for comment in &comments.inline {
output.push(' ');
output.push(' ');
output.push_str(comment);
line_width = line_width.add_width(2).add_str(comment);
}
for (_, comments) in aliases {
for comment in &comments.atop {
output.push(' ');
output.push(' ');
output.push_str(comment);
line_width = line_width.add_width(2).add_str(comment);
}
for comment in &comments.inline {
output.push(' ');
output.push(' ');
output.push_str(comment);
line_width = line_width.add_width(2).add_str(comment);
}
for comment in &comments.trailing {
output.push(' ');
output.push(' ');
output.push_str(comment);
line_width = line_width.add_width(2).add_str(comment);
}
}
for comment in &comments.trailing {
output.push(' ');
output.push(' ');
output.push_str(comment);
line_width = line_width.add_width(2).add_str(comment);
}
output.push_str(&stylist.line_ending());
(output, line_width)
}
/// Format an import-from statement in multi-line format.
fn format_multi_line(
import_from: &ImportFromData,
comments: &ImportFromCommentSet,
aliases: &[(AliasData, ImportFromCommentSet)],
is_first: bool,
stylist: &Stylist,
) -> String {
let mut output = String::with_capacity(CAPACITY);
if !is_first && !comments.atop.is_empty() {
output.push_str(&stylist.line_ending());
}
for comment in &comments.atop {
output.push_str(comment);
output.push_str(&stylist.line_ending());
}
output.push_str("from ");
output.push_str(&import_from.module_name());
output.push_str(" import ");
output.push('(');
for comment in &comments.inline {
output.push(' ');
output.push(' ');
output.push_str(comment);
}
output.push_str(&stylist.line_ending());
for (AliasData { name, asname }, comments) in aliases {
for comment in &comments.atop {
output.push_str(stylist.indentation());
output.push_str(comment);
output.push_str(&stylist.line_ending());
}
output.push_str(stylist.indentation());
if let Some(asname) = asname {
output.push_str(name);
output.push_str(" as ");
output.push_str(asname);
} else {
output.push_str(name);
}
output.push(',');
for comment in &comments.inline {
output.push(' ');
output.push(' ');
output.push_str(comment);
}
output.push_str(&stylist.line_ending());
for comment in &comments.trailing {
output.push_str(stylist.indentation());
output.push_str(comment);
output.push_str(&stylist.line_ending());
}
}
output.push(')');
for comment in &comments.trailing {
output.push_str(" ");
output.push_str(comment);
}
output.push_str(&stylist.line_ending());
output
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/annotate.rs | crates/ruff_linter/src/rules/isort/annotate.rs | use ruff_python_ast::token::Tokens;
use ruff_python_ast::{self as ast, Stmt};
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use super::comments::Comment;
use super::helpers::trailing_comma;
use super::types::{AliasData, TrailingComma};
use super::{AnnotatedAliasData, AnnotatedImport};
pub(crate) fn annotate_imports<'a>(
imports: &'a [&'a Stmt],
comments: Vec<Comment<'a>>,
locator: &Locator<'a>,
split_on_trailing_comma: bool,
tokens: &Tokens,
) -> Vec<AnnotatedImport<'a>> {
let mut comments_iter = comments.into_iter().peekable();
imports
.iter()
.map(|import| {
match import {
Stmt::Import(ast::StmtImport {
names,
range,
node_index: _,
}) => {
// Find comments above.
let mut atop = vec![];
while let Some(comment) =
comments_iter.next_if(|comment| comment.start() < range.start())
{
atop.push(comment);
}
// Find comments inline.
let mut inline = vec![];
let import_line_end = locator.line_end(range.end());
while let Some(comment) =
comments_iter.next_if(|comment| comment.end() <= import_line_end)
{
inline.push(comment);
}
AnnotatedImport::Import {
names: names
.iter()
.map(|alias| AliasData {
name: locator.slice(&alias.name),
asname: alias.asname.as_ref().map(|asname| locator.slice(asname)),
})
.collect(),
atop,
inline,
}
}
Stmt::ImportFrom(ast::StmtImportFrom {
module,
names,
level,
range: _,
node_index: _,
}) => {
// Find comments above.
let mut atop = vec![];
while let Some(comment) =
comments_iter.next_if(|comment| comment.start() < import.start())
{
atop.push(comment);
}
// Find comments inline.
// We associate inline comments with the import statement unless there's a
// single member, and it's a single-line import (like `from foo
// import bar # noqa`).
let mut inline = vec![];
if names.len() > 1
|| names.first().is_some_and(|alias| {
locator
.contains_line_break(TextRange::new(import.start(), alias.start()))
})
{
let import_start_line_end = locator.line_end(import.start());
while let Some(comment) =
comments_iter.next_if(|comment| comment.end() <= import_start_line_end)
{
inline.push(comment);
}
}
// Capture names.
let mut aliases: Vec<_> = names
.iter()
.map(|alias| {
// Find comments above.
let mut alias_atop = vec![];
while let Some(comment) =
comments_iter.next_if(|comment| comment.start() < alias.start())
{
alias_atop.push(comment);
}
// Find comments inline.
let mut alias_inline = vec![];
let alias_line_end = locator.line_end(alias.end());
while let Some(comment) =
comments_iter.next_if(|comment| comment.end() <= alias_line_end)
{
alias_inline.push(comment);
}
AnnotatedAliasData {
name: locator.slice(&alias.name),
asname: alias.asname.as_ref().map(|asname| locator.slice(asname)),
atop: alias_atop,
inline: alias_inline,
trailing: vec![],
}
})
.collect();
// Capture trailing comments on the _last_ alias, as in:
// ```python
// from foo import (
// bar,
// # noqa
// )
// ```
if let Some(last_alias) = aliases.last_mut() {
while let Some(comment) =
comments_iter.next_if(|comment| comment.start() < import.end())
{
last_alias.trailing.push(comment);
}
}
// Capture trailing comments, as in:
// ```python
// from foo import (
// bar,
// ) # noqa
// ```
let mut trailing = vec![];
let import_line_end = locator.line_end(import.end());
while let Some(comment) =
comments_iter.next_if(|comment| comment.start() < import_line_end)
{
trailing.push(comment);
}
AnnotatedImport::ImportFrom {
module: module.as_ref().map(|module| locator.slice(module)),
names: aliases,
level: *level,
trailing_comma: if split_on_trailing_comma {
trailing_comma(import, tokens)
} else {
TrailingComma::default()
},
atop,
inline,
trailing,
}
}
_ => panic!("Expected Stmt::Import | Stmt::ImportFrom"),
}
})
.collect()
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/normalize.rs | crates/ruff_linter/src/rules/isort/normalize.rs | use super::AnnotatedImport;
use super::settings::Settings;
use super::types::{AliasData, ImportBlock, ImportFromData, TrailingComma};
pub(crate) fn normalize_imports<'a>(
imports: Vec<AnnotatedImport<'a>>,
settings: &Settings,
) -> ImportBlock<'a> {
let mut block = ImportBlock::default();
for import in imports {
match import {
AnnotatedImport::Import {
names,
atop,
inline,
} => {
// Associate the comments with the first alias (best effort).
if let Some(name) = names.first() {
let comment_set = block
.import
.entry(AliasData {
name: name.name,
asname: name.asname,
})
.or_default();
for comment in atop {
comment_set.atop.push(comment.value);
}
for comment in inline {
comment_set.inline.push(comment.value);
}
}
// Create an entry for every alias.
for name in &names {
block
.import
.entry(AliasData {
name: name.name,
asname: name.asname,
})
.or_default();
}
}
AnnotatedImport::ImportFrom {
module,
names,
level,
atop,
inline,
trailing,
trailing_comma,
} => {
// Whether to track each member of the import as a separate entry.
let isolate_aliases = settings.force_single_line
&& module
.is_none_or(|module| !settings.single_line_exclusions.contains(module))
&& names.first().is_none_or(|alias| alias.name != "*");
// Insert comments on the statement itself.
if isolate_aliases {
let mut first = true;
for alias in &names {
let import_from = block
.import_from_as
.entry((
ImportFromData { module, level },
AliasData {
name: alias.name,
asname: alias.asname,
},
))
.or_default();
// Associate the comments above the import statement with the first alias
// (best effort).
if std::mem::take(&mut first) {
for comment in &atop {
import_from.comments.atop.push(comment.value.clone());
}
}
// Replicate the inline (and after) comments onto every member.
for comment in &inline {
import_from.comments.inline.push(comment.value.clone());
}
for comment in &trailing {
import_from.comments.trailing.push(comment.value.clone());
}
}
} else {
if let Some(alias) = names.first() {
let import_from = if alias.name == "*" {
block
.import_from_star
.entry(ImportFromData { module, level })
.or_default()
} else if alias.asname.is_none() || settings.combine_as_imports {
block
.import_from
.entry(ImportFromData { module, level })
.or_default()
} else {
block
.import_from_as
.entry((
ImportFromData { module, level },
AliasData {
name: alias.name,
asname: alias.asname,
},
))
.or_default()
};
for comment in atop {
import_from.comments.atop.push(comment.value);
}
for comment in inline {
import_from.comments.inline.push(comment.value);
}
for comment in trailing {
import_from.comments.trailing.push(comment.value);
}
}
}
// Create an entry for every alias (member) within the statement.
for alias in names {
let import_from = if alias.name == "*" {
block
.import_from_star
.entry(ImportFromData { module, level })
.or_default()
} else if !isolate_aliases
&& (alias.asname.is_none() || settings.combine_as_imports)
{
block
.import_from
.entry(ImportFromData { module, level })
.or_default()
} else {
block
.import_from_as
.entry((
ImportFromData { module, level },
AliasData {
name: alias.name,
asname: alias.asname,
},
))
.or_default()
};
let comment_set = import_from
.aliases
.entry(AliasData {
name: alias.name,
asname: alias.asname,
})
.or_default();
for comment in alias.atop {
comment_set.atop.push(comment.value);
}
for comment in alias.inline {
comment_set.inline.push(comment.value);
}
for comment in alias.trailing {
comment_set.trailing.push(comment.value);
}
// Propagate trailing commas.
if !isolate_aliases && matches!(trailing_comma, TrailingComma::Present) {
import_from.trailing_comma = TrailingComma::Present;
}
}
}
}
}
block
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/split.rs | crates/ruff_linter/src/rules/isort/split.rs | use crate::rules::isort::types::{ImportBlock, Importable};
/// Find the index of the block that the import should be placed in.
/// The index is the position of the pattern in `forced_separate` plus one.
/// If the import is not matched by any of the patterns, return 0 (the first
/// block).
fn find_block_index(forced_separate: &[String], imp: &dyn Importable) -> usize {
forced_separate
.iter()
.position(|pattern| imp.module_base().starts_with(pattern))
.map_or(0, |position| position + 1)
}
/// Split the import block into multiple blocks, where the first block is the
/// imports that are not matched by any of the patterns in `forced_separate`,
/// and the rest of the blocks are the imports that _are_ matched by the
/// patterns in `forced_separate`, in the order they appear in the
/// `forced_separate` set. Empty blocks are retained for patterns that do not
/// match any imports.
pub(crate) fn split_by_forced_separate<'a>(
block: ImportBlock<'a>,
forced_separate: &[String],
) -> Vec<ImportBlock<'a>> {
if forced_separate.is_empty() {
// Nothing to do here.
return vec![block];
}
let mut blocks = vec![ImportBlock::default()]; // The zeroth block is for non-forced-separate imports.
for _ in forced_separate {
// Populate the blocks with empty blocks for each forced_separate pattern.
blocks.push(ImportBlock::default());
}
let ImportBlock {
import,
import_from,
import_from_as,
import_from_star,
} = block;
for (imp, comment_set) in import {
blocks[find_block_index(forced_separate, &imp)]
.import
.insert(imp, comment_set);
}
for (imp, val) in import_from {
blocks[find_block_index(forced_separate, &imp)]
.import_from
.insert(imp, val);
}
for ((imp, alias), val) in import_from_as {
blocks[find_block_index(forced_separate, &imp)]
.import_from_as
.insert((imp, alias), val);
}
for (imp, comment_set) in import_from_star {
blocks[find_block_index(forced_separate, &imp)]
.import_from_star
.insert(imp, comment_set);
}
blocks
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/rules/add_required_imports.rs | crates/ruff_linter/src/rules/isort/rules/add_required_imports.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_docstring_stmt;
use ruff_python_ast::{self as ast, ModModule, PySourceType, Stmt};
use ruff_python_codegen::Stylist;
use ruff_python_parser::Parsed;
use ruff_python_semantic::{FutureImport, NameImport};
use ruff_text_size::{TextRange, TextSize};
use crate::Locator;
use crate::checkers::ast::LintContext;
use crate::importer::Importer;
use crate::settings::LinterSettings;
use crate::{AlwaysFixableViolation, Fix};
/// ## What it does
/// Adds any required imports, as specified by the user, to the top of the
/// file.
///
/// ## Why is this bad?
/// In some projects, certain imports are required to be present in all
/// files. For example, some projects assume that
/// `from __future__ import annotations` is enabled,
/// and thus require that import to be
/// present in all files. Omitting a "required" import (as specified by
/// the user) can cause errors or unexpected behavior.
///
/// ## Example
/// ```python
/// import typing
/// ```
///
/// Use instead:
/// ```python
/// from __future__ import annotations
///
/// import typing
/// ```
///
/// ## Options
/// - `lint.isort.required-imports`
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.218")]
pub(crate) struct MissingRequiredImport(pub String);
impl AlwaysFixableViolation for MissingRequiredImport {
#[derive_message_formats]
fn message(&self) -> String {
let MissingRequiredImport(name) = self;
format!("Missing required import: `{name}`")
}
fn fix_title(&self) -> String {
let MissingRequiredImport(name) = self;
format!("Insert required import: `{name}`")
}
}
/// Return `true` if the [`Stmt`] includes the given [`AnyImportRef`].
fn includes_import(stmt: &Stmt, target: &NameImport) -> bool {
match target {
NameImport::Import(target) => {
let Stmt::Import(ast::StmtImport {
names,
range: _,
node_index: _,
}) = &stmt
else {
return false;
};
names.iter().any(|alias| {
alias.name == target.name.name
&& alias.asname.as_deref() == target.name.as_name.as_deref()
})
}
NameImport::ImportFrom(target) => {
let Stmt::ImportFrom(ast::StmtImportFrom {
module,
names,
level,
range: _,
node_index: _,
}) = &stmt
else {
return false;
};
module.as_deref() == target.module.as_deref()
&& *level == target.level
&& names.iter().any(|alias| {
alias.name == target.name.name
&& alias.asname.as_deref() == target.name.as_name.as_deref()
})
}
}
}
fn add_required_import(
required_import: &NameImport,
parsed: &Parsed<ModModule>,
locator: &Locator,
stylist: &Stylist,
source_type: PySourceType,
context: &LintContext,
) {
// Don't add imports to semantically-empty files.
if parsed.suite().iter().all(is_docstring_stmt) {
return;
}
// We don't need to add `__future__` imports to stubs.
if source_type.is_stub() && required_import.is_future_import() {
return;
}
// If the import is already present in a top-level block, don't add it.
if parsed
.suite()
.iter()
.any(|stmt| includes_import(stmt, required_import))
{
return;
}
// Always insert the diagnostic at top-of-file.
let mut diagnostic = context.report_diagnostic(
MissingRequiredImport(required_import.to_string()),
TextRange::default(),
);
diagnostic.set_fix(Fix::safe_edit(
Importer::new(parsed, locator.contents(), stylist)
.add_import(required_import, TextSize::default()),
));
}
/// I002
pub(crate) fn add_required_imports(
parsed: &Parsed<ModModule>,
locator: &Locator,
stylist: &Stylist,
settings: &LinterSettings,
source_type: PySourceType,
context: &LintContext,
) {
for required_import in &settings.isort.required_imports {
add_required_import(
required_import,
parsed,
locator,
stylist,
source_type,
context,
);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/rules/organize_imports.rs | crates/ruff_linter/src/rules/isort/rules/organize_imports.rs | use itertools::{EitherOrBoth, Itertools};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::Tokens;
use ruff_python_ast::whitespace::trailing_lines_end;
use ruff_python_ast::{PySourceType, PythonVersion, Stmt};
use ruff_python_codegen::Stylist;
use ruff_python_index::Indexer;
use ruff_python_trivia::{PythonWhitespace, leading_indentation, textwrap::indent};
use ruff_source_file::{LineRanges, UniversalNewlines};
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::LintContext;
use crate::line_width::LineWidthBuilder;
use crate::package::PackageRoot;
use crate::rules::isort::block::Block;
use crate::rules::isort::{comments, format_imports};
use crate::settings::LinterSettings;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// De-duplicates, groups, and sorts imports based on the provided `isort` settings.
///
/// ## Why is this bad?
/// Consistency is good. Use a common convention for imports to make your code
/// more readable and idiomatic.
///
/// ## Example
/// ```python
/// import pandas
/// import numpy as np
/// ```
///
/// Use instead:
/// ```python
/// import numpy as np
/// import pandas
/// ```
///
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.110")]
pub(crate) struct UnsortedImports;
impl Violation for UnsortedImports {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Import block is un-sorted or un-formatted".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Organize imports".to_string())
}
}
fn extract_range(body: &[&Stmt]) -> TextRange {
let location = body.first().unwrap().start();
let end_location = body.last().unwrap().end();
TextRange::new(location, end_location)
}
fn extract_indentation_range(body: &[&Stmt], locator: &Locator) -> TextRange {
let location = body.first().unwrap().start();
TextRange::new(locator.line_start(location), location)
}
/// Compares two strings, returning true if they are equal modulo whitespace
/// at the start of each line.
fn matches_ignoring_indentation(val1: &str, val2: &str) -> bool {
val1.universal_newlines()
.zip_longest(val2.universal_newlines())
.all(|pair| match pair {
EitherOrBoth::Both(line1, line2) => {
line1.trim_whitespace_start() == line2.trim_whitespace_start()
}
_ => false,
})
}
#[expect(clippy::too_many_arguments)]
/// I001
pub(crate) fn organize_imports(
block: &Block,
locator: &Locator,
stylist: &Stylist,
indexer: &Indexer,
settings: &LinterSettings,
package: Option<PackageRoot<'_>>,
source_type: PySourceType,
tokens: &Tokens,
target_version: PythonVersion,
context: &LintContext,
) {
let indentation = locator.slice(extract_indentation_range(&block.imports, locator));
let indentation = leading_indentation(indentation);
let range = extract_range(&block.imports);
// Special-cases: there's leading or trailing content in the import block. These
// are too hard to get right, and relatively rare, so flag but don't fix.
if indexer.preceded_by_multi_statement_line(block.imports.first().unwrap(), locator.contents())
|| indexer
.followed_by_multi_statement_line(block.imports.last().unwrap(), locator.contents())
{
context.report_diagnostic(UnsortedImports, range);
return;
}
// Extract comments. Take care to grab any inline comments from the last line.
let comments = comments::collect_comments(
TextRange::new(range.start(), locator.full_line_end(range.end())),
locator,
indexer.comment_ranges(),
);
let trailing_line_end = if block.trailer.is_none() {
locator.full_line_end(range.end())
} else {
trailing_lines_end(block.imports.last().unwrap(), locator.contents())
};
// Generate the sorted import block.
let expected = format_imports(
block,
comments,
locator,
settings.line_length,
LineWidthBuilder::new(settings.tab_size).add_str(indentation),
stylist,
&settings.src,
package,
source_type,
target_version,
&settings.isort,
tokens,
);
// Expand the span the entire range, including leading and trailing space.
let fix_range = TextRange::new(locator.line_start(range.start()), trailing_line_end);
let actual = locator.slice(fix_range);
if matches_ignoring_indentation(actual, &expected) {
return;
}
let mut diagnostic = context.report_diagnostic(UnsortedImports, range);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
indent(&expected, indentation).to_string(),
fix_range,
)));
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/isort/rules/mod.rs | crates/ruff_linter/src/rules/isort/rules/mod.rs | pub(crate) use add_required_imports::*;
pub(crate) use organize_imports::*;
pub(crate) mod add_required_imports;
pub(crate) mod organize_imports;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_tidy_imports/settings.rs | crates/ruff_linter/src/rules/flake8_tidy_imports/settings.rs | use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use crate::display_settings;
use ruff_macros::CacheKey;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, CacheKey)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ApiBan {
/// The message to display when the API is used.
pub msg: String,
}
impl Display for ApiBan {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.msg)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, CacheKey, Default)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum Strictness {
/// Ban imports that extend into the parent module or beyond.
#[default]
Parents,
/// Ban all relative imports.
All,
}
impl Display for Strictness {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Parents => write!(f, "\"parents\""),
Self::All => write!(f, "\"all\""),
}
}
}
#[derive(Debug, Clone, CacheKey, Default)]
pub struct Settings {
pub ban_relative_imports: Strictness,
pub banned_api: FxHashMap<String, ApiBan>,
pub banned_module_level_imports: Vec<String>,
}
impl Settings {
pub fn banned_module_level_imports(&self) -> impl Iterator<Item = &str> {
self.banned_module_level_imports.iter().map(AsRef::as_ref)
}
}
impl Display for Settings {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.flake8_tidy_imports",
fields = [
self.ban_relative_imports,
self.banned_api | map,
self.banned_module_level_imports | array,
]
}
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.