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/pep8_naming/rules/camelcase_imported_as_acronym.rs | crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Alias, Stmt};
use ruff_python_stdlib::str::{self};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::pep8_naming::helpers;
/// ## What it does
/// Checks for `CamelCase` imports that are aliased as acronyms.
///
/// ## Why is this bad?
/// [PEP 8] recommends naming conventions for classes, functions,
/// constants, and more. The use of inconsistent naming styles between
/// import and alias names may lead readers to expect an import to be of
/// another type (e.g., confuse a Python class with a constant).
///
/// Import aliases should thus follow the same naming style as the member
/// being imported.
///
/// Note that this rule is distinct from `camelcase-imported-as-constant`
/// to accommodate selective enforcement.
///
/// Also note that import aliases following an import convention according to the
/// [`lint.flake8-import-conventions.aliases`] option are allowed.
///
/// ## Example
/// ```python
/// from example import MyClassName as MCN
/// ```
///
/// Use instead:
/// ```python
/// from example import MyClassName
/// ```
///
/// ## Options
/// - `lint.flake8-import-conventions.aliases`
/// - `lint.pep8-naming.ignore-names`
/// - `lint.pep8-naming.extend-ignore-names`
///
/// [PEP 8]: https://peps.python.org/pep-0008/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.82")]
pub(crate) struct CamelcaseImportedAsAcronym {
name: String,
asname: String,
}
impl Violation for CamelcaseImportedAsAcronym {
#[derive_message_formats]
fn message(&self) -> String {
let CamelcaseImportedAsAcronym { name, asname } = self;
format!("CamelCase `{name}` imported as acronym `{asname}`")
}
}
/// N817
pub(crate) fn camelcase_imported_as_acronym(
name: &str,
asname: &str,
alias: &Alias,
stmt: &Stmt,
checker: &Checker,
) {
if helpers::is_camelcase(name)
&& !str::is_cased_lowercase(asname)
&& str::is_cased_uppercase(asname)
&& helpers::is_acronym(name, asname)
{
let ignore_names = &checker.settings().pep8_naming.ignore_names;
// Ignore any explicitly-allowed names.
if ignore_names.matches(name) || ignore_names.matches(asname) {
return;
}
// Ignore names that follow a community-agreed import convention.
if is_ignored_because_of_import_convention(asname, stmt, alias, checker) {
return;
}
let mut diagnostic = checker.report_diagnostic(
CamelcaseImportedAsAcronym {
name: name.to_string(),
asname: asname.to_string(),
},
alias.range(),
);
diagnostic.set_parent(stmt.start());
}
}
fn is_ignored_because_of_import_convention(
asname: &str,
stmt: &Stmt,
alias: &Alias,
checker: &Checker,
) -> bool {
let full_name = if let Some(import_from) = stmt.as_import_from_stmt() {
// Never test relative imports for exclusion because we can't resolve the full-module name.
let Some(module) = import_from.module.as_ref() else {
return false;
};
if import_from.level != 0 {
return false;
}
std::borrow::Cow::Owned(format!("{module}.{}", alias.name))
} else {
std::borrow::Cow::Borrowed(&*alias.name)
};
// Ignore names that follow a community-agreed import convention.
checker
.settings()
.flake8_import_conventions
.aliases
.get(&*full_name)
.map(String::as_str)
== Some(asname)
}
| 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/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs | crates/ruff_linter/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Alias, Stmt};
use ruff_python_stdlib::str;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::pep8_naming::settings::IgnoreNames;
/// ## What it does
/// Checks for lowercase imports that are aliased to non-lowercase names.
///
/// ## Why is this bad?
/// [PEP 8] recommends naming conventions for classes, functions,
/// constants, and more. The use of inconsistent naming styles between
/// import and alias names may lead readers to expect an import to be of
/// another type (e.g., confuse a Python class with a constant).
///
/// Import aliases should thus follow the same naming style as the member
/// being imported.
///
/// ## Example
/// ```python
/// from example import myclassname as MyClassName
/// ```
///
/// Use instead:
/// ```python
/// from example import myclassname
/// ```
///
/// ## Options
/// - `lint.pep8-naming.ignore-names`
/// - `lint.pep8-naming.extend-ignore-names`
///
/// [PEP 8]: https://peps.python.org/pep-0008/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.82")]
pub(crate) struct LowercaseImportedAsNonLowercase {
name: String,
asname: String,
}
impl Violation for LowercaseImportedAsNonLowercase {
#[derive_message_formats]
fn message(&self) -> String {
let LowercaseImportedAsNonLowercase { name, asname } = self;
format!("Lowercase `{name}` imported as non-lowercase `{asname}`")
}
}
/// N812
pub(crate) fn lowercase_imported_as_non_lowercase(
checker: &Checker,
name: &str,
asname: &str,
alias: &Alias,
stmt: &Stmt,
ignore_names: &IgnoreNames,
) {
if !str::is_cased_uppercase(name) && str::is_cased_lowercase(name) && !str::is_lowercase(asname)
{
// Ignore any explicitly-allowed names.
if ignore_names.matches(name) || ignore_names.matches(asname) {
return;
}
let mut diagnostic = checker.report_diagnostic(
LowercaseImportedAsNonLowercase {
name: name.to_string(),
asname: asname.to_string(),
},
alias.range(),
);
diagnostic.set_parent(stmt.start());
}
}
| 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/pep8_naming/rules/mod.rs | crates/ruff_linter/src/rules/pep8_naming/rules/mod.rs | pub(crate) use camelcase_imported_as_acronym::*;
pub(crate) use camelcase_imported_as_constant::*;
pub(crate) use camelcase_imported_as_lowercase::*;
pub(crate) use constant_imported_as_non_constant::*;
pub(crate) use dunder_function_name::*;
pub(crate) use error_suffix_on_exception_name::*;
pub(crate) use invalid_argument_name::*;
pub(crate) use invalid_class_name::*;
pub(crate) use invalid_first_argument_name::*;
pub(crate) use invalid_function_name::*;
pub(crate) use invalid_module_name::*;
pub(crate) use lowercase_imported_as_non_lowercase::*;
pub(crate) use mixed_case_variable_in_class_scope::*;
pub(crate) use mixed_case_variable_in_global_scope::*;
pub(crate) use non_lowercase_variable_in_function::*;
mod camelcase_imported_as_acronym;
mod camelcase_imported_as_constant;
mod camelcase_imported_as_lowercase;
mod constant_imported_as_non_constant;
mod dunder_function_name;
mod error_suffix_on_exception_name;
mod invalid_argument_name;
mod invalid_class_name;
mod invalid_first_argument_name;
mod invalid_function_name;
mod invalid_module_name;
mod lowercase_imported_as_non_lowercase;
mod mixed_case_variable_in_class_scope;
mod mixed_case_variable_in_global_scope;
mod non_lowercase_variable_in_function;
| 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/pep8_naming/rules/non_lowercase_variable_in_function.rs | crates/ruff_linter/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs | use ruff_python_ast::Expr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_stdlib::str;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::pep8_naming::helpers;
/// ## What it does
/// Checks for the use of non-lowercase variable names in functions.
///
/// ## Why is this bad?
/// [PEP 8] recommends that all function variables use lowercase names:
///
/// > Function names should be lowercase, with words separated by underscores as necessary to
/// > improve readability. Variable names follow the same convention as function names. mixedCase
/// > is allowed only in contexts where that's already the prevailing style (e.g. threading.py),
/// > to retain backwards compatibility.
///
/// ## Example
/// ```python
/// def my_function(a):
/// B = a + 3
/// return B
/// ```
///
/// Use instead:
/// ```python
/// def my_function(a):
/// b = a + 3
/// return b
/// ```
///
/// ## Options
/// - `lint.pep8-naming.ignore-names`
/// - `lint.pep8-naming.extend-ignore-names`
///
/// [PEP 8]: https://peps.python.org/pep-0008/#function-and-variable-names
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.89")]
pub(crate) struct NonLowercaseVariableInFunction {
name: String,
}
impl Violation for NonLowercaseVariableInFunction {
#[derive_message_formats]
fn message(&self) -> String {
let NonLowercaseVariableInFunction { name } = self;
format!("Variable `{name}` in function should be lowercase")
}
}
/// N806
pub(crate) fn non_lowercase_variable_in_function(checker: &Checker, expr: &Expr, name: &str) {
if str::is_lowercase(name) {
return;
}
// Ignore globals.
if checker
.semantic()
.lookup_symbol(name)
.is_some_and(|id| checker.semantic().binding(id).is_global())
{
return;
}
let parent = checker.semantic().current_statement();
if helpers::is_named_tuple_assignment(parent, checker.semantic())
|| helpers::is_typed_dict_assignment(parent, checker.semantic())
|| helpers::is_type_var_assignment(parent, checker.semantic())
|| helpers::is_type_alias_assignment(parent, checker.semantic())
|| helpers::is_django_model_import(name, parent, checker.semantic())
{
return;
}
// Ignore explicitly-allowed names.
if checker.settings().pep8_naming.ignore_names.matches(name) {
return;
}
checker.report_diagnostic(
NonLowercaseVariableInFunction {
name: name.to_string(),
},
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/pep8_naming/rules/invalid_function_name.rs | crates/ruff_linter/src/rules/pep8_naming/rules/invalid_function_name.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Decorator, Stmt, identifier::Identifier};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::{class::any_base_class, visibility};
use ruff_python_stdlib::str;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::pep8_naming::settings::IgnoreNames;
/// ## What it does
/// Checks for functions names that do not follow the `snake_case` naming
/// convention.
///
/// ## Why is this bad?
/// [PEP 8] recommends that function names follow `snake_case`:
///
/// > Function names should be lowercase, with words separated by underscores as necessary to
/// > improve readability. mixedCase is allowed only in contexts where that’s already the
/// > prevailing style (e.g. threading.py), to retain backwards compatibility.
///
/// Names can be excluded from this rule using the [`lint.pep8-naming.ignore-names`]
/// or [`lint.pep8-naming.extend-ignore-names`] configuration options. For example,
/// to ignore all functions starting with `test_` from this rule, set the
/// [`lint.pep8-naming.extend-ignore-names`] option to `["test_*"]`.
///
/// This rule exempts methods decorated with [`@typing.override`][override].
/// Explicitly decorating a 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 naming conventions on such methods.
///
/// ## Example
/// ```python
/// def myFunction():
/// pass
/// ```
///
/// Use instead:
/// ```python
/// def my_function():
/// pass
/// ```
///
/// ## Options
/// - `lint.pep8-naming.ignore-names`
/// - `lint.pep8-naming.extend-ignore-names`
///
/// [PEP 8]: https://peps.python.org/pep-0008/#function-and-variable-names
/// [override]: https://docs.python.org/3/library/typing.html#typing.override
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.77")]
pub(crate) struct InvalidFunctionName {
name: String,
}
impl Violation for InvalidFunctionName {
#[derive_message_formats]
fn message(&self) -> String {
let InvalidFunctionName { name } = self;
format!("Function name `{name}` should be lowercase")
}
}
/// N802
pub(crate) fn invalid_function_name(
checker: &Checker,
stmt: &Stmt,
name: &str,
decorator_list: &[Decorator],
ignore_names: &IgnoreNames,
semantic: &SemanticModel,
) {
// Ignore any function names that are already lowercase.
if str::is_lowercase(name) {
return;
}
// Ignore any functions that are explicitly `@override` or `@overload`.
// These are defined elsewhere, so if they're first-party,
// we'll flag them at the definition site.
if visibility::is_override(decorator_list, semantic)
|| visibility::is_overload(decorator_list, semantic)
{
return;
}
// Ignore any explicitly-allowed names.
if ignore_names.matches(name) {
return;
}
let parent_class = semantic
.current_statement_parent()
.and_then(|parent| parent.as_class_def_stmt());
// Ignore the visit_* methods of the ast.NodeVisitor and ast.NodeTransformer classes.
if name.starts_with("visit_")
&& parent_class.is_some_and(|class| {
any_base_class(class, semantic, &mut |superclass| {
let qualified = semantic.resolve_qualified_name(superclass);
qualified.is_some_and(|name| {
matches!(name.segments(), ["ast", "NodeVisitor" | "NodeTransformer"])
})
})
})
{
return;
}
// Ignore the do_* methods of the http.server.BaseHTTPRequestHandler class and its subclasses
if name.starts_with("do_")
&& parent_class.is_some_and(|class| {
any_base_class(class, semantic, &mut |superclass| {
let qualified = semantic.resolve_qualified_name(superclass);
qualified.is_some_and(|name| {
matches!(
name.segments(),
[
"http",
"server",
"BaseHTTPRequestHandler"
| "CGIHTTPRequestHandler"
| "SimpleHTTPRequestHandler"
]
)
})
})
})
{
return;
}
let mut diagnostic = checker.report_diagnostic(
InvalidFunctionName {
name: name.to_string(),
},
stmt.identifier(),
);
if parent_class.is_some() {
diagnostic.help(
"Consider adding `@typing.override` if this method \
overrides a method from a superclass",
);
}
}
| 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/pep8_naming/rules/camelcase_imported_as_constant.rs | crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs | use ruff_python_ast::{Alias, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_stdlib::str::{self};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::pep8_naming::helpers;
use crate::rules::pep8_naming::settings::IgnoreNames;
/// ## What it does
/// Checks for `CamelCase` imports that are aliased to constant-style names.
///
/// ## Why is this bad?
/// [PEP 8] recommends naming conventions for classes, functions,
/// constants, and more. The use of inconsistent naming styles between
/// import and alias names may lead readers to expect an import to be of
/// another type (e.g., confuse a Python class with a constant).
///
/// Import aliases should thus follow the same naming style as the member
/// being imported.
///
/// ## Example
/// ```python
/// from example import MyClassName as MY_CLASS_NAME
/// ```
///
/// Use instead:
/// ```python
/// from example import MyClassName
/// ```
///
/// ## Note
/// Identifiers consisting of a single uppercase character are ambiguous under
/// the rules of [PEP 8], which specifies `CamelCase` for classes and
/// `ALL_CAPS_SNAKE_CASE` for constants. Without a second character, it is not
/// possible to reliably guess whether the identifier is intended to be part
/// of a `CamelCase` string for a class or an `ALL_CAPS_SNAKE_CASE` string for
/// a constant, since both conventions will produce the same output when given
/// a single input character. Therefore, this lint rule does not apply to cases
/// where the alias for the imported identifier consists of a single uppercase
/// character.
///
/// A common example of a single uppercase character being used for a class
/// name can be found in Django's `django.db.models.Q` class.
///
/// ## Options
/// - `lint.pep8-naming.ignore-names`
/// - `lint.pep8-naming.extend-ignore-names`
///
/// [PEP 8]: https://peps.python.org/pep-0008/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.82")]
pub(crate) struct CamelcaseImportedAsConstant {
name: String,
asname: String,
}
impl Violation for CamelcaseImportedAsConstant {
#[derive_message_formats]
fn message(&self) -> String {
let CamelcaseImportedAsConstant { name, asname } = self;
format!("Camelcase `{name}` imported as constant `{asname}`")
}
}
/// N814
pub(crate) fn camelcase_imported_as_constant(
checker: &Checker,
name: &str,
asname: &str,
alias: &Alias,
stmt: &Stmt,
ignore_names: &IgnoreNames,
) {
// Single-character names are ambiguous. It could be a class or a constant.
if asname.chars().nth(1).is_none() {
return;
}
if helpers::is_camelcase(name)
&& !str::is_cased_lowercase(asname)
&& str::is_cased_uppercase(asname)
&& !helpers::is_acronym(name, asname)
{
// Ignore any explicitly-allowed names.
if ignore_names.matches(name) || ignore_names.matches(asname) {
return;
}
let mut diagnostic = checker.report_diagnostic(
CamelcaseImportedAsConstant {
name: name.to_string(),
asname: asname.to_string(),
},
alias.range(),
);
diagnostic.set_parent(stmt.start());
}
}
| 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/pep8_naming/rules/invalid_first_argument_name.rs | crates/ruff_linter/src/rules/pep8_naming/rules/invalid_first_argument_name.rs | use anyhow::Result;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::ParameterWithDefault;
use ruff_python_codegen::Stylist;
use ruff_python_semantic::analyze::class::{IsMetaclass, is_metaclass};
use ruff_python_semantic::analyze::function_type;
use ruff_python_semantic::{Scope, ScopeKind, SemanticModel};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::{Checker, DiagnosticGuard};
use crate::registry::Rule;
use crate::renamer::{Renamer, ShadowedKind};
use crate::{Fix, Violation};
/// ## What it does
/// Checks for instance methods that use a name other than `self` for their
/// first argument.
///
/// ## Why is this bad?
/// [PEP 8] recommends the use of `self` as first argument for all instance
/// methods:
///
/// > Always use self for the first argument to instance methods.
/// >
/// > If a function argument’s name clashes with a reserved keyword, it is generally better to
/// > append a single trailing underscore rather than use an abbreviation or spelling corruption.
/// > Thus `class_` is better than `clss`. (Perhaps better is to avoid such clashes by using a synonym.)
///
/// Names can be excluded from this rule using the [`lint.pep8-naming.ignore-names`]
/// or [`lint.pep8-naming.extend-ignore-names`] configuration options. For example,
/// to allow the use of `this` as the first argument to instance methods, set
/// the [`lint.pep8-naming.extend-ignore-names`] option to `["this"]`.
///
/// ## Example
///
/// ```python
/// class Example:
/// def function(cls, data): ...
/// ```
///
/// Use instead:
///
/// ```python
/// class Example:
/// def function(self, data): ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as renaming a method parameter
/// can change the behavior of the program.
///
/// ## Options
/// - `lint.pep8-naming.classmethod-decorators`
/// - `lint.pep8-naming.staticmethod-decorators`
/// - `lint.pep8-naming.ignore-names`
/// - `lint.pep8-naming.extend-ignore-names`
///
/// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.77")]
pub(crate) struct InvalidFirstArgumentNameForMethod {
argument_name: String,
}
impl Violation for InvalidFirstArgumentNameForMethod {
const FIX_AVAILABILITY: crate::FixAvailability = crate::FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"First argument of a method should be named `self`".to_string()
}
fn fix_title(&self) -> Option<String> {
let Self { argument_name } = self;
Some(format!("Rename `{argument_name}` to `self`"))
}
}
/// ## What it does
/// Checks for class methods that use a name other than `cls` for their
/// first argument.
///
/// The method `__new__` is exempted from this
/// check and the corresponding violation is caught by
/// [`bad-staticmethod-argument`][PLW0211].
///
/// ## Why is this bad?
/// [PEP 8] recommends the use of `cls` as the first argument for all class
/// methods:
///
/// > Always use `cls` for the first argument to class methods.
/// >
/// > If a function argument’s name clashes with a reserved keyword, it is generally better to
/// > append a single trailing underscore rather than use an abbreviation or spelling corruption.
/// > Thus `class_` is better than `clss`. (Perhaps better is to avoid such clashes by using a synonym.)
///
/// Names can be excluded from this rule using the [`lint.pep8-naming.ignore-names`]
/// or [`lint.pep8-naming.extend-ignore-names`] configuration options. For example,
/// to allow the use of `klass` as the first argument to class methods, set
/// the [`lint.pep8-naming.extend-ignore-names`] option to `["klass"]`.
///
/// ## Example
///
/// ```python
/// class Example:
/// @classmethod
/// def function(self, data): ...
/// ```
///
/// Use instead:
///
/// ```python
/// class Example:
/// @classmethod
/// def function(cls, data): ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as renaming a method parameter
/// can change the behavior of the program.
///
/// ## Options
/// - `lint.pep8-naming.classmethod-decorators`
/// - `lint.pep8-naming.staticmethod-decorators`
/// - `lint.pep8-naming.ignore-names`
/// - `lint.pep8-naming.extend-ignore-names`
///
/// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments
/// [PLW0211]: https://docs.astral.sh/ruff/rules/bad-staticmethod-argument/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.77")]
pub(crate) struct InvalidFirstArgumentNameForClassMethod {
argument_name: String,
// Whether the method is `__new__`
is_new: bool,
}
impl Violation for InvalidFirstArgumentNameForClassMethod {
const FIX_AVAILABILITY: crate::FixAvailability = crate::FixAvailability::Sometimes;
#[derive_message_formats]
// The first string below is what shows up in the documentation
// in the rule table, and it is the more common case.
fn message(&self) -> String {
if !self.is_new {
"First argument of a class method should be named `cls`".to_string()
} else {
"First argument of `__new__` method should be named `cls`".to_string()
}
}
fn fix_title(&self) -> Option<String> {
let Self { argument_name, .. } = self;
Some(format!("Rename `{argument_name}` to `cls`"))
}
}
#[derive(Debug, Copy, Clone)]
enum FunctionType {
/// The function is an instance method.
Method,
/// The function is a class method.
ClassMethod,
}
impl FunctionType {
fn diagnostic_kind<'a, 'b>(
self,
checker: &'a Checker<'b>,
argument_name: String,
range: TextRange,
) -> DiagnosticGuard<'a, 'b> {
match self {
Self::Method => checker
.report_diagnostic(InvalidFirstArgumentNameForMethod { argument_name }, range),
Self::ClassMethod => checker.report_diagnostic(
InvalidFirstArgumentNameForClassMethod {
argument_name,
is_new: false,
},
range,
),
}
}
const fn valid_first_argument_name(self) -> &'static str {
match self {
Self::Method => "self",
Self::ClassMethod => "cls",
}
}
const fn rule(self) -> Rule {
match self {
Self::Method => Rule::InvalidFirstArgumentNameForMethod,
Self::ClassMethod => Rule::InvalidFirstArgumentNameForClassMethod,
}
}
}
/// N804, N805
pub(crate) fn invalid_first_argument_name(checker: &Checker, scope: &Scope) {
let ScopeKind::Function(ast::StmtFunctionDef {
name,
parameters,
decorator_list,
..
}) = &scope.kind
else {
panic!("Expected ScopeKind::Function")
};
let semantic = checker.semantic();
let Some(parent_scope) = semantic.first_non_type_parent_scope(scope) else {
return;
};
let ScopeKind::Class(parent) = parent_scope.kind else {
return;
};
let function_type = match function_type::classify(
name,
decorator_list,
parent_scope,
semantic,
&checker.settings().pep8_naming.classmethod_decorators,
&checker.settings().pep8_naming.staticmethod_decorators,
) {
function_type::FunctionType::Function | function_type::FunctionType::StaticMethod => {
return;
}
function_type::FunctionType::Method => match is_metaclass(parent, semantic) {
IsMetaclass::Yes => FunctionType::ClassMethod,
IsMetaclass::No => FunctionType::Method,
IsMetaclass::Maybe => return,
},
function_type::FunctionType::ClassMethod => FunctionType::ClassMethod,
// This violation is caught by `PLW0211` instead
function_type::FunctionType::NewMethod => {
return;
}
};
if !checker.is_rule_enabled(function_type.rule()) {
return;
}
let Some(ParameterWithDefault {
parameter: self_or_cls,
..
}) = parameters
.posonlyargs
.first()
.or_else(|| parameters.args.first())
else {
return;
};
if &self_or_cls.name == function_type.valid_first_argument_name()
|| checker
.settings()
.pep8_naming
.ignore_names
.matches(&self_or_cls.name)
{
return;
}
let mut diagnostic =
function_type.diagnostic_kind(checker, self_or_cls.name.to_string(), self_or_cls.range());
diagnostic.try_set_optional_fix(|| {
rename_parameter(
checker,
scope,
self_or_cls,
parameters,
checker.semantic(),
function_type,
checker.stylist(),
)
});
}
/// Rename the first parameter to `self` or `cls`, if no other parameter has the target name.
fn rename_parameter(
checker: &Checker,
scope: &Scope<'_>,
self_or_cls: &ast::Parameter,
parameters: &ast::Parameters,
semantic: &SemanticModel<'_>,
function_type: FunctionType,
stylist: &Stylist,
) -> Result<Option<Fix>> {
// Don't fix if another parameter has the valid name.
if parameters
.iter()
.skip(1)
.any(|parameter| parameter.name() == function_type.valid_first_argument_name())
{
return Ok(None);
}
let binding = scope
.get(&self_or_cls.name)
.map(|binding_id| semantic.binding(binding_id))
.unwrap();
// Don't provide autofix if `self` or `cls` is already defined in the scope.
if ShadowedKind::new(binding, function_type.valid_first_argument_name(), checker).shadows_any()
{
return Ok(None);
}
let (edit, rest) = Renamer::rename(
&self_or_cls.name,
function_type.valid_first_argument_name(),
scope,
semantic,
stylist,
)?;
Ok(Some(Fix::unsafe_edits(edit, rest)))
}
| 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/pep8_naming/rules/invalid_module_name.rs | crates/ruff_linter/src/rules/pep8_naming/rules/invalid_module_name.rs | use std::ffi::OsStr;
use std::path::Path;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::PySourceType;
use ruff_python_stdlib::identifiers::{is_migration_name, is_module_name};
use ruff_python_stdlib::path::is_module_file;
use ruff_text_size::TextRange;
use crate::Violation;
use crate::checkers::ast::LintContext;
use crate::package::PackageRoot;
use crate::rules::pep8_naming::settings::IgnoreNames;
/// ## What it does
/// Checks for module names that do not follow the `snake_case` naming
/// convention or are otherwise invalid.
///
/// ## Why is this bad?
/// [PEP 8] recommends the use of the `snake_case` naming convention for
/// module names:
///
/// > Modules should have short, all-lowercase names. Underscores can be used in the
/// > module name if it improves readability. Python packages should also have short,
/// > all-lowercase names, although the use of underscores is discouraged.
/// >
/// > When an extension module written in C or C++ has an accompanying Python module that
/// > provides a higher level (e.g. more object-oriented) interface, the C/C++ module has
/// > a leading underscore (e.g. `_socket`).
///
/// Further, in order for Python modules to be importable, they must be valid
/// identifiers. As such, they cannot start with a digit, or collide with hard
/// keywords, like `import` or `class`.
///
/// ## Example
/// - Instead of `example-module-name` or `example module name`, use `example_module_name`.
/// - Instead of `ExampleModule`, use `example_module`.
///
/// ## Options
///
/// - `lint.pep8-naming.ignore-names`
///
/// [PEP 8]: https://peps.python.org/pep-0008/#package-and-module-names
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.248")]
pub(crate) struct InvalidModuleName {
name: String,
}
impl Violation for InvalidModuleName {
#[derive_message_formats]
fn message(&self) -> String {
let InvalidModuleName { name } = self;
format!("Invalid module name: '{name}'")
}
}
/// N999
pub(crate) fn invalid_module_name(
path: &Path,
package: Option<PackageRoot<'_>>,
ignore_names: &IgnoreNames,
context: &LintContext,
) {
if !PySourceType::try_from_path(path).is_some_and(PySourceType::is_py_file_or_stub) {
return;
}
if let Some(package) = package {
let module_name = if is_module_file(path) {
package.path().file_name().unwrap().to_string_lossy()
} else {
path.file_stem().unwrap().to_string_lossy()
};
// As a special case, we allow files in `versions` and `migrations` directories to start
// with a digit (e.g., `0001_initial.py`), to support common conventions used by Django
// and other frameworks.
let is_valid_module_name = if is_migration_file(path) {
is_migration_name(&module_name)
} else {
is_module_name(&module_name)
};
if !is_valid_module_name {
// Ignore any explicitly-allowed names.
if ignore_names.matches(&module_name) {
return;
}
context.report_diagnostic(
InvalidModuleName {
name: module_name.to_string(),
},
TextRange::default(),
);
}
}
}
/// Return `true` if a [`Path`] refers to a migration file.
fn is_migration_file(path: &Path) -> bool {
path.parent()
.and_then(Path::file_name)
.and_then(OsStr::to_str)
.is_some_and(|parent| matches!(parent, "versions" | "migrations"))
}
| 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/pep8_naming/rules/camelcase_imported_as_lowercase.rs | crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs | use ruff_python_ast::{Alias, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::pep8_naming::helpers;
use crate::rules::pep8_naming::settings::IgnoreNames;
/// ## What it does
/// Checks for `CamelCase` imports that are aliased to lowercase names.
///
/// ## Why is this bad?
/// [PEP 8] recommends naming conventions for classes, functions,
/// constants, and more. The use of inconsistent naming styles between
/// import and alias names may lead readers to expect an import to be of
/// another type (e.g., confuse a Python class with a constant).
///
/// Import aliases should thus follow the same naming style as the member
/// being imported.
///
/// ## Example
/// ```python
/// from example import MyClassName as myclassname
/// ```
///
/// Use instead:
/// ```python
/// from example import MyClassName
/// ```
///
/// ## Options
/// - `lint.pep8-naming.ignore-names`
/// - `lint.pep8-naming.extend-ignore-names`
///
/// [PEP 8]: https://peps.python.org/pep-0008/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.82")]
pub(crate) struct CamelcaseImportedAsLowercase {
name: String,
asname: String,
}
impl Violation for CamelcaseImportedAsLowercase {
#[derive_message_formats]
fn message(&self) -> String {
let CamelcaseImportedAsLowercase { name, asname } = self;
format!("Camelcase `{name}` imported as lowercase `{asname}`")
}
}
/// N813
pub(crate) fn camelcase_imported_as_lowercase(
checker: &Checker,
name: &str,
asname: &str,
alias: &Alias,
stmt: &Stmt,
ignore_names: &IgnoreNames,
) {
if helpers::is_camelcase(name) && ruff_python_stdlib::str::is_cased_lowercase(asname) {
// Ignore any explicitly-allowed names.
if ignore_names.matches(name) || ignore_names.matches(asname) {
return;
}
let mut diagnostic = checker.report_diagnostic(
CamelcaseImportedAsLowercase {
name: name.to_string(),
asname: asname.to_string(),
},
alias.range(),
);
diagnostic.set_parent(stmt.start());
}
}
| 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/pyupgrade/settings.rs | crates/ruff_linter/src/rules/pyupgrade/settings.rs | //! Settings for the `pyupgrade` plugin.
use crate::display_settings;
use ruff_macros::CacheKey;
use std::fmt;
#[derive(Debug, Clone, Default, CacheKey)]
pub struct Settings {
pub keep_runtime_typing: bool,
}
impl fmt::Display for Settings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.pyupgrade",
fields = [
self.keep_runtime_typing
]
}
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/pyupgrade/helpers.rs | crates/ruff_linter/src/rules/pyupgrade/helpers.rs | use regex::{Captures, Regex};
use std::borrow::Cow;
use std::sync::LazyLock;
static CURLY_BRACES: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(\\N\{[^}]+})|([{}])").unwrap());
pub(super) fn curly_escape(text: &str) -> Cow<'_, str> {
// Match all curly braces. This will include named unicode escapes (like
// \N{SNOWMAN}), which we _don't_ want to escape, so take care to preserve them.
CURLY_BRACES.replace_all(text, |caps: &Captures| {
if let Some(match_) = caps.get(1) {
match_.as_str().to_string()
} else {
if &caps[2] == "{" {
"{{".to_string()
} else {
"}}".to_string()
}
}
})
}
static DOUBLE_CURLY_BRACES: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"((\{\{)|(\}\}))").unwrap());
pub(super) fn curly_unescape(text: &str) -> Cow<'_, str> {
// Match all double curly braces and replace with a single
DOUBLE_CURLY_BRACES.replace_all(text, |caps: &Captures| {
if &caps[1] == "{{" {
"{".to_string()
} else {
"}".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/pyupgrade/fixes.rs | crates/ruff_linter/src/rules/pyupgrade/fixes.rs | use ruff_python_ast::StmtImportFrom;
use ruff_python_ast::token::{TokenKind, Tokens};
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
/// Remove any imports matching `members` from an import-from statement.
pub(crate) fn remove_import_members(
locator: &Locator<'_>,
import_from_stmt: &StmtImportFrom,
tokens: &Tokens,
members_to_remove: &[&str],
) -> String {
let commas: Vec<TextRange> = tokens
.in_range(import_from_stmt.range())
.iter()
.skip_while(|token| token.kind() != TokenKind::Import)
.filter_map(|token| {
if token.kind() == TokenKind::Comma {
Some(token.range())
} else {
None
}
})
.collect();
// Reconstruct the source code by skipping any names that are in `members`.
let mut output = String::with_capacity(import_from_stmt.range().len().to_usize());
let mut last_pos = import_from_stmt.start();
let mut is_first = true;
for (index, member) in import_from_stmt.names.iter().enumerate() {
if !members_to_remove.contains(&member.name.as_str()) {
is_first = false;
continue;
}
let range = if is_first {
TextRange::new(
import_from_stmt.names[index].start(),
import_from_stmt.names[index + 1].start(),
)
} else {
TextRange::new(
commas[index - 1].start(),
import_from_stmt.names[index].end(),
)
};
// Add all contents from `last_pos` to `fix.location`.
// It's possible that `last_pos` is after `fix.location`, if we're removing the
// first _two_ members.
if range.start() > last_pos {
let slice = locator.slice(TextRange::new(last_pos, range.start()));
output.push_str(slice);
}
last_pos = range.end();
}
// Add the remaining content.
let slice = locator.slice(TextRange::new(last_pos, import_from_stmt.end()));
output.push_str(slice);
output
}
#[cfg(test)]
mod tests {
use ruff_python_parser::parse_module;
use crate::Locator;
use super::remove_import_members;
fn test_helper(source: &str, members_to_remove: &[&str]) -> String {
let parsed = parse_module(source).unwrap();
let import_from_stmt = parsed
.suite()
.first()
.expect("source should have one statement")
.as_import_from_stmt()
.expect("first statement should be an import from statement");
remove_import_members(
&Locator::new(source),
import_from_stmt,
parsed.tokens(),
members_to_remove,
)
}
#[test]
fn once() {
let source = r"from foo import bar, baz, bop, qux as q";
let expected = r"from foo import bar, baz, qux as q";
let actual = test_helper(source, &["bop"]);
assert_eq!(expected, actual);
}
#[test]
fn twice() {
let source = r"from foo import bar, baz, bop, qux as q";
let expected = r"from foo import bar, qux as q";
let actual = test_helper(source, &["baz", "bop"]);
assert_eq!(expected, actual);
}
#[test]
fn aliased() {
let source = r"from foo import bar, baz, bop as boop, qux as q";
let expected = r"from foo import bar, baz, qux as q";
let actual = test_helper(source, &["bop"]);
assert_eq!(expected, actual);
}
#[test]
fn parenthesized() {
let source = r"from foo import (bar, baz, bop, qux as q)";
let expected = r"from foo import (bar, baz, qux as q)";
let actual = test_helper(source, &["bop"]);
assert_eq!(expected, actual);
}
#[test]
fn last_import() {
let source = r"from foo import bar, baz, bop, qux as q";
let expected = r"from foo import bar, baz, bop";
let actual = test_helper(source, &["qux"]);
assert_eq!(expected, actual);
}
#[test]
fn first_import() {
let source = r"from foo import bar, baz, bop, qux as q";
let expected = r"from foo import baz, bop, qux as q";
let actual = test_helper(source, &["bar"]);
assert_eq!(expected, actual);
}
#[test]
fn first_two_imports() {
let source = r"from foo import bar, baz, bop, qux as q";
let expected = r"from foo import bop, qux as q";
let actual = test_helper(source, &["bar", "baz"]);
assert_eq!(expected, actual);
}
#[test]
fn first_two_imports_multiline() {
let source = r"from foo import (
bar,
baz,
bop,
qux as q
)";
let expected = r"from foo import (
bop,
qux as q
)";
let actual = test_helper(source, &["bar", "baz"]);
assert_eq!(expected, actual);
}
#[test]
fn multiline_once() {
let source = r"from foo import (
bar,
baz,
bop,
qux as q,
)";
let expected = r"from foo import (
bar,
baz,
qux as q,
)";
let actual = test_helper(source, &["bop"]);
assert_eq!(expected, actual);
}
#[test]
fn multiline_twice() {
let source = r"from foo import (
bar,
baz,
bop,
qux as q,
)";
let expected = r"from foo import (
bar,
qux as q,
)";
let actual = test_helper(source, &["baz", "bop"]);
assert_eq!(expected, actual);
}
#[test]
fn multiline_comment() {
let source = r"from foo import (
bar,
baz,
# This comment should be removed.
bop,
# This comment should be retained.
qux as q,
)";
let expected = r"from foo import (
bar,
baz,
# This comment should be retained.
qux as q,
)";
let actual = test_helper(source, &["bop"]);
assert_eq!(expected, actual);
}
#[test]
fn multi_comment_first_import() {
let source = r"from foo import (
# This comment should be retained.
bar,
# This comment should be removed.
baz,
bop,
qux as q,
)";
let expected = r"from foo import (
# This comment should be retained.
baz,
bop,
qux as q,
)";
let actual = test_helper(source, &["bar"]);
assert_eq!(expected, actual);
}
}
| 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/pyupgrade/types.rs | crates/ruff_linter/src/rules/pyupgrade/types.rs | use ruff_python_ast::{Expr, ExprNumberLiteral, Number};
use serde::{Deserialize, Serialize};
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Primitive {
Bool,
Str,
Bytes,
Int,
Float,
Complex,
}
impl Primitive {
pub(crate) const fn from_expr(expr: &Expr) -> Option<Self> {
match expr {
Expr::BooleanLiteral(_) => Some(Self::Bool),
Expr::StringLiteral(_) => Some(Self::Str),
Expr::BytesLiteral(_) => Some(Self::Bytes),
Expr::NumberLiteral(ExprNumberLiteral { value, .. }) => match value {
Number::Int(_) => Some(Self::Int),
Number::Float(_) => Some(Self::Float),
Number::Complex { .. } => Some(Self::Complex),
},
_ => None,
}
}
pub(crate) fn builtin(self) -> String {
match self {
Self::Bool => "bool".to_string(),
Self::Str => "str".to_string(),
Self::Bytes => "bytes".to_string(),
Self::Int => "int".to_string(),
Self::Float => "float".to_string(),
Self::Complex => "complex".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/pyupgrade/mod.rs | crates/ruff_linter/src/rules/pyupgrade/mod.rs | //! Rules from [pyupgrade](https://pypi.org/project/pyupgrade/).
pub(crate) mod fixes;
mod helpers;
pub(crate) mod rules;
pub mod settings;
pub(crate) mod types;
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use std::path::Path;
use anyhow::Result;
use ruff_python_ast::PythonVersion;
use ruff_python_semantic::{MemberNameImport, NameImport};
use test_case::test_case;
use crate::registry::Rule;
use crate::rules::{isort, pyupgrade};
use crate::settings::types::PreviewMode;
use crate::test::{test_path, test_snippet};
use crate::{assert_diagnostics, assert_diagnostics_diff, settings};
#[test_case(Rule::ConvertNamedTupleFunctionalToClass, Path::new("UP014.py"))]
#[test_case(Rule::ConvertTypedDictFunctionalToClass, Path::new("UP013.py"))]
#[test_case(Rule::DeprecatedCElementTree, Path::new("UP023.py"))]
#[test_case(Rule::DeprecatedImport, Path::new("UP035.py"))]
#[test_case(Rule::DeprecatedMockImport, Path::new("UP026.py"))]
#[test_case(Rule::DeprecatedUnittestAlias, Path::new("UP005.py"))]
#[test_case(Rule::ExtraneousParentheses, Path::new("UP034.py"))]
#[test_case(Rule::FString, Path::new("UP032_0.py"))]
#[test_case(Rule::FString, Path::new("UP032_1.py"))]
#[test_case(Rule::FString, Path::new("UP032_2.py"))]
#[test_case(Rule::FString, Path::new("UP032_3.py"))]
#[test_case(Rule::FormatLiterals, Path::new("UP030_0.py"))]
#[test_case(Rule::FormatLiterals, Path::new("UP030_1.py"))]
#[test_case(Rule::LRUCacheWithMaxsizeNone, Path::new("UP033_0.py"))]
#[test_case(Rule::LRUCacheWithMaxsizeNone, Path::new("UP033_1.py"))]
#[test_case(Rule::LRUCacheWithoutParameters, Path::new("UP011.py"))]
#[test_case(Rule::NativeLiterals, Path::new("UP018.py"))]
#[test_case(Rule::NativeLiterals, Path::new("UP018_CR.py"))]
#[test_case(Rule::NativeLiterals, Path::new("UP018_LF.py"))]
#[test_case(Rule::NonPEP585Annotation, Path::new("UP006_0.py"))]
#[test_case(Rule::NonPEP585Annotation, Path::new("UP006_1.py"))]
#[test_case(Rule::NonPEP585Annotation, Path::new("UP006_2.py"))]
#[test_case(Rule::NonPEP585Annotation, Path::new("UP006_3.py"))]
#[test_case(Rule::NonPEP604AnnotationUnion, Path::new("UP007.py"))]
#[test_case(Rule::NonPEP604AnnotationOptional, Path::new("UP045.py"))]
#[test_case(Rule::NonPEP604Isinstance, Path::new("UP038.py"))]
#[test_case(Rule::OSErrorAlias, Path::new("UP024_0.py"))]
#[test_case(Rule::OSErrorAlias, Path::new("UP024_1.py"))]
#[test_case(Rule::OSErrorAlias, Path::new("UP024_2.py"))]
#[test_case(Rule::OSErrorAlias, Path::new("UP024_3.py"))]
#[test_case(Rule::OSErrorAlias, Path::new("UP024_4.py"))]
#[test_case(Rule::OpenAlias, Path::new("UP020.py"))]
#[test_case(Rule::OutdatedVersionBlock, Path::new("UP036_0.py"))]
#[test_case(Rule::OutdatedVersionBlock, Path::new("UP036_1.py"))]
#[test_case(Rule::OutdatedVersionBlock, Path::new("UP036_2.py"))]
#[test_case(Rule::OutdatedVersionBlock, Path::new("UP036_3.py"))]
#[test_case(Rule::OutdatedVersionBlock, Path::new("UP036_4.py"))]
#[test_case(Rule::OutdatedVersionBlock, Path::new("UP036_5.py"))]
#[test_case(Rule::PrintfStringFormatting, Path::new("UP031_0.py"))]
#[test_case(Rule::PrintfStringFormatting, Path::new("UP031_1.py"))]
#[test_case(Rule::QuotedAnnotation, Path::new("UP037_0.py"))]
#[test_case(Rule::QuotedAnnotation, Path::new("UP037_1.py"))]
#[test_case(Rule::QuotedAnnotation, Path::new("UP037_2.pyi"))]
#[test_case(Rule::QuotedAnnotation, Path::new("UP037_3.py"))]
#[test_case(Rule::RedundantOpenModes, Path::new("UP015.py"))]
#[test_case(Rule::RedundantOpenModes, Path::new("UP015_1.py"))]
#[test_case(Rule::ReplaceStdoutStderr, Path::new("UP022.py"))]
#[test_case(Rule::ReplaceUniversalNewlines, Path::new("UP021.py"))]
#[test_case(Rule::SuperCallWithParameters, Path::new("UP008.py"))]
#[test_case(Rule::TimeoutErrorAlias, Path::new("UP041.py"))]
#[test_case(Rule::ReplaceStrEnum, Path::new("UP042.py"))]
#[test_case(Rule::TypeOfPrimitive, Path::new("UP003.py"))]
#[test_case(Rule::TypingTextStrAlias, Path::new("UP019.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_0.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_1.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_2.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_3.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_4.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_5.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_6.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_7.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_8.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_9.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_10.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_other_other.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_other_utf8.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_utf8_other.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_utf8_utf8.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_utf8_utf8_other.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_utf8_code_other.py"))]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_code_utf8_utf8.py"))]
#[test_case(
Rule::UTF8EncodingDeclaration,
Path::new("UP009_hashbang_utf8_other.py")
)]
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_many_empty_lines.py"))]
#[test_case(Rule::UnicodeKindPrefix, Path::new("UP025.py"))]
#[test_case(Rule::UnnecessaryBuiltinImport, Path::new("UP029_0.py"))]
#[test_case(Rule::UnnecessaryBuiltinImport, Path::new("UP029_2.py"))]
#[test_case(Rule::UnnecessaryClassParentheses, Path::new("UP039.py"))]
#[test_case(Rule::UnnecessaryDefaultTypeArgs, Path::new("UP043.py"))]
#[test_case(Rule::UnnecessaryEncodeUTF8, Path::new("UP012.py"))]
#[test_case(Rule::UnnecessaryFutureImport, Path::new("UP010_0.py"))]
#[test_case(Rule::UnnecessaryFutureImport, Path::new("UP010_1.py"))]
#[test_case(Rule::UselessMetaclassType, Path::new("UP001.py"))]
#[test_case(Rule::UselessObjectInheritance, Path::new("UP004.py"))]
#[test_case(Rule::YieldInForLoop, Path::new("UP028_0.py"))]
#[test_case(Rule::YieldInForLoop, Path::new("UP028_1.py"))]
#[test_case(Rule::NonPEP695TypeAlias, Path::new("UP040.py"))]
#[test_case(Rule::NonPEP695TypeAlias, Path::new("UP040.pyi"))]
#[test_case(Rule::NonPEP695GenericClass, Path::new("UP046_0.py"))]
#[test_case(Rule::NonPEP695GenericClass, Path::new("UP046_1.py"))]
#[test_case(Rule::NonPEP695GenericFunction, Path::new("UP047_0.py"))]
#[test_case(Rule::PrivateTypeParameter, Path::new("UP049_0.py"))]
#[test_case(Rule::PrivateTypeParameter, Path::new("UP049_1.py"))]
#[test_case(Rule::UselessClassMetaclassType, Path::new("UP050.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = path.to_string_lossy().to_string();
let diagnostics = test_path(
Path::new("pyupgrade").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::NonPEP695GenericClass, Path::new("UP046_2.py"))]
#[test_case(Rule::NonPEP695GenericFunction, Path::new("UP047_1.py"))]
fn rules_not_applied_default_typevar_backported(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = path.to_string_lossy().to_string();
let diagnostics = test_path(
Path::new("pyupgrade").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
unresolved_target_version: PythonVersion::PY312.into(),
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::SuperCallWithParameters, Path::new("UP008.py"))]
#[test_case(Rule::TypingTextStrAlias, Path::new("UP019.py"))]
fn rules_preview(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}__preview", path.to_string_lossy());
let diagnostics = test_path(
Path::new("pyupgrade").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::QuotedAnnotation, Path::new("UP037_3.py"))]
fn rules_py313(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("rules_py313__{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("pyupgrade").join(path).as_path(),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY313.into(),
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::NonPEP695TypeAlias, Path::new("UP040.py"))]
#[test_case(Rule::NonPEP695TypeAlias, Path::new("UP040.pyi"))]
#[test_case(Rule::NonPEP695GenericClass, Path::new("UP046_0.py"))]
#[test_case(Rule::NonPEP695GenericClass, Path::new("UP046_1.py"))]
#[test_case(Rule::NonPEP695GenericFunction, Path::new("UP047_0.py"))]
fn type_var_default_preview(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}__preview_diff", path.to_string_lossy());
assert_diagnostics_diff!(
snapshot,
Path::new("pyupgrade").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Disabled,
..settings::LinterSettings::for_rule(rule_code)
},
&settings::LinterSettings {
preview: PreviewMode::Enabled,
..settings::LinterSettings::for_rule(rule_code)
},
);
Ok(())
}
#[test_case(Rule::QuotedAnnotation, Path::new("UP037_0.py"))]
#[test_case(Rule::QuotedAnnotation, Path::new("UP037_1.py"))]
#[test_case(Rule::QuotedAnnotation, Path::new("UP037_2.pyi"))]
fn up037_add_future_annotation(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("add_future_annotation_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("pyupgrade").join(path).as_path(),
&settings::LinterSettings {
future_annotations: true,
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test]
fn async_timeout_error_alias_not_applied_py310() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/UP041.py"),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY310.into(),
..settings::LinterSettings::for_rule(Rule::TimeoutErrorAlias)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn non_pep695_type_alias_not_applied_py311() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/UP040.py"),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY311.into(),
..settings::LinterSettings::for_rule(Rule::NonPEP695TypeAlias)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn future_annotations_keep_runtime_typing_p37() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/future_annotations.py"),
&settings::LinterSettings {
pyupgrade: pyupgrade::settings::Settings {
keep_runtime_typing: true,
},
unresolved_target_version: PythonVersion::PY37.into(),
..settings::LinterSettings::for_rule(Rule::NonPEP585Annotation)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn future_annotations_keep_runtime_typing_p310() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/future_annotations.py"),
&settings::LinterSettings {
pyupgrade: pyupgrade::settings::Settings {
keep_runtime_typing: true,
},
unresolved_target_version: PythonVersion::PY310.into(),
..settings::LinterSettings::for_rule(Rule::NonPEP585Annotation)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn future_annotations_pep_585_p37() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/future_annotations.py"),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY37.into(),
..settings::LinterSettings::for_rule(Rule::NonPEP585Annotation)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn future_annotations_pep_585_py310() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/future_annotations.py"),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY310.into(),
..settings::LinterSettings::for_rule(Rule::NonPEP585Annotation)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn future_annotations_pep_604_p37() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/future_annotations.py"),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY37.into(),
..settings::LinterSettings::for_rules([
Rule::NonPEP604AnnotationUnion,
Rule::NonPEP604AnnotationOptional,
])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn future_annotations_pep_604_py310() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/future_annotations.py"),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY310.into(),
..settings::LinterSettings::for_rules([
Rule::NonPEP604AnnotationUnion,
Rule::NonPEP604AnnotationOptional,
])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn datetime_utc_alias_py311() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/UP017.py"),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY311.into(),
..settings::LinterSettings::for_rule(Rule::DatetimeTimezoneUTC)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn unpack_pep_646_py311() -> Result<()> {
let diagnostics = test_path(
Path::new("pyupgrade/UP044.py"),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY311.into(),
..settings::LinterSettings::for_rule(Rule::NonPEP646Unpack)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn i002_conflict() {
let diagnostics = test_snippet(
"from pipes import quote, Template",
&settings::LinterSettings {
isort: isort::settings::Settings {
required_imports: BTreeSet::from_iter([
// https://github.com/astral-sh/ruff/issues/18729
NameImport::ImportFrom(MemberNameImport::member(
"__future__".to_string(),
"generator_stop".to_string(),
)),
// https://github.com/astral-sh/ruff/issues/16802
NameImport::ImportFrom(MemberNameImport::member(
"collections".to_string(),
"Sequence".to_string(),
)),
// Only bail out if _all_ the names in UP035 are required. `pipes.Template`
// isn't flagged by UP035, so requiring it shouldn't prevent `pipes.quote`
// from getting a diagnostic.
NameImport::ImportFrom(MemberNameImport::member(
"pipes".to_string(),
"Template".to_string(),
)),
]),
..Default::default()
},
..settings::LinterSettings::for_rules([
Rule::MissingRequiredImport,
Rule::UnnecessaryFutureImport,
Rule::DeprecatedImport,
])
},
);
assert_diagnostics!(diagnostics, @r"
UP035 [*] Import from `shlex` instead: `quote`
--> <filename>:1:1
|
1 | from pipes import quote, Template
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
help: Import from `shlex`
- from pipes import quote, Template
1 + from pipes import Template
2 + from shlex import quote
I002 [*] Missing required import: `from __future__ import generator_stop`
--> <filename>:1:1
help: Insert required import: `from __future__ import generator_stop`
1 + from __future__ import generator_stop
2 | from pipes import quote, Template
I002 [*] Missing required import: `from collections import Sequence`
--> <filename>:1:1
help: Insert required import: `from collections import Sequence`
1 + from collections import Sequence
2 | from pipes import quote, Template
");
}
#[test_case(Path::new("UP029_1.py"))]
fn i002_up029_conflict(path: &Path) -> Result<()> {
let snapshot = format!("{}_skip_required_imports", path.to_string_lossy());
let diagnostics = test_path(
Path::new("pyupgrade").join(path).as_path(),
&settings::LinterSettings {
isort: isort::settings::Settings {
required_imports: BTreeSet::from_iter([
// https://github.com/astral-sh/ruff/issues/20601
NameImport::ImportFrom(MemberNameImport::member(
"builtins".to_string(),
"str".to_string(),
)),
]),
..Default::default()
},
..settings::LinterSettings::for_rules([
Rule::MissingRequiredImport,
Rule::UnnecessaryBuiltinImport,
])
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test]
fn unnecessary_default_type_args_stubs_py312_preview() -> Result<()> {
let snapshot = format!("{}__preview", "UP043.pyi");
let diagnostics = test_path(
Path::new("pyupgrade/UP043.pyi"),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
unresolved_target_version: PythonVersion::PY312.into(),
..settings::LinterSettings::for_rule(Rule::UnnecessaryDefaultTypeArgs)
},
)?;
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/pyupgrade/rules/extraneous_parentheses.rs | crates/ruff_linter/src/rules/pyupgrade/rules/extraneous_parentheses.rs | use std::slice::Iter;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::{Token, TokenKind, Tokens};
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::LintContext;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for extraneous parentheses.
///
/// ## Why is this bad?
/// Extraneous parentheses are redundant, and can be removed to improve
/// readability while retaining identical semantics.
///
/// ## Example
/// ```python
/// print(("Hello, world"))
/// ```
///
/// Use instead:
/// ```python
/// print("Hello, world")
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.228")]
pub(crate) struct ExtraneousParentheses;
impl AlwaysFixableViolation for ExtraneousParentheses {
#[derive_message_formats]
fn message(&self) -> String {
"Avoid extraneous parentheses".to_string()
}
fn fix_title(&self) -> String {
"Remove extraneous parentheses".to_string()
}
}
// See: https://github.com/asottile/pyupgrade/blob/97ed6fb3cf2e650d4f762ba231c3f04c41797710/pyupgrade/_main.py#L148
fn match_extraneous_parentheses(tokens: &mut Iter<'_, Token>) -> Option<(TextRange, TextRange)> {
// Store the location of the extraneous opening parenthesis.
let start_range = loop {
let token = tokens.next()?;
match token.kind() {
TokenKind::Comment | TokenKind::NonLogicalNewline => {
continue;
}
TokenKind::Lpar => {
break token.range();
}
_ => {
return None;
}
}
};
// Verify that we're not in an empty tuple.
let mut empty_tuple = true;
// Verify that we're not in a tuple or coroutine.
let mut depth = 1u32;
// Store the location of the extraneous closing parenthesis.
let end_range = loop {
let token = tokens.next()?;
match token.kind() {
// If we find a comma or a yield at depth 1 or 2, it's a tuple or coroutine.
TokenKind::Comma | TokenKind::Yield if depth == 1 => return None,
TokenKind::Lpar | TokenKind::Lbrace | TokenKind::Lsqb => {
depth = depth.saturating_add(1);
}
TokenKind::Rpar | TokenKind::Rbrace | TokenKind::Rsqb => {
depth = depth.saturating_sub(1);
}
_ => {}
}
if depth == 0 {
break token.range();
}
if !matches!(
token.kind(),
TokenKind::Comment | TokenKind::NonLogicalNewline
) {
empty_tuple = false;
}
};
if empty_tuple {
return None;
}
// Find the next non-coding token.
let token = loop {
let token = tokens.next()?;
match token.kind() {
TokenKind::Comment | TokenKind::NonLogicalNewline => continue,
_ => {
break token;
}
}
};
if matches!(token.kind(), TokenKind::Rpar) {
Some((start_range, end_range))
} else {
None
}
}
/// UP034
pub(crate) fn extraneous_parentheses(context: &LintContext, tokens: &Tokens, locator: &Locator) {
let mut token_iter = tokens.iter();
while let Some(token) = token_iter.next() {
if !matches!(token.kind(), TokenKind::Lpar) {
continue;
}
let Some((start_range, end_range)) = match_extraneous_parentheses(&mut token_iter) else {
continue;
};
if let Some(mut diagnostic) = context.report_diagnostic_if_enabled(
ExtraneousParentheses,
TextRange::new(start_range.start(), end_range.end()),
) {
let contents = locator.slice(TextRange::new(start_range.start(), end_range.end()));
diagnostic.set_fix(Fix::safe_edit(Edit::replacement(
contents[1..contents.len() - 1].to_string(),
start_range.start(),
end_range.end(),
)));
}
}
}
| 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/pyupgrade/rules/quoted_annotation.rs | crates/ruff_linter/src/rules/pyupgrade/rules/quoted_annotation.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::Stmt;
use ruff_python_ast::token::TokenKind;
use ruff_python_semantic::SemanticModel;
use ruff_source_file::LineRanges;
use ruff_text_size::{TextLen, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for the presence of unnecessary quotes in type annotations.
///
/// ## Why is this bad?
/// In Python, type annotations can be quoted to avoid forward references.
///
/// However, if `from __future__ import annotations` is present, Python
/// will always evaluate type annotations in a deferred manner, making
/// the quotes unnecessary.
///
/// Similarly, if the annotation is located in a typing-only context and
/// won't be evaluated by Python at runtime, the quotes will also be
/// considered unnecessary. For example, Python does not evaluate type
/// annotations on assignments in function bodies.
///
/// ## Example
///
/// Given:
///
/// ```python
/// from __future__ import annotations
///
///
/// def foo(bar: "Bar") -> "Bar": ...
/// ```
///
/// Use instead:
///
/// ```python
/// from __future__ import annotations
///
///
/// def foo(bar: Bar) -> Bar: ...
/// ```
///
/// Given:
///
/// ```python
/// def foo() -> None:
/// bar: "Bar"
/// ```
///
/// Use instead:
///
/// ```python
/// def foo() -> None:
/// bar: Bar
/// ```
///
/// ## Preview
///
/// When [preview] is enabled, if [`lint.future-annotations`] is set to `true`,
/// `from __future__ import annotations` will be added if doing so would allow an annotation to be
/// unquoted.
///
/// ## Fix safety
///
/// The rule's fix is marked as safe, unless [preview] and
/// [`lint.future-annotations`] are enabled and a `from __future__ import
/// annotations` import is added. Such an import may change the behavior of all annotations in the
/// file.
///
/// ## Options
/// - `lint.future-annotations`
///
/// ## See also
/// - [`quoted-annotation-in-stub`][PYI020]: A rule that
/// removes all quoted annotations from stub files
/// - [`quoted-type-alias`][TC008]: A rule that removes unnecessary quotes
/// from type aliases.
///
/// ## References
/// - [PEP 563 – Postponed Evaluation of Annotations](https://peps.python.org/pep-0563/)
/// - [Python documentation: `__future__`](https://docs.python.org/3/library/__future__.html#module-__future__)
///
/// [PYI020]: https://docs.astral.sh/ruff/rules/quoted-annotation-in-stub/
/// [TC008]: https://docs.astral.sh/ruff/rules/quoted-type-alias/
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.242")]
pub(crate) struct QuotedAnnotation;
impl AlwaysFixableViolation for QuotedAnnotation {
#[derive_message_formats]
fn message(&self) -> String {
"Remove quotes from type annotation".to_string()
}
fn fix_title(&self) -> String {
"Remove quotes".to_string()
}
}
/// UP037
pub(crate) fn quoted_annotation(checker: &Checker, annotation: &str, range: TextRange) {
let add_future_import = checker.settings().future_annotations
&& checker.semantic().in_runtime_evaluated_annotation();
if !(checker.semantic().in_typing_only_annotation() || add_future_import) {
return;
}
let placeholder_range = TextRange::up_to(annotation.text_len());
let spans_multiple_lines = annotation.contains_line_break(placeholder_range);
let last_token_is_comment = checker
.tokens()
// The actual last token will always be a logical newline,
// so we check the second to last
.get(checker.tokens().len().saturating_sub(2))
.is_some_and(|tok| tok.kind() == TokenKind::Comment);
let new_content = match (spans_multiple_lines, last_token_is_comment) {
(_, false) if in_parameter_annotation(range.start(), checker.semantic()) => {
annotation.to_string()
}
(false, false) => annotation.to_string(),
(true, false) => format!("({annotation})"),
(_, true) => format!("({annotation}\n)"),
};
let unquote_edit = Edit::range_replacement(new_content, range);
let fix = if add_future_import {
let import_edit = checker.importer().add_future_import();
Fix::unsafe_edits(unquote_edit, [import_edit])
} else {
Fix::safe_edit(unquote_edit)
};
checker
.report_diagnostic(QuotedAnnotation, range)
.set_fix(fix);
}
fn in_parameter_annotation(offset: TextSize, semantic: &SemanticModel) -> bool {
let Stmt::FunctionDef(stmt) = semantic.current_statement() else {
return false;
};
stmt.parameters.range.contains(offset)
}
| 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/pyupgrade/rules/use_pep604_isinstance.rs | crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_isinstance.rs | use std::fmt;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::Expr;
use ruff_python_ast::helpers::pep_604_union;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub(crate) enum CallKind {
Isinstance,
Issubclass,
}
impl fmt::Display for CallKind {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
CallKind::Isinstance => fmt.write_str("isinstance"),
CallKind::Issubclass => fmt.write_str("issubclass"),
}
}
}
impl CallKind {
pub(crate) fn from_name(name: &str) -> Option<Self> {
match name {
"isinstance" => Some(CallKind::Isinstance),
"issubclass" => Some(CallKind::Issubclass),
_ => None,
}
}
}
/// ## Removed
/// This rule was removed as using [PEP 604] syntax in `isinstance` and `issubclass` calls
/// isn't recommended practice, and it incorrectly suggests that other typing syntaxes like [PEP 695]
/// would be supported by `isinstance` and `issubclass`. Using the [PEP 604] syntax
/// is also slightly slower.
///
/// ## What it does
/// Checks for uses of `isinstance` and `issubclass` that take a tuple
/// of types for comparison.
///
/// ## Why is this bad?
/// Since Python 3.10, `isinstance` and `issubclass` can be passed a
/// `|`-separated union of types, which is consistent
/// with the union operator introduced in [PEP 604].
///
/// Note that this results in slower code. Ignore this rule if the
/// performance of an `isinstance` or `issubclass` check is a
/// concern, e.g., in a hot loop.
///
/// ## Example
/// ```python
/// isinstance(x, (int, float))
/// ```
///
/// Use instead:
/// ```python
/// isinstance(x, int | float)
/// ```
///
/// ## Options
/// - `target-version`
///
/// ## References
/// - [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance)
/// - [Python documentation: `issubclass`](https://docs.python.org/3/library/functions.html#issubclass)
///
/// [PEP 604]: https://peps.python.org/pep-0604/
/// [PEP 695]: https://peps.python.org/pep-0695/
#[derive(ViolationMetadata)]
#[violation_metadata(removed_since = "0.13.0")]
pub(crate) struct NonPEP604Isinstance {
kind: CallKind,
}
impl AlwaysFixableViolation for NonPEP604Isinstance {
#[derive_message_formats]
fn message(&self) -> String {
format!("Use `X | Y` in `{}` call instead of `(X, Y)`", self.kind)
}
fn fix_title(&self) -> String {
"Convert to `X | Y`".to_string()
}
}
/// UP038
pub(crate) fn use_pep604_isinstance(checker: &Checker, expr: &Expr, func: &Expr, args: &[Expr]) {
let Some(types) = args.get(1) else {
return;
};
let Expr::Tuple(tuple) = types else {
return;
};
// Ex) `()`
if tuple.is_empty() {
return;
}
// Ex) `(*args,)`
if tuple.iter().any(Expr::is_starred_expr) {
return;
}
let Some(builtin_function_name) = checker.semantic().resolve_builtin_symbol(func) else {
return;
};
let Some(kind) = CallKind::from_name(builtin_function_name) else {
return;
};
checker
.report_diagnostic(NonPEP604Isinstance { kind }, expr.range())
.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&pep_604_union(&tuple.elts)),
types.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/pyupgrade/rules/format_literals.rs | crates/ruff_linter/src/rules/pyupgrade/rules/format_literals.rs | use std::sync::LazyLock;
use anyhow::{Result, anyhow};
use libcst_native::{Arg, Expression};
use regex::Regex;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_codegen::Stylist;
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::cst::matchers::{
match_attribute, match_call_mut, match_expression, transform_expression_text,
};
use crate::fix::codemods::CodegenStylist;
use crate::rules::pyflakes::format::FormatSummary;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for unnecessary positional indices in format strings.
///
/// ## Why is this bad?
/// In Python 3.1 and later, format strings can use implicit positional
/// references. For example, `"{0}, {1}".format("Hello", "World")` can be
/// rewritten as `"{}, {}".format("Hello", "World")`.
///
/// If the positional indices appear exactly in-order, they can be omitted
/// in favor of automatic indices to improve readability.
///
/// ## Example
/// ```python
/// "{0}, {1}".format("Hello", "World") # "Hello, World"
/// ```
///
/// Use instead:
/// ```python
/// "{}, {}".format("Hello", "World") # "Hello, World"
/// ```
///
/// This fix is marked as unsafe because:
/// - Comments attached to arguments are not moved, which can cause comments to mismatch the actual arguments.
/// - If arguments have side effects (e.g., print), reordering may change program behavior.
///
/// ## References
/// - [Python documentation: Format String Syntax](https://docs.python.org/3/library/string.html#format-string-syntax)
/// - [Python documentation: `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.218")]
pub(crate) struct FormatLiterals;
impl Violation for FormatLiterals {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use implicit references for positional format fields".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Remove explicit positional indices".to_string())
}
}
/// UP030
pub(crate) fn format_literals(checker: &Checker, call: &ast::ExprCall, summary: &FormatSummary) {
// The format we expect is, e.g.: `"{0} {1}".format(...)`
if summary.has_nested_parts {
return;
}
if !summary.keywords.is_empty() {
return;
}
if !summary.autos.is_empty() {
return;
}
if summary.indices.is_empty() {
return;
}
if (0..summary.indices.len()).any(|index| !summary.indices.contains(&index)) {
return;
}
// If the positional indices aren't sequential (e.g., `"{1} {0}".format(1, 2)`), then we
// need to reorder the function arguments; so we need to ensure that the function
// arguments aren't splatted (e.g., `"{1} {0}".format(*foo)`), that there are a sufficient
// number of them, etc.
let arguments = if is_sequential(&summary.indices) {
Arguments::Preserve
} else {
// Ex) `"{1} {0}".format(foo=1, bar=2)`
if !call.arguments.keywords.is_empty() {
return;
}
// Ex) `"{1} {0}".format(foo)`
if call.arguments.args.len() < summary.indices.len() {
return;
}
// Ex) `"{1} {0}".format(*foo)`
if call
.arguments
.args
.iter()
.take(summary.indices.len())
.any(Expr::is_starred_expr)
{
return;
}
Arguments::Reorder(&summary.indices)
};
let mut diagnostic = checker.report_diagnostic(FormatLiterals, call.range());
diagnostic.try_set_fix(|| {
generate_call(call, arguments, checker.locator(), checker.stylist())
.map(|suggestion| Fix::unsafe_edit(Edit::range_replacement(suggestion, call.range())))
});
}
/// Returns true if the indices are sequential.
fn is_sequential(indices: &[usize]) -> bool {
indices.iter().enumerate().all(|(idx, value)| idx == *value)
}
static FORMAT_SPECIFIER: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"(?x)
(?P<prefix>
^|[^{]|(?:\{{2})+ # preceded by nothing, a non-brace, or an even number of braces
)
\{ # opening curly brace
(?P<int>\d+) # followed by any integer
(?P<fmt>.*?) # followed by any text
} # followed by a closing brace
",
)
.unwrap()
});
/// Remove the explicit positional indices from a format string.
fn remove_specifiers<'a>(value: &mut Expression<'a>, arena: &'a typed_arena::Arena<String>) {
match value {
Expression::SimpleString(expr) => {
expr.value = arena.alloc(
FORMAT_SPECIFIER
.replace_all(expr.value, "$prefix{$fmt}")
.to_string(),
);
}
Expression::ConcatenatedString(expr) => {
let mut stack = vec![&mut expr.left, &mut expr.right];
while let Some(string) = stack.pop() {
match string.as_mut() {
libcst_native::String::Simple(string) => {
string.value = arena.alloc(
FORMAT_SPECIFIER
.replace_all(string.value, "$prefix{$fmt}")
.to_string(),
);
}
libcst_native::String::Concatenated(string) => {
stack.push(&mut string.left);
stack.push(&mut string.right);
}
libcst_native::String::Formatted(_) | libcst_native::String::Templated(_) => {}
}
}
}
_ => {}
}
}
/// Return the corrected argument vector.
fn generate_arguments<'a>(arguments: &[Arg<'a>], order: &[usize]) -> Result<Vec<Arg<'a>>> {
let mut new_arguments: Vec<Arg> = Vec::with_capacity(arguments.len());
for (idx, given) in order.iter().enumerate() {
// We need to keep the formatting in the same order but move the values.
let values = arguments
.get(*given)
.ok_or_else(|| anyhow!("Failed to extract argument at: {given}"))?;
let formatting = arguments
.get(idx)
.ok_or_else(|| anyhow!("Failed to extract argument at: {idx}"))?;
let argument = Arg {
value: values.value.clone(),
comma: formatting.comma.clone(),
equal: None,
keyword: None,
star: values.star,
whitespace_after_star: formatting.whitespace_after_star.clone(),
whitespace_after_arg: formatting.whitespace_after_arg.clone(),
};
new_arguments.push(argument);
}
Ok(new_arguments)
}
#[derive(Debug, Copy, Clone)]
enum Arguments<'a> {
/// Preserve the arguments to the `.format(...)` call.
Preserve,
/// Reorder the arguments to the `.format(...)` call, based on the given
/// indices.
Reorder(&'a [usize]),
}
/// Returns the corrected function call.
fn generate_call(
call: &ast::ExprCall,
arguments: Arguments,
locator: &Locator,
stylist: &Stylist,
) -> Result<String> {
let source_code = locator.slice(call);
let output = transform_expression_text(source_code, |source_code| {
let mut expression = match_expression(&source_code)?;
// Fix the call arguments.
let call = match_call_mut(&mut expression)?;
if let Arguments::Reorder(order) = arguments {
call.args = generate_arguments(&call.args, order)?;
}
// Fix the string itself.
let item = match_attribute(&mut call.func)?;
let arena = typed_arena::Arena::new();
remove_specifiers(&mut item.value, &arena);
Ok(expression.codegen_stylist(stylist))
})?;
// Ex) `'{' '0}'.format(1)`
if output == source_code {
return Err(anyhow!("Unable to identify format literals"));
}
Ok(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/pyupgrade/rules/unnecessary_encode_utf8.rs | crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs | use std::fmt::Write as _;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::{TokenKind, Tokens};
use ruff_python_ast::{self as ast, Arguments, Expr, Keyword};
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, pad, remove_argument};
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for unnecessary calls to `encode` as UTF-8.
///
/// ## Why is this bad?
/// UTF-8 is the default encoding in Python, so there is no need to call
/// `encode` when UTF-8 is the desired encoding. Instead, use a bytes literal.
///
/// ## Example
/// ```python
/// "foo".encode("utf-8")
/// ```
///
/// Use instead:
/// ```python
/// b"foo"
/// ```
///
/// ## References
/// - [Python documentation: `str.encode`](https://docs.python.org/3/library/stdtypes.html#str.encode)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct UnnecessaryEncodeUTF8 {
reason: Reason,
}
impl AlwaysFixableViolation for UnnecessaryEncodeUTF8 {
#[derive_message_formats]
fn message(&self) -> String {
match self.reason {
Reason::BytesLiteral => "Unnecessary call to `encode` as UTF-8".to_string(),
Reason::DefaultArgument => {
"Unnecessary UTF-8 `encoding` argument to `encode`".to_string()
}
}
}
fn fix_title(&self) -> String {
match self.reason {
Reason::BytesLiteral => "Rewrite as bytes literal".to_string(),
Reason::DefaultArgument => "Remove unnecessary `encoding` argument".to_string(),
}
}
}
#[derive(Debug, PartialEq, Eq)]
enum Reason {
BytesLiteral,
DefaultArgument,
}
const UTF8_LITERALS: &[&str] = &["utf-8", "utf8", "utf_8", "u8", "utf", "cp65001"];
fn match_encoded_variable(func: &Expr) -> Option<&Expr> {
let Expr::Attribute(ast::ExprAttribute {
value: variable,
attr,
..
}) = func
else {
return None;
};
if attr != "encode" {
return None;
}
Some(variable)
}
fn is_utf8_encoding_arg(arg: &Expr) -> bool {
if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &arg {
UTF8_LITERALS.contains(&value.to_str().to_lowercase().as_str())
} else {
false
}
}
#[derive(Debug)]
enum EncodingArg<'a> {
/// Ex) `"".encode()`
Empty,
/// Ex) `"".encode("utf-8")`
Positional(&'a Expr),
/// Ex) `"".encode(encoding="utf-8")`
Keyword(&'a Keyword),
}
/// Return the encoding argument to an `encode` call, if it can be determined to be a
/// UTF-8-equivalent encoding.
fn match_encoding_arg(arguments: &Arguments) -> Option<EncodingArg<'_>> {
match (&*arguments.args, &*arguments.keywords) {
// Ex `"".encode()`
([], []) => return Some(EncodingArg::Empty),
// Ex `"".encode(encoding)`
([arg], []) => {
if is_utf8_encoding_arg(arg) {
return Some(EncodingArg::Positional(arg));
}
}
// Ex `"".encode(kwarg=kwarg)`
([], [keyword]) => {
if keyword.arg.as_ref().is_some_and(|arg| arg == "encoding") {
if is_utf8_encoding_arg(&keyword.value) {
return Some(EncodingArg::Keyword(keyword));
}
}
}
// Ex `"".encode(*args, **kwargs)`
_ => {}
}
None
}
/// Return a [`Fix`] replacing the call to encode with a byte string.
fn replace_with_bytes_literal(locator: &Locator, call: &ast::ExprCall, tokens: &Tokens) -> Fix {
// Build up a replacement string by prefixing all string tokens with `b`.
let mut replacement = String::with_capacity(call.range().len().to_usize() + 1);
let mut prev = call.start();
for token in tokens.in_range(call.range()) {
match token.kind() {
TokenKind::Dot => break,
TokenKind::String => {
replacement.push_str(locator.slice(TextRange::new(prev, token.start())));
let string = locator.slice(token);
let _ = write!(
&mut replacement,
"b{}",
&string.trim_start_matches('u').trim_start_matches('U')
);
}
_ => {
replacement.push_str(locator.slice(TextRange::new(prev, token.end())));
}
}
prev = token.end();
}
Fix::safe_edit(Edit::range_replacement(
pad(replacement, call.range(), locator),
call.range(),
))
}
/// UP012
pub(crate) fn unnecessary_encode_utf8(checker: &Checker, call: &ast::ExprCall) {
let Some(variable) = match_encoded_variable(&call.func) else {
return;
};
match variable {
Expr::StringLiteral(ast::ExprStringLiteral { value: literal, .. }) => {
// Ex) `"str".encode()`, `"str".encode("utf-8")`
if let Some(encoding_arg) = match_encoding_arg(&call.arguments) {
if literal.to_str().is_ascii() {
// Ex) Convert `"foo".encode()` to `b"foo"`.
let mut diagnostic = checker.report_diagnostic(
UnnecessaryEncodeUTF8 {
reason: Reason::BytesLiteral,
},
call.range(),
);
diagnostic.set_fix(replace_with_bytes_literal(
checker.locator(),
call,
checker.tokens(),
));
} else if let EncodingArg::Keyword(kwarg) = encoding_arg {
// Ex) Convert `"unicode text©".encode(encoding="utf-8")` to
// `"unicode text©".encode()`.
let mut diagnostic = checker.report_diagnostic(
UnnecessaryEncodeUTF8 {
reason: Reason::DefaultArgument,
},
call.range(),
);
diagnostic.try_set_fix(|| {
remove_argument(
kwarg,
&call.arguments,
Parentheses::Preserve,
checker.locator().contents(),
checker.tokens(),
)
.map(Fix::safe_edit)
});
} else if let EncodingArg::Positional(arg) = encoding_arg {
// Ex) Convert `"unicode text©".encode("utf-8")` to `"unicode text©".encode()`.
let mut diagnostic = checker.report_diagnostic(
UnnecessaryEncodeUTF8 {
reason: Reason::DefaultArgument,
},
call.range(),
);
diagnostic.try_set_fix(|| {
remove_argument(
arg,
&call.arguments,
Parentheses::Preserve,
checker.locator().contents(),
checker.tokens(),
)
.map(Fix::safe_edit)
});
}
}
}
// Ex) `f"foo{bar}".encode("utf-8")`
Expr::FString(_) => {
if let Some(encoding_arg) = match_encoding_arg(&call.arguments) {
if let EncodingArg::Keyword(kwarg) = encoding_arg {
// Ex) Convert `f"unicode text©".encode(encoding="utf-8")` to
// `f"unicode text©".encode()`.
let mut diagnostic = checker.report_diagnostic(
UnnecessaryEncodeUTF8 {
reason: Reason::DefaultArgument,
},
call.range(),
);
diagnostic.try_set_fix(|| {
remove_argument(
kwarg,
&call.arguments,
Parentheses::Preserve,
checker.locator().contents(),
checker.tokens(),
)
.map(Fix::safe_edit)
});
} else if let EncodingArg::Positional(arg) = encoding_arg {
// Ex) Convert `f"unicode text©".encode("utf-8")` to `f"unicode text©".encode()`.
let mut diagnostic = checker.report_diagnostic(
UnnecessaryEncodeUTF8 {
reason: Reason::DefaultArgument,
},
call.range(),
);
diagnostic.try_set_fix(|| {
remove_argument(
arg,
&call.arguments,
Parentheses::Preserve,
checker.locator().contents(),
checker.tokens(),
)
.map(Fix::safe_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/pyupgrade/rules/unicode_kind_prefix.rs | crates/ruff_linter/src/rules/pyupgrade/rules/unicode_kind_prefix.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::StringLiteral;
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of the Unicode kind prefix (`u`) in strings.
///
/// ## Why is this bad?
/// In Python 3, all strings are Unicode by default. The Unicode kind prefix is
/// unnecessary and should be removed to avoid confusion.
///
/// ## Example
/// ```python
/// u"foo"
/// ```
///
/// Use instead:
/// ```python
/// "foo"
/// ```
///
/// ## References
/// - [Python documentation: Unicode HOWTO](https://docs.python.org/3/howto/unicode.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.201")]
pub(crate) struct UnicodeKindPrefix;
impl AlwaysFixableViolation for UnicodeKindPrefix {
#[derive_message_formats]
fn message(&self) -> String {
"Remove unicode literals from strings".to_string()
}
fn fix_title(&self) -> String {
"Remove unicode prefix".to_string()
}
}
/// UP025
pub(crate) fn unicode_kind_prefix(checker: &Checker, string: &StringLiteral) {
if string.flags.prefix().is_unicode() {
let mut diagnostic = checker.report_diagnostic(UnicodeKindPrefix, string.range);
let prefix_range = TextRange::at(string.start(), TextSize::new(1));
let locator = checker.locator();
let content = locator
.slice(TextRange::new(prefix_range.end(), string.end()))
.to_owned();
// If the preceding character is equivalent to the quote character, insert a space to avoid a
// syntax error. For example, when removing the `u` prefix in `""u""`, rewrite to `"" ""`
// instead of `""""`.
// see https://github.com/astral-sh/ruff/issues/18895
let edit = if locator
.slice(TextRange::up_to(prefix_range.start()))
.chars()
.last()
.is_some_and(|char| content.starts_with(char))
{
Edit::range_replacement(" ".to_string(), prefix_range)
} else {
Edit::range_deletion(prefix_range)
};
diagnostic.set_fix(Fix::safe_edit(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/pyupgrade/rules/deprecated_import.rs | crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_import.rs | use itertools::Itertools;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::Tokens;
use ruff_python_ast::whitespace::indentation;
use ruff_python_ast::{Alias, StmtImportFrom, StmtRef};
use ruff_python_codegen::Stylist;
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::rules::pyupgrade::fixes;
use crate::rules::pyupgrade::rules::unnecessary_future_import::is_import_required_by_isort;
use crate::{Edit, Fix, FixAvailability, Violation};
use ruff_python_ast::PythonVersion;
use super::RequiredImports;
/// An import was moved and renamed as part of a deprecation.
/// For example, `typing.AbstractSet` was moved to `collections.abc.Set`.
#[derive(Debug, PartialEq, Eq)]
struct WithRename {
module: String,
member: String,
target: String,
}
/// A series of imports from the same module were moved to another module,
/// but retain their original names.
#[derive(Debug, PartialEq, Eq)]
struct WithoutRename {
target: String,
members: Vec<String>,
fixable: bool,
}
#[derive(Debug, PartialEq, Eq)]
enum Deprecation {
WithRename(WithRename),
WithoutRename(WithoutRename),
}
/// ## What it does
/// Checks for uses of deprecated imports based on the minimum supported
/// Python version.
///
/// ## Why is this bad?
/// Deprecated imports may be removed in future versions of Python, and
/// should be replaced with their new equivalents.
///
/// Note that, in some cases, it may be preferable to continue importing
/// members from `typing_extensions` even after they're added to the Python
/// standard library, as `typing_extensions` can backport bugfixes and
/// optimizations from later Python versions. This rule thus avoids flagging
/// imports from `typing_extensions` in such cases.
///
/// ## Example
/// ```python
/// from collections import Sequence
/// ```
///
/// Use instead:
/// ```python
/// from collections.abc import Sequence
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.239")]
pub(crate) struct DeprecatedImport {
deprecation: Deprecation,
}
impl Violation for DeprecatedImport {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
match &self.deprecation {
Deprecation::WithoutRename(WithoutRename {
members, target, ..
}) => {
let names = members.iter().map(|name| format!("`{name}`")).join(", ");
format!("Import from `{target}` instead: {names}")
}
Deprecation::WithRename(WithRename {
module,
member,
target,
}) => {
format!("`{module}.{member}` is deprecated, use `{target}` instead")
}
}
}
fn fix_title(&self) -> Option<String> {
if let Deprecation::WithoutRename(WithoutRename { target, .. }) = &self.deprecation {
Some(format!("Import from `{target}`"))
} else {
None
}
}
}
/// Returns `true` if the module may contain deprecated imports.
fn is_relevant_module(module: &str) -> bool {
matches!(
module,
"collections"
| "pipes"
| "mypy_extensions"
| "typing_extensions"
| "typing"
| "typing.re"
| "backports.strenum"
)
}
// Members of `collections` that were moved to `collections.abc`.
const COLLECTIONS_TO_ABC: &[&str] = &[
"AsyncGenerator",
"AsyncIterable",
"AsyncIterator",
"Awaitable",
"ByteString",
"Callable",
"Collection",
"Container",
"Coroutine",
"Generator",
"Hashable",
"ItemsView",
"Iterable",
"Iterator",
"KeysView",
"Mapping",
"MappingView",
"MutableMapping",
"MutableSequence",
"MutableSet",
"Reversible",
"Sequence",
"Set",
"Sized",
"ValuesView",
];
// Members of `pipes` that were moved to `shlex`.
const PIPES_TO_SHLEX: &[&str] = &["quote"];
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING: &[&str] = &[
"AbstractSet",
"AnyStr",
"AsyncIterable",
"AsyncIterator",
"Awaitable",
"BinaryIO",
"Callable",
"ClassVar",
"Collection",
"Container",
"Coroutine",
"DefaultDict",
"Dict",
"FrozenSet",
"Generic",
"Hashable",
"IO",
"ItemsView",
"Iterable",
"Iterator",
"KeysView",
"List",
"Mapping",
"MappingView",
"Match",
"MutableMapping",
"MutableSequence",
"MutableSet",
"Optional",
"Pattern",
"Reversible",
"Sequence",
"Set",
"Sized",
"TYPE_CHECKING",
"Text",
"TextIO",
"Tuple",
"Type",
"Union",
"ValuesView",
"cast",
"no_type_check",
"no_type_check_decorator",
// Introduced in Python 3.5.2, but `typing_extensions` contains backported bugfixes and
// optimizations,
// "NewType",
// "Generator",
// "ContextManager",
];
// Python 3.7+
// Members of `mypy_extensions` that were moved to `typing`.
const MYPY_EXTENSIONS_TO_TYPING_37: &[&str] = &["NoReturn"];
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_37: &[&str] = &[
"ChainMap",
"Counter",
"Deque",
"ForwardRef",
"NoReturn",
// Introduced in Python <=3.7, but `typing_extensions` backports some features
// from Python 3.12/3.13
// "AsyncContextManager",
// "AsyncGenerator",
// "NamedTuple",
];
// Python 3.8+
// Members of `mypy_extensions` that were moved to `typing`.
const MYPY_EXTENSIONS_TO_TYPING_38: &[&str] = &["TypedDict"];
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_38: &[&str] = &[
"Final",
"OrderedDict",
// Introduced in Python 3.8, but `typing_extensions` contains backported bugfixes and
// optimizations.
// "Literal",
// "Protocol",
// "SupportsIndex",
// "runtime_checkable",
// "TypedDict",
];
// Python 3.9+
// Members of `typing` that were moved to `collections.abc`.
const TYPING_TO_COLLECTIONS_ABC_39: &[&str] = &[
"AsyncGenerator",
"AsyncIterable",
"AsyncIterator",
"Awaitable",
"ByteString",
"Collection",
"Container",
"Coroutine",
"Generator",
"Hashable",
"ItemsView",
"Iterable",
"Iterator",
"KeysView",
"Mapping",
"MappingView",
"MutableMapping",
"MutableSequence",
"MutableSet",
"Reversible",
"Sequence",
"Sized",
"ValuesView",
];
// Members of `typing` that were moved to `collections`.
const TYPING_TO_COLLECTIONS_39: &[&str] = &["ChainMap", "Counter", "OrderedDict"];
// Members of `typing` that were moved to `typing.re`.
const TYPING_TO_RE_39: &[&str] = &["Match", "Pattern"];
// Members of `typing.re` that were moved to `re`.
const TYPING_RE_TO_RE_39: &[&str] = &["Match", "Pattern"];
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_39: &[&str] = &["Annotated"];
// Members of `typing` that were moved _and_ renamed (and thus cannot be
// automatically fixed).
const TYPING_TO_RENAME_PY39: &[(&str, &str)] = &[
(
"AsyncContextManager",
"contextlib.AbstractAsyncContextManager",
),
("ContextManager", "contextlib.AbstractContextManager"),
("AbstractSet", "collections.abc.Set"),
("Tuple", "tuple"),
("List", "list"),
("FrozenSet", "frozenset"),
("Dict", "dict"),
("Type", "type"),
("Set", "set"),
("Deque", "collections.deque"),
("DefaultDict", "collections.defaultdict"),
];
// Python 3.10+
// Members of `typing` that were moved to `collections.abc`.
const TYPING_TO_COLLECTIONS_ABC_310: &[&str] = &["Callable"];
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_310: &[&str] = &[
"Concatenate",
"Literal",
"NewType",
"ParamSpecArgs",
"ParamSpecKwargs",
"TypeAlias",
"TypeGuard",
"get_args",
"get_origin",
// Introduced in Python 3.10, but `typing_extensions` equivalent
// also checks for `typing_extensions.TypedDict` in addition to `typing.TypedDict`.
// "is_typeddict",
];
// Python 3.11+
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_311: &[&str] = &[
"Any",
"LiteralString",
"Never",
"NotRequired",
"Required",
"Self",
"assert_never",
"assert_type",
"clear_overloads",
"final",
"get_overloads",
"overload",
"reveal_type",
];
const BACKPORTS_STR_ENUM_TO_ENUM_311: &[&str] = &["StrEnum"];
// Python 3.12+
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_312: &[&str] = &[
// Introduced in Python 3.8, but `typing_extensions` backports a ton of optimizations that were
// added in Python 3.12.
"Protocol",
"SupportsAbs",
"SupportsBytes",
"SupportsComplex",
"SupportsFloat",
"SupportsIndex",
"SupportsInt",
"SupportsRound",
"TypeAliasType",
"Unpack",
// Introduced in Python 3.6, but `typing_extensions` backports bugfixes and features
"NamedTuple",
// Introduced in Python 3.11, but `typing_extensions` backports the `frozen_default` argument,
// which was introduced in Python 3.12.
"dataclass_transform",
"override",
];
// Members of `typing_extensions` that were moved to `collections.abc`.
const TYPING_EXTENSIONS_TO_COLLECTIONS_ABC_312: &[&str] = &["Buffer"];
// Members of `typing_extensions` that were moved to `types`.
const TYPING_EXTENSIONS_TO_TYPES_312: &[&str] = &["get_original_bases"];
// Python 3.13+
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_313: &[&str] = &[
"get_protocol_members",
"is_protocol",
"NoDefault",
"ReadOnly",
"TypeIs",
// Introduced in Python 3.5,
// but typing_extensions backports features from py313:
"get_type_hints",
// Introduced in Python 3.6,
// but typing_extensions backports features from py313:
"ContextManager",
"Generator",
// Introduced in Python 3.7,
// but typing_extensions backports features from py313:
"AsyncContextManager",
"AsyncGenerator",
// Introduced in Python 3.8, but typing_extensions
// backports features and bugfixes from py313:
"Protocol",
"runtime_checkable",
// Introduced in earlier Python versions,
// but typing_extensions backports PEP-696:
"ParamSpec",
"TypeVar",
"TypeVarTuple",
// `typing_extensions` backports PEP 728 (TypedDict with Typed Extra Items)
// "TypedDict",
];
// Members of `typing_extensions` that were moved to `types`.
const TYPING_EXTENSIONS_TO_TYPES_313: &[&str] = &["CapsuleType"];
// Members of typing_extensions that were moved to `warnings`
const TYPING_EXTENSIONS_TO_WARNINGS_313: &[&str] = &["deprecated"];
struct ImportReplacer<'a> {
import_from_stmt: &'a StmtImportFrom,
module: &'a str,
locator: &'a Locator<'a>,
stylist: &'a Stylist<'a>,
tokens: &'a Tokens,
version: PythonVersion,
required_imports: &'a RequiredImports,
}
impl<'a> ImportReplacer<'a> {
const fn new(
import_from_stmt: &'a StmtImportFrom,
module: &'a str,
locator: &'a Locator<'a>,
stylist: &'a Stylist<'a>,
tokens: &'a Tokens,
version: PythonVersion,
required_imports: &'a RequiredImports,
) -> Self {
Self {
import_from_stmt,
module,
locator,
stylist,
tokens,
version,
required_imports,
}
}
/// Return a list of deprecated imports whose members were renamed.
fn with_renames(&self) -> Vec<WithRename> {
let mut operations = vec![];
if self.module == "typing" {
if self.version >= PythonVersion::PY39 {
for member in &self.import_from_stmt.names {
if is_import_required_by_isort(
self.required_imports,
StmtRef::ImportFrom(self.import_from_stmt),
member,
) {
continue;
}
if let Some(target) = TYPING_TO_RENAME_PY39.iter().find_map(|(name, target)| {
if &member.name == *name {
Some(*target)
} else {
None
}
}) {
operations.push(WithRename {
module: "typing".to_string(),
member: member.name.to_string(),
target: target.to_string(),
});
}
}
}
}
operations
}
/// Return a list of deprecated imports whose members were moved, but not renamed.
fn without_renames(&self) -> Vec<(WithoutRename, Option<String>)> {
let mut operations = vec![];
match self.module {
"collections" => {
if let Some(operation) = self.try_replace(COLLECTIONS_TO_ABC, "collections.abc") {
operations.push(operation);
}
}
"pipes" => {
if let Some(operation) = self.try_replace(PIPES_TO_SHLEX, "shlex") {
operations.push(operation);
}
}
"typing_extensions" => {
// `typing_extensions` to `collections.abc`
let mut typing_extensions_to_collections_abc = vec![];
if self.version >= PythonVersion::PY312 {
typing_extensions_to_collections_abc
.extend(TYPING_EXTENSIONS_TO_COLLECTIONS_ABC_312);
}
if let Some(operation) =
self.try_replace(&typing_extensions_to_collections_abc, "collections.abc")
{
operations.push(operation);
}
// `typing_extensions` to `warnings`
let mut typing_extensions_to_warnings = vec![];
if self.version >= PythonVersion::PY313 {
typing_extensions_to_warnings.extend(TYPING_EXTENSIONS_TO_WARNINGS_313);
}
if let Some(operation) =
self.try_replace(&typing_extensions_to_warnings, "warnings")
{
operations.push(operation);
}
// `typing_extensions` to `types`
let mut typing_extensions_to_types = vec![];
if self.version >= PythonVersion::PY312 {
typing_extensions_to_types.extend(TYPING_EXTENSIONS_TO_TYPES_312);
}
if self.version >= PythonVersion::PY313 {
typing_extensions_to_types.extend(TYPING_EXTENSIONS_TO_TYPES_313);
}
if let Some(operation) = self.try_replace(&typing_extensions_to_types, "types") {
operations.push(operation);
}
// `typing_extensions` to `typing`
let mut typing_extensions_to_typing = TYPING_EXTENSIONS_TO_TYPING.to_vec();
if self.version >= PythonVersion::PY37 {
typing_extensions_to_typing.extend(TYPING_EXTENSIONS_TO_TYPING_37);
}
if self.version >= PythonVersion::PY38 {
typing_extensions_to_typing.extend(TYPING_EXTENSIONS_TO_TYPING_38);
}
if self.version >= PythonVersion::PY39 {
typing_extensions_to_typing.extend(TYPING_EXTENSIONS_TO_TYPING_39);
}
if self.version >= PythonVersion::PY310 {
typing_extensions_to_typing.extend(TYPING_EXTENSIONS_TO_TYPING_310);
}
if self.version >= PythonVersion::PY311 {
typing_extensions_to_typing.extend(TYPING_EXTENSIONS_TO_TYPING_311);
}
if self.version >= PythonVersion::PY312 {
typing_extensions_to_typing.extend(TYPING_EXTENSIONS_TO_TYPING_312);
}
if self.version >= PythonVersion::PY313 {
typing_extensions_to_typing.extend(TYPING_EXTENSIONS_TO_TYPING_313);
}
if let Some(operation) = self.try_replace(&typing_extensions_to_typing, "typing") {
operations.push(operation);
}
}
"mypy_extensions" => {
let mut mypy_extensions_to_typing = vec![];
if self.version >= PythonVersion::PY37 {
mypy_extensions_to_typing.extend(MYPY_EXTENSIONS_TO_TYPING_37);
}
if self.version >= PythonVersion::PY38 {
mypy_extensions_to_typing.extend(MYPY_EXTENSIONS_TO_TYPING_38);
}
if let Some(operation) = self.try_replace(&mypy_extensions_to_typing, "typing") {
operations.push(operation);
}
}
"typing" => {
// `typing` to `collections.abc`
let mut typing_to_collections_abc = vec![];
if self.version >= PythonVersion::PY39 {
typing_to_collections_abc.extend(TYPING_TO_COLLECTIONS_ABC_39);
}
if self.version >= PythonVersion::PY310 {
typing_to_collections_abc.extend(TYPING_TO_COLLECTIONS_ABC_310);
}
if let Some(operation) =
self.try_replace(&typing_to_collections_abc, "collections.abc")
{
operations.push(operation);
}
// `typing` to `collections`
let mut typing_to_collections = vec![];
if self.version >= PythonVersion::PY39 {
typing_to_collections.extend(TYPING_TO_COLLECTIONS_39);
}
if let Some(operation) = self.try_replace(&typing_to_collections, "collections") {
operations.push(operation);
}
// `typing` to `re`
let mut typing_to_re = vec![];
if self.version >= PythonVersion::PY39 {
typing_to_re.extend(TYPING_TO_RE_39);
}
if let Some(operation) = self.try_replace(&typing_to_re, "re") {
operations.push(operation);
}
}
"typing.re" if self.version >= PythonVersion::PY39 => {
if let Some(operation) = self.try_replace(TYPING_RE_TO_RE_39, "re") {
operations.push(operation);
}
}
"backports.strenum" if self.version >= PythonVersion::PY311 => {
if let Some(operation) = self.try_replace(BACKPORTS_STR_ENUM_TO_ENUM_311, "enum") {
operations.push(operation);
}
}
_ => {}
}
operations
}
fn try_replace(
&'a self,
candidates: &[&str],
target: &'a str,
) -> Option<(WithoutRename, Option<String>)> {
if candidates.is_empty() {
return None;
}
let (matched_names, unmatched_names) = self.partition_imports(candidates);
// If we have no matched names, we don't need to do anything.
if matched_names.is_empty() {
return None;
}
if unmatched_names.is_empty() {
let matched = ImportReplacer::format_import_from(&matched_names, target);
let operation = WithoutRename {
target: target.to_string(),
members: matched_names
.iter()
.map(|name| name.name.to_string())
.collect(),
fixable: true,
};
let fix = Some(matched);
Some((operation, fix))
} else {
let indentation = indentation(self.locator.contents(), self.import_from_stmt);
// If we have matched _and_ unmatched names, but the import is not on its own
// line, we can't add a statement after it. For example, if we have
// `if True: import foo`, we can't add a statement to the next line.
let Some(indentation) = indentation else {
let operation = WithoutRename {
target: target.to_string(),
members: matched_names
.iter()
.map(|name| name.name.to_string())
.collect(),
fixable: false,
};
let fix = None;
return Some((operation, fix));
};
let matched = ImportReplacer::format_import_from(&matched_names, target);
let unmatched = fixes::remove_import_members(
self.locator,
self.import_from_stmt,
self.tokens,
&matched_names
.iter()
.map(|name| name.name.as_str())
.collect::<Vec<_>>(),
);
let operation = WithoutRename {
target: target.to_string(),
members: matched_names
.iter()
.map(|name| name.name.to_string())
.collect(),
fixable: true,
};
let fix = Some(format!(
"{unmatched}{}{}{matched}",
self.stylist.line_ending().as_str(),
indentation,
));
Some((operation, fix))
}
}
/// Partitions imports into matched and unmatched names.
fn partition_imports(&self, candidates: &[&str]) -> (Vec<&Alias>, Vec<&Alias>) {
let mut matched_names = vec![];
let mut unmatched_names = vec![];
for name in &self.import_from_stmt.names {
if is_import_required_by_isort(
self.required_imports,
StmtRef::ImportFrom(self.import_from_stmt),
name,
) {
unmatched_names.push(name);
} else if candidates.contains(&name.name.as_str()) {
matched_names.push(name);
} else {
unmatched_names.push(name);
}
}
(matched_names, unmatched_names)
}
/// Converts a list of names and a module into an `import from`-style
/// import.
fn format_import_from(names: &[&Alias], module: &str) -> String {
// Construct the whitespace strings.
// Generate the formatted names.
let qualified_names: String = names
.iter()
.map(|name| match &name.asname {
Some(asname) => format!("{} as {}", name.name, asname),
None => format!("{}", name.name),
})
.join(", ");
format!("from {module} import {qualified_names}")
}
}
/// UP035
pub(crate) fn deprecated_import(checker: &Checker, import_from_stmt: &StmtImportFrom) {
// Avoid relative and star imports.
if import_from_stmt.level > 0 {
return;
}
if import_from_stmt
.names
.first()
.is_some_and(|name| &name.name == "*")
{
return;
}
let Some(module) = import_from_stmt.module.as_deref() else {
return;
};
if !is_relevant_module(module) {
return;
}
let fixer = ImportReplacer::new(
import_from_stmt,
module,
checker.locator(),
checker.stylist(),
checker.tokens(),
checker.target_version(),
&checker.settings().isort.required_imports,
);
for (operation, fix) in fixer.without_renames() {
let mut diagnostic = checker.report_diagnostic(
DeprecatedImport {
deprecation: Deprecation::WithoutRename(operation),
},
import_from_stmt.range(),
);
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
if let Some(content) = fix {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
content,
import_from_stmt.range(),
)));
}
}
for operation in fixer.with_renames() {
let mut diagnostic = checker.report_diagnostic(
DeprecatedImport {
deprecation: Deprecation::WithRename(operation),
},
import_from_stmt.range(),
);
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
}
}
| 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/pyupgrade/rules/deprecated_c_element_tree.rs | crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_c_element_tree.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Stmt};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of the `xml.etree.cElementTree` module.
///
/// ## Why is this bad?
/// In Python 3.3, `xml.etree.cElementTree` was deprecated in favor of
/// `xml.etree.ElementTree`.
///
/// ## Example
/// ```python
/// from xml.etree import cElementTree as ET
/// ```
///
/// Use instead:
/// ```python
/// from xml.etree import ElementTree as ET
/// ```
///
/// ## References
/// - [Python documentation: `xml.etree.ElementTree`](https://docs.python.org/3/library/xml.etree.elementtree.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.199")]
pub(crate) struct DeprecatedCElementTree;
impl AlwaysFixableViolation for DeprecatedCElementTree {
#[derive_message_formats]
fn message(&self) -> String {
"`cElementTree` is deprecated, use `ElementTree`".to_string()
}
fn fix_title(&self) -> String {
"Replace with `ElementTree`".to_string()
}
}
fn add_check_for_node<T>(checker: &Checker, node: &T)
where
T: Ranged,
{
let mut diagnostic = checker.report_diagnostic(DeprecatedCElementTree, node.range());
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
let contents = checker.locator().slice(node);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
contents.replacen("cElementTree", "ElementTree", 1),
node.range(),
)));
}
/// UP023
pub(crate) fn deprecated_c_element_tree(checker: &Checker, stmt: &Stmt) {
match stmt {
Stmt::Import(ast::StmtImport {
names,
range: _,
node_index: _,
}) => {
// Ex) `import xml.etree.cElementTree as ET`
for name in names {
if &name.name == "xml.etree.cElementTree" && name.asname.is_some() {
add_check_for_node(checker, name);
}
}
}
Stmt::ImportFrom(ast::StmtImportFrom {
module,
names,
level,
range: _,
node_index: _,
}) => {
if *level > 0 {
// Ex) `import .xml.etree.cElementTree as ET`
} else if let Some(module) = module {
if module == "xml.etree.cElementTree" {
// Ex) `from xml.etree.cElementTree import XML`
add_check_for_node(checker, stmt);
} else if module == "xml.etree" {
// Ex) `from xml.etree import cElementTree as ET`
for name in names {
if &name.name == "cElementTree" && name.asname.is_some() {
add_check_for_node(checker, name);
}
}
}
}
}
_ => panic!("Expected Stmt::Import | Stmt::ImportFrom"),
}
}
| 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/pyupgrade/rules/useless_metaclass_type.rs | crates/ruff_linter/src/rules/pyupgrade/rules/useless_metaclass_type.rs | use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix;
use crate::{AlwaysFixableViolation, Fix};
/// ## What it does
/// Checks for the use of `__metaclass__ = type` in class definitions.
///
/// ## Why is this bad?
/// Since Python 3, `__metaclass__ = type` is implied and can thus be omitted.
///
/// ## Example
///
/// ```python
/// class Foo:
/// __metaclass__ = type
/// ```
///
/// Use instead:
///
/// ```python
/// class Foo: ...
/// ```
///
/// ## References
/// - [PEP 3115 – Metaclasses in Python 3000](https://peps.python.org/pep-3115/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct UselessMetaclassType;
impl AlwaysFixableViolation for UselessMetaclassType {
#[derive_message_formats]
fn message(&self) -> String {
"`__metaclass__ = type` is implied".to_string()
}
fn fix_title(&self) -> String {
"Remove `__metaclass__ = type`".to_string()
}
}
/// UP001
pub(crate) fn useless_metaclass_type(
checker: &Checker,
stmt: &Stmt,
value: &Expr,
targets: &[Expr],
) {
let [Expr::Name(ast::ExprName { id, .. })] = targets else {
return;
};
if id != "__metaclass__" {
return;
}
let Expr::Name(ast::ExprName { id, .. }) = value else {
return;
};
if id != "type" {
return;
}
let mut diagnostic = checker.report_diagnostic(UselessMetaclassType, stmt.range());
let stmt = checker.semantic().current_statement();
let parent = checker.semantic().current_statement_parent();
let edit = fix::edits::delete_stmt(stmt, parent, checker.locator(), checker.indexer());
diagnostic.set_fix(Fix::safe_edit(edit).isolate(Checker::isolation(
checker.semantic().current_statement_parent_id(),
)));
}
| 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/pyupgrade/rules/useless_class_metaclass_type.rs | crates/ruff_linter/src/rules/pyupgrade/rules/useless_class_metaclass_type.rs | use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::{Fix, FixAvailability, Violation};
use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::StmtClassDef;
use ruff_text_size::Ranged;
/// ## What it does
/// Checks for `metaclass=type` in class definitions.
///
/// ## Why is this bad?
/// Since Python 3, the default metaclass is `type`, so specifying it explicitly is redundant.
///
/// Even though `__prepare__` is not required, the default metaclass (`type`) implements it,
/// for the convenience of subclasses calling it via `super()`.
/// ## Example
///
/// ```python
/// class Foo(metaclass=type): ...
/// ```
///
/// Use instead:
///
/// ```python
/// class Foo: ...
/// ```
///
/// ## References
/// - [PEP 3115 – Metaclasses in Python 3000](https://peps.python.org/pep-3115/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.13.0")]
pub(crate) struct UselessClassMetaclassType {
name: String,
}
impl Violation for UselessClassMetaclassType {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let UselessClassMetaclassType { name } = self;
format!("Class `{name}` uses `metaclass=type`, which is redundant")
}
fn fix_title(&self) -> Option<String> {
Some("Remove `metaclass=type`".to_string())
}
}
/// UP050
pub(crate) fn useless_class_metaclass_type(checker: &Checker, class_def: &StmtClassDef) {
let Some(arguments) = class_def.arguments.as_deref() else {
return;
};
for keyword in &arguments.keywords {
if let (Some("metaclass"), expr) = (keyword.arg.as_deref(), &keyword.value) {
if checker.semantic().match_builtin_expr(expr, "type") {
let mut diagnostic = checker.report_diagnostic(
UselessClassMetaclassType {
name: class_def.name.to_string(),
},
keyword.range(),
);
diagnostic.try_set_fix(|| {
let edit = remove_argument(
keyword,
arguments,
Parentheses::Remove,
checker.locator().contents(),
checker.tokens(),
)?;
let range = edit.range();
let applicability = if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
Ok(Fix::applicable_edit(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/pyupgrade/rules/yield_in_for_loop.rs | crates/ruff_linter/src/rules/pyupgrade/rules/yield_in_for_loop.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `for` loops that can be replaced with `yield from` expressions.
///
/// ## Why is this bad?
/// If a `for` loop only contains a `yield` statement, it can be replaced with a
/// `yield from` expression, which is more concise and idiomatic.
///
/// ## Example
/// ```python
/// def bar():
/// for x in foo:
/// yield x
///
/// global y
/// for y in foo:
/// yield y
/// ```
///
/// Use instead:
/// ```python
/// def bar():
/// yield from foo
///
/// for _element in foo:
/// y = _element
/// yield y
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as converting a `for` loop to a `yield
/// from` expression can change the behavior of the program in rare cases.
/// For example, if a generator is being sent values via `send`, then rewriting
/// to a `yield from` could lead to an attribute error if the underlying
/// generator does not implement the `send` method.
///
/// Additionally, if at least one target is `global` or `nonlocal`,
/// no fix will be offered.
///
/// In most cases, however, the fix is safe, and such a modification should have
/// no effect on the behavior of the program.
///
/// ## References
/// - [Python documentation: The `yield` statement](https://docs.python.org/3/reference/simple_stmts.html#the-yield-statement)
/// - [PEP 380 – Syntax for Delegating to a Subgenerator](https://peps.python.org/pep-0380/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.210")]
pub(crate) struct YieldInForLoop;
impl Violation for YieldInForLoop {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Replace `yield` over `for` loop with `yield from`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `yield from`".to_string())
}
}
/// UP028
pub(crate) fn yield_in_for_loop(checker: &Checker, stmt_for: &ast::StmtFor) {
// Intentionally omit async contexts.
if checker.semantic().in_async_context() {
return;
}
let ast::StmtFor {
target,
iter,
body,
orelse,
is_async: _,
range: _,
node_index: _,
} = stmt_for;
// If there is an else statement, don't rewrite.
if !orelse.is_empty() {
return;
}
// If there's any logic besides a yield, don't rewrite.
let [body] = body.as_slice() else {
return;
};
// If the body is not a yield, don't rewrite.
let Stmt::Expr(ast::StmtExpr {
value,
range: _,
node_index: _,
}) = &body
else {
return;
};
let Expr::Yield(ast::ExprYield {
value: Some(value),
range: _,
node_index: _,
}) = value.as_ref()
else {
return;
};
// If the target is not the same as the value, don't rewrite. For example, we should rewrite
// `for x in y: yield x` to `yield from y`, but not `for x in y: yield x + 1`.
if !is_same_expr(target, value) {
return;
}
// If any of the bound names are used outside of the yield itself, don't rewrite.
if collect_names(value).any(|name| {
checker
.semantic()
.current_scope()
.get_all(name.id.as_str())
// Skip unbound bindings like `del x`
.find(|&id| !checker.semantic().binding(id).is_unbound())
.is_some_and(|binding_id| {
let binding = checker.semantic().binding(binding_id);
binding.references.iter().any(|reference_id| {
checker.semantic().reference(*reference_id).range() != name.range()
})
})
}) {
return;
}
let mut diagnostic = checker.report_diagnostic(YieldInForLoop, stmt_for.range());
let contents = checker.locator().slice(
parenthesized_range(iter.as_ref().into(), stmt_for.into(), checker.tokens())
.unwrap_or(iter.range()),
);
let contents = if iter.as_tuple_expr().is_some_and(|it| !it.parenthesized) {
format!("yield from ({contents})")
} else {
format!("yield from {contents}")
};
if !collect_names(value).any(|name| {
let semantic = checker.semantic();
let mut bindings = semantic.current_scope().get_all(name.id.as_str());
bindings.any(|id| {
let binding = semantic.binding(id);
binding.is_global() || binding.is_nonlocal()
})
}) {
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
contents,
stmt_for.range(),
)));
}
}
/// Return `true` if the two expressions are equivalent, and both consistent solely
/// of tuples and names.
fn is_same_expr(left: &Expr, right: &Expr) -> bool {
match (&left, &right) {
(Expr::Name(left), Expr::Name(right)) => left.id == right.id,
(Expr::Tuple(left), Expr::Tuple(right)) => {
left.len() == right.len()
&& left
.iter()
.zip(right)
.all(|(left, right)| is_same_expr(left, right))
}
_ => false,
}
}
/// Collect all named variables in an expression consisting solely of tuples and
/// names.
fn collect_names<'a>(expr: &'a Expr) -> Box<dyn Iterator<Item = &'a ast::ExprName> + 'a> {
Box::new(
expr.as_name_expr().into_iter().chain(
expr.as_tuple_expr()
.into_iter()
.flat_map(|tuple| tuple.iter().flat_map(collect_names)),
),
)
}
| 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/pyupgrade/rules/lru_cache_with_maxsize_none.rs | crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs | use ruff_python_ast::{self as ast, Arguments, Decorator, Expr, Keyword};
use ruff_text_size::{Ranged, TextRange};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of `functools.lru_cache` that set `maxsize=None`.
///
/// ## Why is this bad?
/// Since Python 3.9, `functools.cache` can be used as a drop-in replacement
/// for `functools.lru_cache(maxsize=None)`. When possible, prefer
/// `functools.cache` as it is more readable and idiomatic.
///
/// ## Example
///
/// ```python
/// import functools
///
///
/// @functools.lru_cache(maxsize=None)
/// def foo(): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import functools
///
///
/// @functools.cache
/// def foo(): ...
/// ```
///
/// ## Options
/// - `target-version`
///
/// ## References
/// - [Python documentation: `@functools.cache`](https://docs.python.org/3/library/functools.html#functools.cache)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.225")]
pub(crate) struct LRUCacheWithMaxsizeNone;
impl AlwaysFixableViolation for LRUCacheWithMaxsizeNone {
#[derive_message_formats]
fn message(&self) -> String {
"Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)`".to_string()
}
fn fix_title(&self) -> String {
"Rewrite with `@functools.cache".to_string()
}
}
/// UP033
pub(crate) fn lru_cache_with_maxsize_none(checker: &Checker, decorator_list: &[Decorator]) {
for decorator in decorator_list {
let Expr::Call(ast::ExprCall {
func,
arguments:
Arguments {
args,
keywords,
range: _,
node_index: _,
},
range: _,
node_index: _,
}) = &decorator.expression
else {
continue;
};
// Look for, e.g., `import functools; @functools.lru_cache(maxsize=None)`.
if args.is_empty()
&& keywords.len() == 1
&& checker
.semantic()
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["functools", "lru_cache"])
})
{
let Keyword {
arg,
value,
range: _,
node_index: _,
} = &keywords[0];
if arg.as_ref().is_some_and(|arg| arg == "maxsize") && value.is_none_literal_expr() {
let mut diagnostic = checker.report_diagnostic(
LRUCacheWithMaxsizeNone,
TextRange::new(func.end(), decorator.end()),
);
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("functools", "cache"),
decorator.start(),
checker.semantic(),
)?;
let reference_edit =
Edit::range_replacement(binding, decorator.expression.range());
Ok(Fix::safe_edits(import_edit, [reference_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/pyupgrade/rules/native_literals.rs | crates/ruff_linter/src/rules/pyupgrade/rules/native_literals.rs | use std::fmt;
use std::str::FromStr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, Int, LiteralExpressionRef, OperatorPrecedence, UnaryOp};
use ruff_source_file::find_newline;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Applicability, Edit, Fix};
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum LiteralType {
Str,
Bytes,
Int,
Float,
Bool,
}
impl FromStr for LiteralType {
type Err = ();
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"str" => Ok(LiteralType::Str),
"bytes" => Ok(LiteralType::Bytes),
"int" => Ok(LiteralType::Int),
"float" => Ok(LiteralType::Float),
"bool" => Ok(LiteralType::Bool),
_ => Err(()),
}
}
}
impl LiteralType {
fn as_zero_value_expr(self, checker: &Checker) -> Expr {
match self {
LiteralType::Str => ast::StringLiteral {
value: Box::default(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
flags: checker.default_string_flags(),
}
.into(),
LiteralType::Bytes => ast::BytesLiteral {
value: Box::default(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
flags: checker.default_bytes_flags(),
}
.into(),
LiteralType::Int => ast::ExprNumberLiteral {
value: ast::Number::Int(Int::from(0u8)),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
LiteralType::Float => ast::ExprNumberLiteral {
value: ast::Number::Float(0.0),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
LiteralType::Bool => ast::ExprBooleanLiteral::default().into(),
}
}
}
impl TryFrom<LiteralExpressionRef<'_>> for LiteralType {
type Error = ();
fn try_from(literal_expr: LiteralExpressionRef<'_>) -> Result<Self, Self::Error> {
match literal_expr {
LiteralExpressionRef::StringLiteral(_) => Ok(LiteralType::Str),
LiteralExpressionRef::BytesLiteral(_) => Ok(LiteralType::Bytes),
LiteralExpressionRef::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => {
match value {
ast::Number::Int(_) => Ok(LiteralType::Int),
ast::Number::Float(_) => Ok(LiteralType::Float),
ast::Number::Complex { .. } => Err(()),
}
}
LiteralExpressionRef::BooleanLiteral(_) => Ok(LiteralType::Bool),
LiteralExpressionRef::NoneLiteral(_) | LiteralExpressionRef::EllipsisLiteral(_) => {
Err(())
}
}
}
}
impl fmt::Display for LiteralType {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
LiteralType::Str => fmt.write_str("str"),
LiteralType::Bytes => fmt.write_str("bytes"),
LiteralType::Int => fmt.write_str("int"),
LiteralType::Float => fmt.write_str("float"),
LiteralType::Bool => fmt.write_str("bool"),
}
}
}
/// ## What it does
/// Checks for unnecessary calls to `str`, `bytes`, `int`, `float`, and `bool`.
///
/// ## Why is this bad?
/// The mentioned constructors can be replaced with their respective literal
/// forms, which are more readable and idiomatic.
///
/// ## Example
/// ```python
/// str("foo")
/// ```
///
/// Use instead:
/// ```python
/// "foo"
/// ```
///
/// ## Fix safety
/// The fix is marked as unsafe if it might remove comments.
///
/// ## References
/// - [Python documentation: `str`](https://docs.python.org/3/library/stdtypes.html#str)
/// - [Python documentation: `bytes`](https://docs.python.org/3/library/stdtypes.html#bytes)
/// - [Python documentation: `int`](https://docs.python.org/3/library/functions.html#int)
/// - [Python documentation: `float`](https://docs.python.org/3/library/functions.html#float)
/// - [Python documentation: `bool`](https://docs.python.org/3/library/functions.html#bool)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.193")]
pub(crate) struct NativeLiterals {
literal_type: LiteralType,
}
impl AlwaysFixableViolation for NativeLiterals {
#[derive_message_formats]
fn message(&self) -> String {
let NativeLiterals { literal_type } = self;
format!("Unnecessary `{literal_type}` call (rewrite as a literal)")
}
fn fix_title(&self) -> String {
let NativeLiterals { literal_type } = self;
match literal_type {
LiteralType::Str => "Replace with string literal".to_string(),
LiteralType::Bytes => "Replace with bytes literal".to_string(),
LiteralType::Int => "Replace with integer literal".to_string(),
LiteralType::Float => "Replace with float literal".to_string(),
LiteralType::Bool => "Replace with boolean literal".to_string(),
}
}
}
/// UP018
pub(crate) fn native_literals(
checker: &Checker,
call: &ast::ExprCall,
parent_expr: Option<&ast::Expr>,
) {
let ast::ExprCall {
func,
arguments:
ast::Arguments {
args,
keywords,
range: _,
node_index: _,
},
range: call_range,
node_index: _,
} = call;
if !keywords.is_empty() || args.len() > 1 {
return;
}
let tokens = checker.tokens();
let semantic = checker.semantic();
let Some(builtin) = semantic.resolve_builtin_symbol(func) else {
return;
};
let Ok(literal_type) = LiteralType::from_str(builtin) else {
return;
};
// There's no way to rewrite, e.g., `f"{f'{str()}'}"` within a nested f-string.
if semantic.in_f_string() {
if semantic
.current_expressions()
.filter(|expr| expr.is_f_string_expr())
.count()
> 1
{
return;
}
}
match args.first() {
None => {
// Do not suggest fix for attribute access on an int like `int().attribute`
// Ex) `int().denominator` is valid but `0.denominator` is not
if literal_type == LiteralType::Int && matches!(parent_expr, Some(Expr::Attribute(_))) {
return;
}
let mut diagnostic =
checker.report_diagnostic(NativeLiterals { literal_type }, call.range());
let expr = literal_type.as_zero_value_expr(checker);
let content = checker.generator().expr(&expr);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
content,
call.range(),
)));
}
Some(arg) => {
let (has_unary_op, literal_expr) = if let Some(literal_expr) = arg.as_literal_expr() {
// Skip implicit concatenated strings.
if literal_expr.is_implicit_concatenated() {
return;
}
(false, literal_expr)
} else if let Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::UAdd | UnaryOp::USub,
operand,
..
}) = arg
{
if let Some(literal_expr) = operand
.as_literal_expr()
.filter(|expr| matches!(expr, LiteralExpressionRef::NumberLiteral(_)))
{
(true, literal_expr)
} else {
// Only allow unary operators for numbers.
return;
}
} else {
return;
};
let Ok(arg_literal_type) = LiteralType::try_from(literal_expr) else {
return;
};
if arg_literal_type != literal_type {
return;
}
let arg_code = checker.locator().slice(arg);
let mut needs_space = false;
// Look for the `Rpar` token of the call expression and check if there is a keyword token right
// next to it without any space separating them. Without this check, the fix for this
// rule would create a syntax error.
// Ex) `bool(True)and None` no space between `)` and the keyword `and`.
//
// Subtract 1 from the end of the range to include `Rpar` token in the slice.
if let [paren_token, next_token, ..] = tokens.after(call_range.sub_end(1.into()).end())
{
needs_space = next_token.kind().is_keyword()
&& paren_token.range().end() == next_token.range().start();
}
let mut content = match (parent_expr, literal_type, has_unary_op) {
// Expressions including newlines must be parenthesised to be valid syntax
(_, _, true) if find_newline(arg_code).is_some() => format!("({arg_code})"),
// Attribute access on an integer requires the integer to be parenthesized to disambiguate from a float
// Ex) `(7).denominator` is valid but `7.denominator` is not
// Note that floats do not have this problem
// Ex) `(1.0).real` is valid and `1.0.real` is too
(Some(Expr::Attribute(_)), LiteralType::Int, _) => format!("({arg_code})"),
(Some(parent), _, _) => {
if OperatorPrecedence::from(parent) > OperatorPrecedence::from(arg) {
format!("({arg_code})")
} else {
arg_code.to_string()
}
}
_ => arg_code.to_string(),
};
if needs_space {
content.push(' ');
}
let applicability = if checker.comment_ranges().intersects(call.range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
let edit = Edit::range_replacement(content, call.range());
let fix = Fix::applicable_edit(edit, applicability);
checker
.report_diagnostic(NativeLiterals { literal_type }, call.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/pyupgrade/rules/replace_universal_newlines.rs | crates/ruff_linter/src/rules/pyupgrade/rules/replace_universal_newlines.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of `subprocess.run` that set the `universal_newlines`
/// keyword argument.
///
/// ## Why is this bad?
/// As of Python 3.7, the `universal_newlines` keyword argument has been
/// renamed to `text`, and now exists for backwards compatibility. The
/// `universal_newlines` keyword argument may be removed in a future version of
/// Python. Prefer `text`, which is more explicit and readable.
///
/// ## Example
/// ```python
/// import subprocess
///
/// subprocess.run(["foo"], universal_newlines=True)
/// ```
///
/// Use instead:
/// ```python
/// import subprocess
///
/// subprocess.run(["foo"], text=True)
/// ```
///
/// ## References
/// - [Python 3.7 release notes](https://docs.python.org/3/whatsnew/3.7.html#subprocess)
/// - [Python documentation: `subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.196")]
pub(crate) struct ReplaceUniversalNewlines;
impl AlwaysFixableViolation for ReplaceUniversalNewlines {
#[derive_message_formats]
fn message(&self) -> String {
"`universal_newlines` is deprecated, use `text`".to_string()
}
fn fix_title(&self) -> String {
"Replace with `text` keyword argument".to_string()
}
}
/// UP021
pub(crate) fn replace_universal_newlines(checker: &Checker, call: &ast::ExprCall) {
if !checker.semantic().seen_module(Modules::SUBPROCESS) {
return;
}
if checker
.semantic()
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["subprocess", "run"]))
{
let Some(kwarg) = call.arguments.find_keyword("universal_newlines") else {
return;
};
let Some(arg) = kwarg.arg.as_ref() else {
return;
};
let mut diagnostic = checker.report_diagnostic(ReplaceUniversalNewlines, arg.range());
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
if call.arguments.find_keyword("text").is_some() {
diagnostic.try_set_fix(|| {
remove_argument(
kwarg,
&call.arguments,
Parentheses::Preserve,
checker.locator().contents(),
checker.tokens(),
)
.map(Fix::safe_edit)
});
} else {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
"text".to_string(),
arg.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/pyupgrade/rules/unnecessary_class_parentheses.rs | crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_class_parentheses.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for class definitions that include unnecessary parentheses after
/// the class name.
///
/// ## Why is this bad?
/// If a class definition doesn't have any bases, the parentheses are
/// unnecessary.
///
/// ## Example
/// ```python
/// class Foo():
/// ...
/// ```
///
/// Use instead:
/// ```python
/// class Foo:
/// ...
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.273")]
pub(crate) struct UnnecessaryClassParentheses;
impl AlwaysFixableViolation for UnnecessaryClassParentheses {
#[derive_message_formats]
fn message(&self) -> String {
"Unnecessary parentheses after class definition".to_string()
}
fn fix_title(&self) -> String {
"Remove parentheses".to_string()
}
}
/// UP039
pub(crate) fn unnecessary_class_parentheses(checker: &Checker, class_def: &ast::StmtClassDef) {
let Some(arguments) = class_def.arguments.as_deref() else {
return;
};
if !arguments.args.is_empty() || !arguments.keywords.is_empty() {
return;
}
let mut diagnostic = checker.report_diagnostic(UnnecessaryClassParentheses, arguments.range());
diagnostic.set_fix(Fix::safe_edit(Edit::deletion(
arguments.start(),
arguments.end(),
)));
}
| 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/pyupgrade/rules/use_pep585_annotation.rs | crates/ruff_linter/src/rules/pyupgrade/rules/use_pep585_annotation.rs | use ruff_python_ast::Expr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::UnqualifiedName;
use ruff_python_semantic::analyze::typing::ModuleMember;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
use ruff_python_ast::PythonVersion;
/// ## What it does
/// Checks for the use of generics that can be replaced with standard library
/// variants based on [PEP 585].
///
/// ## Why is this bad?
/// [PEP 585] enabled collections in the Python standard library (like `list`)
/// to be used as generics directly, instead of importing analogous members
/// from the `typing` module (like `typing.List`).
///
/// When available, the [PEP 585] syntax should be used instead of importing
/// members from the `typing` module, as it's more concise and readable.
/// Importing those members from `typing` is considered deprecated as of [PEP
/// 585].
///
/// This rule is enabled when targeting Python 3.9 or later (see:
/// [`target-version`]). By default, it's _also_ enabled for earlier Python
/// versions if `from __future__ import annotations` is present, as
/// `__future__` annotations are not evaluated at runtime. If your code relies
/// on runtime type annotations (either directly or via a library like
/// Pydantic), you can disable this behavior for Python versions prior to 3.9
/// by setting [`lint.pyupgrade.keep-runtime-typing`] to `true`.
///
/// ## Example
/// ```python
/// from typing import List
///
/// foo: List[int] = [1, 2, 3]
/// ```
///
/// Use instead:
/// ```python
/// foo: list[int] = [1, 2, 3]
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may lead to runtime errors when
/// alongside libraries that rely on runtime type annotations, like Pydantic,
/// on Python versions prior to Python 3.9.
///
/// ## Options
/// - `target-version`
/// - `lint.pyupgrade.keep-runtime-typing`
///
/// [PEP 585]: https://peps.python.org/pep-0585/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct NonPEP585Annotation {
from: String,
to: String,
}
impl Violation for NonPEP585Annotation {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let NonPEP585Annotation { from, to } = self;
format!("Use `{to}` instead of `{from}` for type annotation")
}
fn fix_title(&self) -> Option<String> {
let NonPEP585Annotation { to, .. } = self;
Some(format!("Replace with `{to}`"))
}
}
/// UP006
pub(crate) fn use_pep585_annotation(checker: &Checker, expr: &Expr, replacement: &ModuleMember) {
let Some(from) = UnqualifiedName::from_expr(expr) else {
return;
};
let mut diagnostic = checker.report_diagnostic(
NonPEP585Annotation {
from: from.to_string(),
to: replacement.to_string(),
},
expr.range(),
);
if !checker.semantic().in_complex_string_type_definition() {
match replacement {
ModuleMember::BuiltIn(name) => {
// Built-in type, like `list`.
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol(
name,
expr.start(),
checker.semantic(),
)?;
let binding_edit = Edit::range_replacement(binding, expr.range());
let applicability = if checker.target_version() >= PythonVersion::PY310 {
Applicability::Safe
} else {
Applicability::Unsafe
};
Ok(Fix::applicable_edits(
binding_edit,
import_edit,
applicability,
))
});
}
ModuleMember::Member(module, member) => {
// Imported type, like `collections.deque`.
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import_from(module, member),
expr.start(),
checker.semantic(),
)?;
let reference_edit = Edit::range_replacement(binding, expr.range());
Ok(Fix::applicable_edits(
import_edit,
[reference_edit],
if checker.target_version() >= PythonVersion::PY310 {
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/pyupgrade/rules/timeout_error_alias.rs | crates/ruff_linter/src/rules/pyupgrade/rules/timeout_error_alias.rs | use ruff_python_ast::{self as ast, ExceptHandler, Expr, ExprContext};
use ruff_text_size::{Ranged, TextRange};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::PythonVersion;
use ruff_python_ast::name::{Name, UnqualifiedName};
use ruff_python_semantic::SemanticModel;
use crate::checkers::ast::Checker;
use crate::fix::edits::pad;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of exceptions that alias `TimeoutError`.
///
/// ## Why is this bad?
/// `TimeoutError` is the builtin error type used for exceptions when a system
/// function timed out at the system level.
///
/// In Python 3.10, `socket.timeout` was aliased to `TimeoutError`. In Python
/// 3.11, `asyncio.TimeoutError` was aliased to `TimeoutError`.
///
/// These aliases remain in place for compatibility with older versions of
/// Python, but may be removed in future versions.
///
/// Prefer using `TimeoutError` directly, as it is more idiomatic and future-proof.
///
/// ## Example
/// ```python
/// import asyncio
///
/// raise asyncio.TimeoutError
/// ```
///
/// Use instead:
/// ```python
/// raise TimeoutError
/// ```
///
/// ## References
/// - [Python documentation: `TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.2.0")]
pub(crate) struct TimeoutErrorAlias {
name: Option<String>,
}
impl AlwaysFixableViolation for TimeoutErrorAlias {
#[derive_message_formats]
fn message(&self) -> String {
"Replace aliased errors with `TimeoutError`".to_string()
}
fn fix_title(&self) -> String {
let TimeoutErrorAlias { name } = self;
match name {
None => "Replace with builtin `TimeoutError`".to_string(),
Some(name) => format!("Replace `{name}` with builtin `TimeoutError`"),
}
}
}
/// Return `true` if an [`Expr`] is an alias of `TimeoutError`.
fn is_alias(expr: &Expr, semantic: &SemanticModel, target_version: PythonVersion) -> bool {
semantic
.resolve_qualified_name(expr)
.is_some_and(|qualified_name| {
if target_version >= PythonVersion::PY311 {
matches!(
qualified_name.segments(),
["socket", "timeout"] | ["asyncio", "TimeoutError"]
)
} else {
// N.B. This lint is only invoked for Python 3.10+. We assume
// as much here since otherwise socket.timeout would be an unsafe
// fix in Python <3.10. We add an assert to make this assumption
// explicit.
assert!(
target_version >= PythonVersion::PY310,
"lint should only be used for Python 3.10+",
);
matches!(qualified_name.segments(), ["socket", "timeout"])
}
})
}
/// Create a [`Diagnostic`] for a single target, like an [`Expr::Name`].
fn atom_diagnostic(checker: &Checker, target: &Expr) {
let mut diagnostic = checker.report_diagnostic(
TimeoutErrorAlias {
name: UnqualifiedName::from_expr(target).map(|name| name.to_string()),
},
target.range(),
);
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol(
"TimeoutError",
target.start(),
checker.semantic(),
)?;
Ok(Fix::safe_edits(
Edit::range_replacement(binding, target.range()),
import_edit,
))
});
}
/// Create a [`Diagnostic`] for a tuple of expressions.
fn tuple_diagnostic(checker: &Checker, tuple: &ast::ExprTuple, aliases: &[&Expr]) {
let mut diagnostic = checker.report_diagnostic(TimeoutErrorAlias { name: None }, tuple.range());
let semantic = checker.semantic();
if semantic.has_builtin_binding("TimeoutError") {
// Filter out any `TimeoutErrors` aliases.
let mut remaining: Vec<Expr> = tuple
.iter()
.filter_map(|element| {
if aliases.contains(&element) {
None
} else {
Some(element.clone())
}
})
.collect();
// If `TimeoutError` itself isn't already in the tuple, add it.
if tuple
.iter()
.all(|element| !semantic.match_builtin_expr(element, "TimeoutError"))
{
let node = ast::ExprName {
id: Name::new_static("TimeoutError"),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
remaining.insert(0, node.into());
}
let content = if remaining.len() == 1 {
"TimeoutError".to_string()
} else {
let node = ast::ExprTuple {
elts: remaining,
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: true,
};
format!("({})", checker.generator().expr(&node.into()))
};
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
pad(content, tuple.range(), checker.locator()),
tuple.range(),
)));
}
}
/// UP041
pub(crate) fn timeout_error_alias_handlers(checker: &Checker, handlers: &[ExceptHandler]) {
for handler in handlers {
let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { type_, .. }) = handler;
let Some(expr) = type_.as_ref() else {
continue;
};
match expr.as_ref() {
Expr::Name(_) | Expr::Attribute(_) => {
if is_alias(expr, checker.semantic(), checker.target_version()) {
atom_diagnostic(checker, expr);
}
}
Expr::Tuple(tuple) => {
// List of aliases to replace with `TimeoutError`.
let mut aliases: Vec<&Expr> = vec![];
for element in tuple {
if is_alias(element, checker.semantic(), checker.target_version()) {
aliases.push(element);
}
}
if !aliases.is_empty() {
tuple_diagnostic(checker, tuple, &aliases);
}
}
_ => {}
}
}
}
/// UP041
pub(crate) fn timeout_error_alias_call(checker: &Checker, func: &Expr) {
if is_alias(func, checker.semantic(), checker.target_version()) {
atom_diagnostic(checker, func);
}
}
/// UP041
pub(crate) fn timeout_error_alias_raise(checker: &Checker, expr: &Expr) {
if matches!(expr, Expr::Name(_) | Expr::Attribute(_)) {
if is_alias(expr, checker.semantic(), checker.target_version()) {
atom_diagnostic(checker, 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/pyupgrade/rules/os_error_alias.rs | crates/ruff_linter/src/rules/pyupgrade/rules/os_error_alias.rs | use ruff_python_ast::{self as ast, ExceptHandler, Expr, ExprContext};
use ruff_text_size::{Ranged, TextRange};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::{Name, UnqualifiedName};
use ruff_python_semantic::SemanticModel;
use crate::checkers::ast::Checker;
use crate::fix::edits::pad;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of exceptions that alias `OSError`.
///
/// ## Why is this bad?
/// `OSError` is the builtin error type used for exceptions that relate to the
/// operating system.
///
/// In Python 3.3, a variety of other exceptions, like `WindowsError` were
/// aliased to `OSError`. These aliases remain in place for compatibility with
/// older versions of Python, but may be removed in future versions.
///
/// Prefer using `OSError` directly, as it is more idiomatic and future-proof.
///
/// ## Example
/// ```python
/// raise IOError
/// ```
///
/// Use instead:
/// ```python
/// raise OSError
/// ```
///
/// ## References
/// - [Python documentation: `OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.206")]
pub(crate) struct OSErrorAlias {
name: Option<String>,
}
impl AlwaysFixableViolation for OSErrorAlias {
#[derive_message_formats]
fn message(&self) -> String {
"Replace aliased errors with `OSError`".to_string()
}
fn fix_title(&self) -> String {
let OSErrorAlias { name } = self;
match name {
None => "Replace with builtin `OSError`".to_string(),
Some(name) => format!("Replace `{name}` with builtin `OSError`"),
}
}
}
/// Return `true` if an [`Expr`] is an alias of `OSError`.
fn is_alias(expr: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(expr)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
[
"" | "builtins",
"EnvironmentError" | "IOError" | "WindowsError"
] | ["mmap" | "resource" | "select" | "socket" | "os", "error"]
)
})
}
/// Create a [`Diagnostic`] for a single target, like an [`Expr::Name`].
fn atom_diagnostic(checker: &Checker, target: &Expr) {
let mut diagnostic = checker.report_diagnostic(
OSErrorAlias {
name: UnqualifiedName::from_expr(target).map(|name| name.to_string()),
},
target.range(),
);
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol(
"OSError",
target.start(),
checker.semantic(),
)?;
Ok(Fix::safe_edits(
Edit::range_replacement(binding, target.range()),
import_edit,
))
});
}
/// Create a [`Diagnostic`] for a tuple of expressions.
fn tuple_diagnostic(checker: &Checker, tuple: &ast::ExprTuple, aliases: &[&Expr]) {
let mut diagnostic = checker.report_diagnostic(OSErrorAlias { name: None }, tuple.range());
let semantic = checker.semantic();
if semantic.has_builtin_binding("OSError") {
// Filter out any `OSErrors` aliases.
let mut remaining: Vec<Expr> = tuple
.iter()
.filter_map(|element| {
if aliases.contains(&element) {
None
} else {
Some(element.clone())
}
})
.collect();
// If `OSError` itself isn't already in the tuple, add it.
if tuple
.iter()
.all(|elem| !semantic.match_builtin_expr(elem, "OSError"))
{
let node = ast::ExprName {
id: Name::new_static("OSError"),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
remaining.insert(0, node.into());
}
let content = if remaining.len() == 1 {
"OSError".to_string()
} else {
let node = ast::ExprTuple {
elts: remaining,
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: true,
};
format!("({})", checker.generator().expr(&node.into()))
};
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
pad(content, tuple.range(), checker.locator()),
tuple.range(),
)));
}
}
/// UP024
pub(crate) fn os_error_alias_handlers(checker: &Checker, handlers: &[ExceptHandler]) {
for handler in handlers {
let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { type_, .. }) = handler;
let Some(expr) = type_.as_ref() else {
continue;
};
match expr.as_ref() {
Expr::Name(_) | Expr::Attribute(_) => {
if is_alias(expr, checker.semantic()) {
atom_diagnostic(checker, expr);
}
}
Expr::Tuple(tuple) => {
// List of aliases to replace with `OSError`.
let mut aliases: Vec<&Expr> = vec![];
for element in tuple {
if is_alias(element, checker.semantic()) {
aliases.push(element);
}
}
if !aliases.is_empty() {
tuple_diagnostic(checker, tuple, &aliases);
}
}
_ => {}
}
}
}
/// UP024
pub(crate) fn os_error_alias_call(checker: &Checker, func: &Expr) {
if is_alias(func, checker.semantic()) {
atom_diagnostic(checker, func);
}
}
/// UP024
pub(crate) fn os_error_alias_raise(checker: &Checker, expr: &Expr) {
if matches!(expr, Expr::Name(_) | Expr::Attribute(_)) {
if is_alias(expr, checker.semantic()) {
atom_diagnostic(checker, 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/pyupgrade/rules/unnecessary_future_import.rs | crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_future_import.rs | use std::collections::{BTreeSet, HashMap};
use itertools::{Itertools, chain};
use ruff_python_semantic::NodeId;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::{QualifiedName, QualifiedNameBuilder};
use ruff_python_ast::{self as ast, Alias, Stmt, StmtRef};
use ruff_python_semantic::{NameImport, Scope};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix;
use crate::{AlwaysFixableViolation, Applicability, Fix};
/// ## What it does
/// Checks for unnecessary `__future__` imports.
///
/// ## Why is this bad?
/// The `__future__` module is used to enable features that are not yet
/// available in the current Python version. If a feature is already
/// available in the minimum supported Python version, importing it
/// from `__future__` is unnecessary and should be removed to avoid
/// confusion.
///
/// ## Example
/// ```python
/// from __future__ import print_function
///
/// print("Hello, world!")
/// ```
///
/// Use instead:
/// ```python
/// print("Hello, world!")
/// ```
///
/// ## Fix safety
/// This fix is marked unsafe if applying it would delete a comment.
///
/// ## Options
/// - `target-version`
///
/// ## References
/// - [Python documentation: `__future__` — Future statement definitions](https://docs.python.org/3/library/__future__.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct UnnecessaryFutureImport {
pub names: Vec<String>,
}
impl AlwaysFixableViolation for UnnecessaryFutureImport {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryFutureImport { names } = self;
if names.len() == 1 {
let import = &names[0];
format!("Unnecessary `__future__` import `{import}` for target Python version")
} else {
let imports = names.iter().map(|name| format!("`{name}`")).join(", ");
format!("Unnecessary `__future__` imports {imports} for target Python version")
}
}
fn fix_title(&self) -> String {
"Remove unnecessary `__future__` import".to_string()
}
}
const PY33_PLUS_REMOVE_FUTURES: &[&str] = &[
"nested_scopes",
"generators",
"with_statement",
"division",
"absolute_import",
"with_statement",
"print_function",
"unicode_literals",
];
const PY37_PLUS_REMOVE_FUTURES: &[&str] = &[
"nested_scopes",
"generators",
"with_statement",
"division",
"absolute_import",
"with_statement",
"print_function",
"unicode_literals",
"generator_stop",
];
pub(crate) type RequiredImports = BTreeSet<NameImport>;
pub(crate) fn is_import_required_by_isort(
required_imports: &RequiredImports,
stmt: StmtRef,
alias: &Alias,
) -> bool {
match stmt {
StmtRef::ImportFrom(ast::StmtImportFrom {
module: Some(module),
..
}) => {
let mut builder = QualifiedNameBuilder::with_capacity(module.split('.').count() + 1);
builder.extend(module.split('.'));
builder.push(alias.name.as_str());
let qualified = builder.build();
required_imports
.iter()
.any(|required_import| required_import.qualified_name() == qualified)
}
StmtRef::ImportFrom(ast::StmtImportFrom { module: None, .. })
| StmtRef::Import(ast::StmtImport { .. }) => {
let name = alias.name.as_str();
let qualified = if name.contains('.') {
QualifiedName::from_dotted_name(name)
} else {
QualifiedName::user_defined(name)
};
required_imports
.iter()
.any(|required_import| required_import.qualified_name() == qualified)
}
_ => false,
}
}
/// UP010
pub(crate) fn unnecessary_future_import(checker: &Checker, scope: &Scope) {
let mut unused_imports: HashMap<NodeId, Vec<&Alias>> = HashMap::new();
for future_name in chain(PY33_PLUS_REMOVE_FUTURES, PY37_PLUS_REMOVE_FUTURES).unique() {
for binding_id in scope.get_all(future_name) {
let binding = checker.semantic().binding(binding_id);
if binding.kind.is_future_import() && binding.is_unused() {
let Some(node_id) = binding.source else {
continue;
};
let stmt = checker.semantic().statement(node_id);
if let Stmt::ImportFrom(ast::StmtImportFrom { names, .. }) = stmt {
let Some(alias) = names
.iter()
.find(|alias| alias.name.as_str() == binding.name(checker.source()))
else {
continue;
};
if alias.asname.is_some() {
continue;
}
if is_import_required_by_isort(
&checker.settings().isort.required_imports,
stmt.into(),
alias,
) {
continue;
}
unused_imports.entry(node_id).or_default().push(alias);
}
}
}
}
for (node_id, unused_aliases) in unused_imports {
let mut diagnostic = checker.report_diagnostic(
UnnecessaryFutureImport {
names: unused_aliases
.iter()
.map(|alias| alias.name.to_string())
.sorted()
.collect(),
},
checker.semantic().statement(node_id).range(),
);
diagnostic.try_set_fix(|| {
let statement = checker.semantic().statement(node_id);
let parent = checker.semantic().parent_statement(node_id);
let edit = fix::edits::remove_unused_imports(
unused_aliases
.iter()
.map(|alias| &alias.name)
.map(ast::Identifier::as_str),
statement,
parent,
checker.locator(),
checker.stylist(),
checker.indexer(),
)?;
let range = edit.range();
let applicability = if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
Ok(
Fix::applicable_edit(edit, applicability).isolate(Checker::isolation(
checker.semantic().current_statement_parent_id(),
)),
)
});
}
}
| 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/pyupgrade/rules/use_pep604_annotation.rs | crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_annotation.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::PythonVersion;
use ruff_python_ast::helpers::{pep_604_optional, pep_604_union};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::analyze::typing::{Pep604Operator, to_pep604_operator};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::fix::edits::pad;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Check for type annotations that can be rewritten based on [PEP 604] syntax.
///
/// ## Why is this bad?
/// [PEP 604] introduced a new syntax for union type annotations based on the
/// `|` operator. This syntax is more concise and readable than the previous
/// `typing.Union` and `typing.Optional` syntaxes.
///
/// This rule is enabled when targeting Python 3.10 or later (see:
/// [`target-version`]). By default, it's _also_ enabled for earlier Python
/// versions if `from __future__ import annotations` is present, as
/// `__future__` annotations are not evaluated at runtime. If your code relies
/// on runtime type annotations (either directly or via a library like
/// Pydantic), you can disable this behavior for Python versions prior to 3.10
/// by setting [`lint.pyupgrade.keep-runtime-typing`] to `true`.
///
/// ## Example
/// ```python
/// from typing import Union
///
/// foo: Union[int, str] = 1
/// ```
///
/// Use instead:
/// ```python
/// foo: int | str = 1
/// ```
///
/// Note that this rule only checks for usages of `typing.Union`,
/// while `UP045` checks for `typing.Optional`.
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may lead to runtime errors when
/// alongside libraries that rely on runtime type annotations, like Pydantic,
/// on Python versions prior to Python 3.10. It may also lead to runtime errors
/// in unusual and likely incorrect type annotations where the type does not
/// support the `|` operator.
///
/// ## Options
/// - `target-version`
/// - `lint.pyupgrade.keep-runtime-typing`
///
/// [PEP 604]: https://peps.python.org/pep-0604/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct NonPEP604AnnotationUnion;
impl Violation for NonPEP604AnnotationUnion {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use `X | Y` for type annotations".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Convert to `X | Y`".to_string())
}
}
/// ## What it does
/// Check for `typing.Optional` annotations that can be rewritten based on [PEP 604] syntax.
///
/// ## Why is this bad?
/// [PEP 604] introduced a new syntax for union type annotations based on the
/// `|` operator. This syntax is more concise and readable than the previous
/// `typing.Optional` syntax.
///
/// This rule is enabled when targeting Python 3.10 or later (see:
/// [`target-version`]). By default, it's _also_ enabled for earlier Python
/// versions if `from __future__ import annotations` is present, as
/// `__future__` annotations are not evaluated at runtime. If your code relies
/// on runtime type annotations (either directly or via a library like
/// Pydantic), you can disable this behavior for Python versions prior to 3.10
/// by setting [`lint.pyupgrade.keep-runtime-typing`] to `true`.
///
/// ## Example
/// ```python
/// from typing import Optional
///
/// foo: Optional[int] = None
/// ```
///
/// Use instead:
/// ```python
/// foo: int | None = None
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as it may lead to runtime errors
/// using libraries that rely on runtime type annotations, like Pydantic,
/// on Python versions prior to Python 3.10. It may also lead to runtime errors
/// in unusual and likely incorrect type annotations where the type does not
/// support the `|` operator.
///
/// ## Options
/// - `target-version`
/// - `lint.pyupgrade.keep-runtime-typing`
///
/// [PEP 604]: https://peps.python.org/pep-0604/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct NonPEP604AnnotationOptional;
impl Violation for NonPEP604AnnotationOptional {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use `X | None` for type annotations".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Convert to `X | None`".to_string())
}
}
/// UP007, UP045
pub(crate) fn non_pep604_annotation(
checker: &Checker,
expr: &Expr,
slice: &Expr,
operator: Pep604Operator,
) {
// `NamedTuple` is not a type; it's a type constructor. Using it in a type annotation doesn't
// make much sense. But since type checkers will currently (incorrectly) _not_ complain about it
// being used in a type annotation, we just ignore `Optional[typing.NamedTuple]` and
// `Union[...]` containing `NamedTuple`.
// <https://github.com/astral-sh/ruff/issues/18619>
if is_optional_named_tuple(checker, operator, slice)
|| is_union_with_named_tuple(checker, operator, slice)
{
return;
}
// Avoid fixing forward references, types not in an annotation, and expressions that would
// lead to invalid syntax.
let fixable = checker.semantic().in_type_definition()
&& !checker.semantic().in_complex_string_type_definition()
&& is_allowed_value(slice)
&& !is_optional_none(operator, slice);
let applicability = if checker.target_version() >= PythonVersion::PY310 {
Applicability::Safe
} else {
Applicability::Unsafe
};
match operator {
Pep604Operator::Optional => {
let guard =
checker.report_diagnostic_if_enabled(NonPEP604AnnotationOptional, expr.range());
let Some(mut diagnostic) = guard else {
return;
};
if fixable {
match slice {
Expr::Tuple(_) => {
// Invalid type annotation.
}
_ => {
// Unwrap all nested Optional[...] and wrap once as `X | None`.
let mut inner = slice;
while let Expr::Subscript(ast::ExprSubscript { value, slice, .. }) = inner {
if let Some(Pep604Operator::Optional) =
to_pep604_operator(value, slice, checker.semantic())
{
inner = slice;
} else {
break;
}
}
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement(
pad(
checker.generator().expr(&pep_604_optional(inner)),
expr.range(),
checker.locator(),
),
expr.range(),
),
applicability,
));
}
}
}
}
Pep604Operator::Union => {
if !checker.is_rule_enabled(Rule::NonPEP604AnnotationUnion) {
return;
}
let mut diagnostic = checker.report_diagnostic(NonPEP604AnnotationUnion, expr.range());
if fixable {
match slice {
Expr::Slice(_) => {
// Invalid type annotation.
}
Expr::Tuple(ast::ExprTuple { elts, .. }) => {
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement(
pad(
checker.generator().expr(&pep_604_union(elts)),
expr.range(),
checker.locator(),
),
expr.range(),
),
applicability,
));
}
_ => {
// Single argument.
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement(
pad(
checker.locator().slice(slice).to_string(),
expr.range(),
checker.locator(),
),
expr.range(),
),
applicability,
));
}
}
}
}
}
}
/// Returns `true` if the expression is valid for use in a bitwise union (e.g., `X | Y`). Returns
/// `false` for lambdas, yield expressions, and other expressions that are invalid in such a
/// context.
fn is_allowed_value(expr: &Expr) -> bool {
// TODO(charlie): If the expression requires parentheses when multi-line, and the annotation
// itself is not parenthesized, this should return `false`. Consider, for example:
// ```python
// x: Union[
// "Sequence["
// "int"
// "]",
// float,
// ]
// ```
// Converting this to PEP 604 syntax requires that the multiline string is parenthesized.
match expr {
Expr::BoolOp(_)
| Expr::BinOp(_)
| Expr::UnaryOp(_)
| Expr::If(_)
| Expr::Dict(_)
| Expr::Set(_)
| Expr::ListComp(_)
| Expr::SetComp(_)
| Expr::DictComp(_)
| Expr::Generator(_)
| Expr::Compare(_)
| Expr::Call(_)
| Expr::FString(_)
| Expr::TString(_)
| Expr::StringLiteral(_)
| Expr::BytesLiteral(_)
| Expr::NumberLiteral(_)
| Expr::BooleanLiteral(_)
| Expr::NoneLiteral(_)
| Expr::EllipsisLiteral(_)
| Expr::Attribute(_)
| Expr::Subscript(_)
| Expr::Name(_)
| Expr::List(_) => true,
Expr::Tuple(tuple) => tuple.iter().all(is_allowed_value),
// Maybe require parentheses.
Expr::Named(_) => false,
// Invalid in binary expressions.
Expr::Await(_)
| Expr::Lambda(_)
| Expr::Yield(_)
| Expr::YieldFrom(_)
| Expr::Starred(_)
| Expr::Slice(_)
| Expr::IpyEscapeCommand(_) => false,
}
}
/// Return `true` if this is an `Optional[typing.NamedTuple]` annotation.
fn is_optional_named_tuple(checker: &Checker, operator: Pep604Operator, slice: &Expr) -> bool {
matches!(operator, Pep604Operator::Optional) && is_named_tuple(checker, slice)
}
/// Return `true` if this is a `Union[...]` annotation containing `typing.NamedTuple`.
fn is_union_with_named_tuple(checker: &Checker, operator: Pep604Operator, slice: &Expr) -> bool {
matches!(operator, Pep604Operator::Union)
&& (is_named_tuple(checker, slice)
|| slice
.as_tuple_expr()
.is_some_and(|tuple| tuple.elts.iter().any(|elt| is_named_tuple(checker, elt))))
}
/// Return `true` if this is a `typing.NamedTuple` annotation.
fn is_named_tuple(checker: &Checker, expr: &Expr) -> bool {
checker.semantic().match_typing_expr(expr, "NamedTuple")
}
/// Return `true` if this is an `Optional[None]` annotation.
fn is_optional_none(operator: Pep604Operator, slice: &Expr) -> bool {
matches!(operator, Pep604Operator::Optional) && matches!(slice, Expr::NoneLiteral(_))
}
| 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/pyupgrade/rules/non_pep646_unpack.rs | crates/ruff_linter/src/rules/pyupgrade/rules/non_pep646_unpack.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Expr, ExprSubscript, PythonVersion};
use ruff_python_semantic::SemanticModel;
use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `Unpack[]` on Python 3.11 and above, and suggests
/// using `*` instead.
///
/// ## Why is this bad?
/// [PEP 646] introduced a new syntax for unpacking sequences based on the `*`
/// operator. This syntax is more concise and readable than the previous
/// `Unpack[]` syntax.
///
/// ## Example
/// ```python
/// from typing import Unpack
///
///
/// def foo(*args: Unpack[tuple[int, ...]]) -> None:
/// pass
/// ```
///
/// Use instead:
/// ```python
/// def foo(*args: *tuple[int, ...]) -> None:
/// pass
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as `Unpack[T]` and `*T` are considered
/// different values when introspecting types at runtime. However, in most cases,
/// the fix should be safe to apply.
///
/// ## Options
///
/// - `target-version`
///
/// [PEP 646]: https://peps.python.org/pep-0646/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.10.0")]
pub(crate) struct NonPEP646Unpack;
impl Violation for NonPEP646Unpack {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always;
#[derive_message_formats]
fn message(&self) -> String {
"Use `*` for unpacking".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Convert to `*` for unpacking".to_string())
}
}
/// UP044
pub(crate) fn use_pep646_unpack(checker: &Checker, expr: &ExprSubscript) {
if checker.target_version() < PythonVersion::PY311 {
return;
}
if !checker.semantic().seen_typing() {
return;
}
let ExprSubscript {
range,
value,
slice,
..
} = expr;
// Skip semantically invalid subscript calls (e.g. `Unpack[str | num]`).
if !(slice.is_name_expr() || slice.is_subscript_expr() || slice.is_attribute_expr()) {
return;
}
if !checker.semantic().match_typing_expr(value, "Unpack") {
return;
}
// Determine whether we're in a valid context for a star expression.
//
// Star expressions are only allowed in two places:
// - Subscript indexes (e.g., `Generic[DType, *Shape]`).
// - Variadic positional arguments (e.g., `def f(*args: *int)`).
//
// See: <https://peps.python.org/pep-0646/#grammar-changes>
if !in_subscript_index(expr, checker.semantic()) && !in_vararg(expr, checker.semantic()) {
return;
}
let mut diagnostic = checker.report_diagnostic(NonPEP646Unpack, *range);
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("*{}", checker.locator().slice(slice.as_ref())),
*range,
)));
}
/// Determine whether the [`ExprSubscript`] is in a subscript index (e.g., `Generic[Unpack[int]]`).
fn in_subscript_index(expr: &ExprSubscript, semantic: &SemanticModel) -> bool {
let parent = semantic
.current_expressions()
.skip(1)
.find_map(|expr| expr.as_subscript_expr());
let Some(parent) = parent else {
return false;
};
// E.g., `Generic[Unpack[int]]`.
if parent
.slice
.as_subscript_expr()
.is_some_and(|slice| slice == expr)
{
return true;
}
// E.g., `Generic[DType, Unpack[int]]`.
if parent.slice.as_tuple_expr().is_some_and(|slice| {
slice
.elts
.iter()
.any(|elt| elt.as_subscript_expr().is_some_and(|elt| elt == expr))
}) {
return true;
}
false
}
/// Determine whether the [`ExprSubscript`] is attached to a variadic argument in a function
/// definition (e.g., `def f(*args: Unpack[int])`).
fn in_vararg(expr: &ExprSubscript, semantic: &SemanticModel) -> bool {
let parent = semantic.current_statement().as_function_def_stmt();
let Some(parent) = parent else {
return false;
};
parent
.parameters
.vararg
.as_ref()
.and_then(|vararg| vararg.annotation())
.and_then(Expr::as_subscript_expr)
== Some(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/pyupgrade/rules/replace_str_enum.rs | crates/ruff_linter/src/rules/pyupgrade/rules/replace_str_enum.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::identifier::Identifier;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for classes that inherit from both `str` and `enum.Enum`.
///
/// ## Why is this bad?
/// Python 3.11 introduced `enum.StrEnum`, which is preferred over inheriting
/// from both `str` and `enum.Enum`.
///
/// ## Example
///
/// ```python
/// import enum
///
///
/// class Foo(str, enum.Enum): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import enum
///
///
/// class Foo(enum.StrEnum): ...
/// ```
///
/// ## Fix safety
///
/// Python 3.11 introduced a [breaking change] for enums that inherit from both
/// `str` and `enum.Enum`. Consider the following enum:
///
/// ```python
/// from enum import Enum
///
///
/// class Foo(str, Enum):
/// BAR = "bar"
/// ```
///
/// In Python 3.11, the formatted representation of `Foo.BAR` changed as
/// follows:
///
/// ```python
/// # Python 3.10
/// f"{Foo.BAR}" # > bar
/// # Python 3.11
/// f"{Foo.BAR}" # > Foo.BAR
/// ```
///
/// Migrating from `str` and `enum.Enum` to `enum.StrEnum` will restore the
/// previous behavior, such that:
///
/// ```python
/// from enum import StrEnum
///
///
/// class Foo(StrEnum):
/// BAR = "bar"
///
///
/// f"{Foo.BAR}" # > bar
/// ```
///
/// As such, migrating to `enum.StrEnum` will introduce a behavior change for
/// code that relies on the Python 3.11 behavior.
///
/// ## Options
///
/// - `target-version`
///
/// ## References
/// - [enum.StrEnum](https://docs.python.org/3/library/enum.html#enum.StrEnum)
///
/// [breaking change]: https://blog.pecar.me/python-enum
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.3.6")]
pub(crate) struct ReplaceStrEnum {
name: String,
}
impl Violation for ReplaceStrEnum {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let ReplaceStrEnum { name } = self;
format!("Class {name} inherits from both `str` and `enum.Enum`")
}
fn fix_title(&self) -> Option<String> {
Some("Inherit from `enum.StrEnum`".to_string())
}
}
/// UP042
pub(crate) fn replace_str_enum(checker: &Checker, class_def: &ast::StmtClassDef) {
let Some(arguments) = class_def.arguments.as_deref() else {
// class does not inherit anything, exit early
return;
};
// Determine whether the class inherits from both `str` and `enum.Enum`.
let mut inherits_str = false;
let mut inherits_enum = false;
for base in &*arguments.args {
if let Some(qualified_name) = checker.semantic().resolve_qualified_name(base) {
match qualified_name.segments() {
["" | "builtins", "str"] => inherits_str = true,
["enum", "Enum"] => inherits_enum = true,
_ => {}
}
}
// Short-circuit if both `str` and `enum.Enum` are found.
if inherits_str && inherits_enum {
break;
}
}
// If the class does not inherit both `str` and `enum.Enum`, exit early.
if !inherits_str || !inherits_enum {
return;
}
let mut diagnostic = checker.report_diagnostic(
ReplaceStrEnum {
name: class_def.name.to_string(),
},
class_def.identifier(),
);
// If the base classes are _exactly_ `str` and `enum.Enum`, apply a fix.
// TODO(charlie): As an alternative, we could remove both arguments, and replace one of the two
// with `StrEnum`. However, `remove_argument` can't be applied multiple times within a single
// fix; doing so leads to a syntax error.
if arguments.len() == 2 {
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("enum", "StrEnum"),
class_def.start(),
checker.semantic(),
)?;
Ok(Fix::unsafe_edits(
import_edit,
[Edit::range_replacement(
format!("({binding})"),
arguments.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/pyupgrade/rules/f_strings.rs | crates/ruff_linter/src/rules/pyupgrade/rules/f_strings.rs | use std::borrow::Cow;
use anyhow::{Context, Result};
use rustc_hash::{FxHashMap, FxHashSet};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::any_over_expr;
use ruff_python_ast::str::{leading_quote, trailing_quote};
use ruff_python_ast::token::TokenKind;
use ruff_python_ast::{self as ast, Expr, Keyword, StringFlags};
use ruff_python_literal::format::{
FieldName, FieldNamePart, FieldType, FormatPart, FormatString, FromTemplate,
};
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::rules::pyflakes::format::FormatSummary;
use crate::rules::pyupgrade::helpers::{curly_escape, curly_unescape};
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `str.format` calls that can be replaced with f-strings.
///
/// ## Why is this bad?
/// f-strings are more readable and generally preferred over `str.format`
/// calls.
///
/// ## Example
/// ```python
/// "{}".format(foo)
/// ```
///
/// Use instead:
/// ```python
/// f"{foo}"
/// ```
///
/// ## References
/// - [Python documentation: f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.224")]
pub(crate) struct FString;
impl Violation for FString {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use f-string instead of `format` call".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Convert to f-string".to_string())
}
}
/// Like [`FormatSummary`], but maps positional and keyword arguments to their
/// values. For example, given `{a} {b}".format(a=1, b=2)`, [`FormatSummary`]
/// would include `"a"` and `'b'` in `kwargs`, mapped to `1` and `2`
/// respectively.
#[derive(Debug)]
struct FormatSummaryValues<'a> {
args: Vec<&'a Expr>,
kwargs: FxHashMap<&'a str, &'a Expr>,
auto_index: usize,
}
impl<'a> FormatSummaryValues<'a> {
fn try_from_call(call: &'a ast::ExprCall, locator: &'a Locator) -> Option<Self> {
let mut extracted_args: Vec<&Expr> = Vec::new();
let mut extracted_kwargs: FxHashMap<&str, &Expr> = FxHashMap::default();
for arg in &*call.arguments.args {
if matches!(arg, Expr::Starred(..))
|| contains_quotes(locator.slice(arg))
|| locator.contains_line_break(arg.range())
{
return None;
}
extracted_args.push(arg);
}
for keyword in &*call.arguments.keywords {
let Keyword {
arg,
value,
range: _,
node_index: _,
} = keyword;
let key = arg.as_ref()?;
if contains_quotes(locator.slice(value)) || locator.contains_line_break(value.range()) {
return None;
}
extracted_kwargs.insert(key, value);
}
if extracted_args.is_empty() && extracted_kwargs.is_empty() {
return None;
}
Some(Self {
args: extracted_args,
kwargs: extracted_kwargs,
auto_index: 0,
})
}
/// Return the next positional index.
fn arg_auto(&mut self) -> usize {
let idx = self.auto_index;
self.auto_index += 1;
idx
}
/// Return the positional argument at the given index.
fn arg_positional(&self, index: usize) -> Option<&Expr> {
self.args.get(index).copied()
}
/// Return the keyword argument with the given name.
fn arg_keyword(&self, key: &str) -> Option<&Expr> {
self.kwargs.get(key).copied()
}
}
/// Return `true` if the string contains quotes.
fn contains_quotes(string: &str) -> bool {
string.contains(['\'', '"'])
}
enum FormatContext {
/// The expression is used as a bare format spec (e.g., `{x}`).
Bare,
/// The expression is used with conversion flags, or attribute or subscript access
/// (e.g., `{x!r}`, `{x.y}`, `{x[y]}`).
Accessed,
}
/// Returns `true` if the expression should be parenthesized when used in an f-string.
fn parenthesize(expr: &Expr, text: &str, context: FormatContext) -> bool {
match (context, expr) {
// E.g., `x + y` should be parenthesized in `f"{(x + y)[0]}"`.
(
FormatContext::Accessed,
Expr::BinOp(_)
| Expr::UnaryOp(_)
| Expr::BoolOp(_)
| Expr::Compare(_)
| Expr::If(_)
| Expr::Lambda(_)
| Expr::Await(_)
| Expr::Yield(_)
| Expr::YieldFrom(_)
| Expr::Starred(_),
) => true,
// E.g., `12` should be parenthesized in `f"{(12).real}"`.
(
FormatContext::Accessed,
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(..),
..
}),
) => text
.chars()
// Ignore digit separators so decimal literals like `1_2` still count as pure digits.
.filter(|c| *c != '_')
.all(|c| c.is_ascii_digit()),
// E.g., `{x, y}` should be parenthesized in `f"{(x, y)}"`.
(
_,
Expr::Generator(_)
| Expr::Dict(_)
| Expr::Named(_)
| Expr::Set(_)
| Expr::SetComp(_)
| Expr::DictComp(_),
) => true,
(_, Expr::Subscript(ast::ExprSubscript { value, .. })) => {
matches!(
value.as_ref(),
Expr::Generator(_)
| Expr::Dict(_)
| Expr::Set(_)
| Expr::SetComp(_)
| Expr::DictComp(_)
)
}
(_, Expr::Attribute(ast::ExprAttribute { value, .. })) => {
matches!(
value.as_ref(),
Expr::Generator(_)
| Expr::Dict(_)
| Expr::Set(_)
| Expr::SetComp(_)
| Expr::DictComp(_)
)
}
(_, Expr::Call(ast::ExprCall { func, .. })) => {
matches!(
func.as_ref(),
Expr::Generator(_)
| Expr::Dict(_)
| Expr::Set(_)
| Expr::SetComp(_)
| Expr::DictComp(_)
)
}
_ => false,
}
}
/// Given an [`Expr`], format it for use in a formatted expression within an f-string.
fn formatted_expr<'a>(expr: &Expr, context: FormatContext, locator: &Locator<'a>) -> Cow<'a, str> {
let text = locator.slice(expr);
if parenthesize(expr, text, context) && !(text.starts_with('(') && text.ends_with(')')) {
Cow::Owned(format!("({text})"))
} else {
Cow::Borrowed(text)
}
}
#[derive(Debug, Clone)]
enum FStringConversion {
/// The format string only contains literal parts and is empty.
EmptyLiteral,
/// The format string only contains literal parts and is non-empty.
NonEmptyLiteral,
/// The format call uses arguments with side effects which are repeated within the
/// format string. For example: `"{x} {x}".format(x=foo())`.
SideEffects,
/// The format string should be converted to an f-string.
Convert(String),
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
enum IndexOrKeyword {
/// The field uses a positional index.
Index(usize),
/// The field uses a keyword name.
Keyword(String),
}
impl FStringConversion {
/// Convert a string `.format` call to an f-string.
fn try_convert(
range: TextRange,
summary: &mut FormatSummaryValues,
locator: &Locator,
) -> Result<Self> {
let contents = locator.slice(range);
// Strip the unicode prefix. It's redundant in Python 3, and invalid when used
// with f-strings.
let contents = if contents.starts_with('U') || contents.starts_with('u') {
&contents[1..]
} else {
contents
};
// Temporarily strip the raw prefix, if present. It will be prepended to the result, before the
// 'f', to match the prefix order both the Ruff formatter (and Black) use when formatting code.
let raw = contents.starts_with('R') || contents.starts_with('r');
let contents = if raw { &contents[1..] } else { contents };
// Remove the leading and trailing quotes.
let leading_quote = leading_quote(contents).context("Unable to identify leading quote")?;
let trailing_quote =
trailing_quote(contents).context("Unable to identify trailing quote")?;
let contents = &contents[leading_quote.len()..contents.len() - trailing_quote.len()];
// If the format string is empty, it doesn't need to be converted.
if contents.is_empty() {
return Ok(Self::EmptyLiteral);
}
// Parse the format string.
let format_string = FormatString::from_str(contents)?;
// If the format string contains only literal parts, it doesn't need to be converted.
if format_string
.format_parts
.iter()
.all(|part| matches!(part, FormatPart::Literal(..)))
{
return Ok(Self::NonEmptyLiteral);
}
let mut converted = String::with_capacity(contents.len());
let mut seen = FxHashSet::default();
for part in format_string.format_parts {
match part {
FormatPart::Field {
field_name,
conversion_spec,
format_spec,
} => {
converted.push('{');
let field = FieldName::parse(&field_name)?;
// Map from field type to specifier.
let specifier = match field.field_type {
FieldType::Auto => IndexOrKeyword::Index(summary.arg_auto()),
FieldType::Index(index) => IndexOrKeyword::Index(index),
FieldType::Keyword(name) => IndexOrKeyword::Keyword(name),
};
let arg = match &specifier {
IndexOrKeyword::Index(index) => {
summary.arg_positional(*index).ok_or_else(|| {
anyhow::anyhow!("Positional argument {index} is missing")
})?
}
IndexOrKeyword::Keyword(name) => {
summary.arg_keyword(name).ok_or_else(|| {
anyhow::anyhow!("Keyword argument '{name}' is missing")
})?
}
};
// If the argument contains a side effect, and it's repeated in the format
// string, we can't convert the format string to an f-string. For example,
// converting `"{x} {x}".format(x=foo())` would result in `f"{foo()} {foo()}"`,
// which would call `foo()` twice.
if !seen.insert(specifier) {
if any_over_expr(arg, &Expr::is_call_expr) {
return Ok(Self::SideEffects);
}
}
converted.push_str(&formatted_expr(
arg,
if field.parts.is_empty() {
FormatContext::Bare
} else {
FormatContext::Accessed
},
locator,
));
for part in field.parts {
match part {
FieldNamePart::Attribute(name) => {
converted.push('.');
converted.push_str(&name);
}
FieldNamePart::Index(index) => {
converted.push('[');
converted.push_str(index.to_string().as_str());
converted.push(']');
}
FieldNamePart::StringIndex(index) => {
let quote = match trailing_quote {
"'" | "'''" | "\"\"\"" => '"',
"\"" => '\'',
_ => unreachable!("invalid trailing quote"),
};
converted.push('[');
converted.push(quote);
converted.push_str(&index);
converted.push(quote);
converted.push(']');
}
}
}
if let Some(conversion_spec) = conversion_spec {
converted.push('!');
converted.push(conversion_spec);
}
if !format_spec.is_empty() {
converted.push(':');
converted.push_str(&format_spec);
}
converted.push('}');
}
FormatPart::Literal(value) => {
converted.push_str(&curly_escape(&value));
}
}
}
// Construct the format string.
let mut contents = String::with_capacity(usize::from(raw) + 1 + converted.len());
if raw {
contents.push('r');
}
contents.push('f');
contents.push_str(leading_quote);
contents.push_str(&converted);
contents.push_str(trailing_quote);
Ok(Self::Convert(contents))
}
}
/// UP032
pub(crate) fn f_strings(checker: &Checker, call: &ast::ExprCall, summary: &FormatSummary) {
if summary.has_nested_parts {
return;
}
let Expr::Attribute(ast::ExprAttribute { value, .. }) = call.func.as_ref() else {
return;
};
let Expr::StringLiteral(literal) = &**value else {
return;
};
let Some(mut summary) = FormatSummaryValues::try_from_call(call, checker.locator()) else {
return;
};
let mut patches: Vec<(TextRange, FStringConversion)> = vec![];
let mut tokens = checker.tokens().in_range(call.func.range()).iter();
let end = loop {
let Some(token) = tokens.next() else {
unreachable!("Should break from the `Tok::Dot` arm");
};
match token.kind() {
TokenKind::Dot => {
// ```
// (
// "a"
// " {} "
// "b"
// ).format(x)
// ```
// ^ Get the position of the character before the dot.
//
// We know that the expression is a string literal, so we can safely assume that the
// dot is the start of an attribute access.
break token.start();
}
TokenKind::String if !token.unwrap_string_flags().is_unclosed() => {
match FStringConversion::try_convert(token.range(), &mut summary, checker.locator())
{
// If the format string contains side effects that would need to be repeated,
// we can't convert it to an f-string.
Ok(FStringConversion::SideEffects) => return,
// If any of the segments fail to convert, then we can't convert the entire
// expression.
Err(_) => return,
// Otherwise, push the conversion to be processed later.
Ok(conversion) => patches.push((token.range(), conversion)),
}
}
_ => {}
}
};
if patches.is_empty() {
return;
}
let mut contents = String::with_capacity(checker.locator().slice(call).len());
let mut prev_end = call.start();
for (range, conversion) in patches {
let fstring = match conversion {
FStringConversion::Convert(fstring) => Some(fstring),
FStringConversion::EmptyLiteral => None,
FStringConversion::NonEmptyLiteral => {
// Convert escaped curly brackets e.g. `{{` to `{` in literal string parts
Some(curly_unescape(checker.locator().slice(range)).to_string())
}
// We handled this in the previous loop.
FStringConversion::SideEffects => unreachable!(),
};
if let Some(fstring) = fstring {
contents.push_str(
checker
.locator()
.slice(TextRange::new(prev_end, range.start())),
);
contents.push_str(&fstring);
}
prev_end = range.end();
}
contents.push_str(checker.locator().slice(TextRange::new(prev_end, end)));
// If necessary, add a space between any leading keyword (`return`, `yield`, `assert`, etc.)
// and the string. For example, `return"foo"` is valid, but `returnf"foo"` is not.
let existing = checker.locator().slice(TextRange::up_to(call.start()));
if existing
.chars()
.last()
.is_some_and(|char| char.is_ascii_alphabetic())
{
contents.insert(0, ' ');
}
// Finally, avoid refactors that would introduce a runtime error.
// For example, Django's `gettext` supports `format`-style arguments, but not f-strings.
// See: https://docs.djangoproject.com/en/4.2/topics/i18n/translation
if checker.semantic().current_expressions().any(|expr| {
expr.as_call_expr().is_some_and(|call| {
checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["django", "utils", "translation", "gettext" | "gettext_lazy"]
)
})
})
}) {
return;
}
let mut diagnostic = checker.report_diagnostic(FString, call.range());
// Avoid fix if there are comments within the call:
// ```
// "{}".format(
// 0, # 0
// )
// ```
let has_comments = checker.comment_ranges().intersects(call.arguments.range());
if !has_comments {
if contents.is_empty() {
// Ex) `''.format(self.project)`
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
checker.locator().slice(literal).to_string(),
call.range(),
)));
} else {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
contents,
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/pyupgrade/rules/open_alias.rs | crates/ruff_linter/src/rules/pyupgrade/rules/open_alias.rs | use ruff_python_ast::Expr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `io.open`.
///
/// ## Why is this bad?
/// In Python 3, `io.open` is an alias for `open`. Prefer using `open` directly,
/// as it is more idiomatic.
///
/// ## Example
/// ```python
/// import io
///
/// with io.open("file.txt") as f:
/// ...
/// ```
///
/// Use instead:
/// ```python
/// with open("file.txt") as f:
/// ...
/// ```
///
/// ## References
/// - [Python documentation: `io.open`](https://docs.python.org/3/library/io.html#io.open)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.196")]
pub(crate) struct OpenAlias;
impl Violation for OpenAlias {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use builtin `open`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with builtin `open`".to_string())
}
}
/// UP020
pub(crate) fn open_alias(checker: &Checker, expr: &Expr, func: &Expr) {
if checker
.semantic()
.resolve_qualified_name(func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["io", "open"]))
{
let mut diagnostic = checker.report_diagnostic(OpenAlias, expr.range());
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol(
"open",
expr.start(),
checker.semantic(),
)?;
Ok(Fix::safe_edits(
Edit::range_replacement(binding, func.range()),
import_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/pyupgrade/rules/typing_text_str_alias.rs | crates/ruff_linter/src/rules/pyupgrade/rules/typing_text_str_alias.rs | use ruff_python_ast::Expr;
use std::fmt::{Display, Formatter};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::preview::is_typing_extensions_str_alias_enabled;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `typing.Text`.
///
/// In preview mode, also checks for `typing_extensions.Text`.
///
/// ## Why is this bad?
/// `typing.Text` is an alias for `str`, and only exists for Python 2
/// compatibility. As of Python 3.11, `typing.Text` is deprecated. Use `str`
/// instead.
///
/// ## Example
/// ```python
/// from typing import Text
///
/// foo: Text = "bar"
/// ```
///
/// Use instead:
/// ```python
/// foo: str = "bar"
/// ```
///
/// ## References
/// - [Python documentation: `typing.Text`](https://docs.python.org/3/library/typing.html#typing.Text)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.195")]
pub(crate) struct TypingTextStrAlias {
module: TypingModule,
}
impl Violation for TypingTextStrAlias {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!("`{}.Text` is deprecated, use `str`", self.module)
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `str`".to_string())
}
}
/// UP019
pub(crate) fn typing_text_str_alias(checker: &Checker, expr: &Expr) {
if !checker
.semantic()
.seen_module(Modules::TYPING | Modules::TYPING_EXTENSIONS)
{
return;
}
if let Some(qualified_name) = checker.semantic().resolve_qualified_name(expr) {
let segments = qualified_name.segments();
let module = match segments {
["typing", "Text"] => TypingModule::Typing,
["typing_extensions", "Text"]
if is_typing_extensions_str_alias_enabled(checker.settings()) =>
{
TypingModule::TypingExtensions
}
_ => return,
};
let mut diagnostic = checker.report_diagnostic(TypingTextStrAlias { module }, expr.range());
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol(
"str",
expr.start(),
checker.semantic(),
)?;
Ok(Fix::safe_edits(
Edit::range_replacement(binding, expr.range()),
import_edit,
))
});
}
}
#[derive(Copy, Clone, Debug)]
enum TypingModule {
Typing,
TypingExtensions,
}
impl Display for TypingModule {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
TypingModule::Typing => f.write_str("typing"),
TypingModule::TypingExtensions => f.write_str("typing_extensions"),
}
}
}
| 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/pyupgrade/rules/unpacked_list_comprehension.rs | crates/ruff_linter/src/rules/pyupgrade/rules/unpacked_list_comprehension.rs | use ruff_macros::ViolationMetadata;
use crate::Violation;
/// ## Removed
/// There's no [evidence](https://github.com/astral-sh/ruff/issues/12754) that generators are
/// meaningfully faster than list comprehensions when combined with unpacking.
///
/// ## What it does
/// Checks for list comprehensions that are immediately unpacked.
///
/// ## Why is this bad?
/// There is no reason to use a list comprehension if the result is immediately
/// unpacked. Instead, use a generator expression, which avoids allocating
/// an intermediary list.
///
/// ## Example
/// ```python
/// a, b, c = [foo(x) for x in items]
/// ```
///
/// Use instead:
/// ```python
/// a, b, c = (foo(x) for x in items)
/// ```
///
/// ## References
/// - [Python documentation: Generator expressions](https://docs.python.org/3/reference/expressions.html#generator-expressions)
/// - [Python documentation: List comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)
#[derive(ViolationMetadata)]
#[violation_metadata(removed_since = "0.8.0")]
pub(crate) struct UnpackedListComprehension;
impl Violation for UnpackedListComprehension {
fn message(&self) -> String {
unreachable!("UP027 has been removed")
}
fn message_formats() -> &'static [&'static str] {
&["Replace unpacked list comprehension with a generator expression"]
}
}
| 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/pyupgrade/rules/printf_string_formatting.rs | crates/ruff_linter/src/rules/pyupgrade/rules/printf_string_formatting.rs | use std::borrow::Cow;
use std::fmt::Write;
use std::str::FromStr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::TokenKind;
use ruff_python_ast::{self as ast, AnyStringFlags, Expr, StringFlags, whitespace::indentation};
use ruff_python_codegen::Stylist;
use ruff_python_literal::cformat::{
CConversionFlags, CFormatPart, CFormatPrecision, CFormatQuantity, CFormatString,
};
use ruff_python_stdlib::identifiers::is_identifier;
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::rules::pyupgrade::helpers::curly_escape;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `printf`-style string formatting, and offers to replace it with
/// `str.format` calls.
///
/// ## Why is this bad?
/// `printf`-style string formatting has a number of quirks, and leads to less
/// readable code than using `str.format` calls or f-strings. In general, prefer
/// the newer `str.format` and f-strings constructs over `printf`-style string
/// formatting.
///
/// ## Example
///
/// ```python
/// "%s, %s" % ("Hello", "World") # "Hello, World"
/// ```
///
/// Use instead:
///
/// ```python
/// "{}, {}".format("Hello", "World") # "Hello, World"
/// ```
///
/// ```python
/// f"{'Hello'}, {'World'}" # "Hello, World"
/// ```
///
/// ## Fix safety
///
/// In cases where the format string contains a single generic format specifier
/// (e.g. `%s`), and the right-hand side is an ambiguous expression,
/// we cannot offer a safe fix.
///
/// For example, given:
///
/// ```python
/// "%s" % val
/// ```
///
/// `val` could be a single-element tuple, _or_ a single value (not
/// contained in a tuple). Both of these would resolve to the same
/// formatted string when using `printf`-style formatting, but
/// resolve differently when using f-strings:
///
/// ```python
/// val = 1
/// print("%s" % val) # "1"
/// print("{}".format(val)) # "1"
///
/// val = (1,)
/// print("%s" % val) # "1"
/// print("{}".format(val)) # "(1,)"
/// ```
///
/// ## References
/// - [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#old-string-formatting)
/// - [Python documentation: `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.229")]
pub(crate) struct PrintfStringFormatting;
impl Violation for PrintfStringFormatting {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use format specifiers instead of percent format".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with format specifiers".to_string())
}
}
fn simplify_conversion_flag(flags: CConversionFlags) -> String {
let mut flag_string = String::new();
if flags.intersects(CConversionFlags::LEFT_ADJUST) {
flag_string.push('<');
}
if flags.intersects(CConversionFlags::SIGN_CHAR) {
flag_string.push('+');
}
if flags.intersects(CConversionFlags::ALTERNATE_FORM) {
flag_string.push('#');
}
if flags.intersects(CConversionFlags::BLANK_SIGN) {
if !flags.intersects(CConversionFlags::SIGN_CHAR) {
flag_string.push(' ');
}
}
if flags.intersects(CConversionFlags::ZERO_PAD) {
if !flags.intersects(CConversionFlags::LEFT_ADJUST) {
flag_string.push('0');
}
}
flag_string
}
/// Convert a [`PercentFormat`] struct into a `String`.
fn handle_part(part: &CFormatPart<String>) -> Cow<'_, str> {
match part {
CFormatPart::Literal(item) => curly_escape(item),
CFormatPart::Spec(spec) => {
let mut format_string = String::new();
// TODO(charlie): What case is this?
if spec.format_char == '%' {
format_string.push('%');
return Cow::Owned(format_string);
}
format_string.push('{');
// Ex) `{foo}`
if let Some(key_item) = &spec.mapping_key {
format_string.push_str(key_item);
}
if !spec.flags.is_empty()
|| spec.min_field_width.is_some()
|| spec.precision.is_some()
|| (spec.format_char != 's' && spec.format_char != 'r' && spec.format_char != 'a')
{
format_string.push(':');
if !spec.flags.is_empty() {
format_string.push_str(&simplify_conversion_flag(spec.flags));
}
if let Some(width) = &spec.min_field_width {
let amount = match width {
CFormatQuantity::Amount(amount) => amount,
CFormatQuantity::FromValuesTuple => {
unreachable!("FromValuesTuple is unsupported")
}
};
format_string.push_str(&amount.to_string());
}
if let Some(precision) = &spec.precision {
match precision {
CFormatPrecision::Quantity(quantity) => match quantity {
CFormatQuantity::Amount(amount) => {
// Integer-only presentation types.
//
// See: https://docs.python.org/3/library/string.html#format-specification-mini-language
if matches!(
spec.format_char,
'b' | 'c' | 'd' | 'o' | 'x' | 'X' | 'n'
) {
format_string.push('0');
format_string.push_str(&amount.to_string());
} else {
format_string.push('.');
format_string.push_str(&amount.to_string());
}
}
CFormatQuantity::FromValuesTuple => {
unreachable!("Width should be a usize")
}
},
CFormatPrecision::Dot => {
format_string.push('.');
format_string.push('0');
}
}
}
}
if spec.format_char != 's' && spec.format_char != 'r' && spec.format_char != 'a' {
format_string.push(spec.format_char);
}
if spec.format_char == 'r' || spec.format_char == 'a' {
format_string.push('!');
format_string.push(spec.format_char);
}
format_string.push('}');
Cow::Owned(format_string)
}
}
}
/// Convert a [`CFormatString`] into a `String`.
fn percent_to_format(format_string: &CFormatString) -> String {
format_string
.iter()
.map(|(_, part)| handle_part(part))
.collect()
}
/// If a tuple has one argument, remove the comma; otherwise, return it as-is.
fn clean_params_tuple<'a>(right: &Expr, locator: &Locator<'a>) -> Cow<'a, str> {
if let Expr::Tuple(tuple) = &right {
if tuple.len() == 1 {
if !locator.contains_line_break(right.range()) {
let mut contents = locator.slice(right).to_string();
for (i, character) in contents.chars().rev().enumerate() {
if character == ',' {
let correct_index = contents.len() - i - 1;
contents.remove(correct_index);
break;
}
}
return Cow::Owned(contents);
}
}
}
Cow::Borrowed(locator.slice(right))
}
/// Converts a dictionary to a function call while preserving as much styling as
/// possible.
fn clean_params_dictionary(right: &Expr, locator: &Locator, stylist: &Stylist) -> Option<String> {
let is_multi_line = locator.contains_line_break(right.range());
let mut contents = String::new();
if let Expr::Dict(ast::ExprDict {
items,
range: _,
node_index: _,
}) = &right
{
let mut arguments: Vec<String> = vec![];
let mut seen: Vec<&str> = vec![];
let mut indent = None;
for ast::DictItem { key, value } in items {
if let Some(key) = key {
if let Expr::StringLiteral(ast::ExprStringLiteral {
value: key_string, ..
}) = key
{
// If the dictionary key is not a valid variable name, abort.
if !is_identifier(key_string.to_str()) {
return None;
}
// If there are multiple entries of the same key, abort.
if seen.contains(&key_string.to_str()) {
return None;
}
seen.push(key_string.to_str());
if is_multi_line {
if indent.is_none() {
indent = indentation(locator.contents(), key);
}
}
let value_string = locator.slice(value);
arguments.push(format!("{key_string}={value_string}"));
} else {
// If there are any non-string keys, abort.
return None;
}
} else {
let value_string = locator.slice(value);
arguments.push(format!("**{value_string}"));
}
}
// If we couldn't parse out key values, abort.
if arguments.is_empty() {
return None;
}
contents.push('(');
if is_multi_line {
let indent = indent?;
for item in &arguments {
contents.push_str(stylist.line_ending().as_str());
contents.push_str(indent);
contents.push_str(item);
contents.push(',');
}
contents.push_str(stylist.line_ending().as_str());
// For the ending parentheses, go back one indent.
let default_indent: &str = stylist.indentation();
if let Some(ident) = indent.strip_prefix(default_indent) {
contents.push_str(ident);
} else {
contents.push_str(indent);
}
} else {
contents.push_str(&arguments.join(", "));
}
contents.push(')');
}
Some(contents)
}
/// Returns `true` if the sequence of [`PercentFormatPart`] indicate that an
/// [`Expr`] can be converted.
fn convertible(format_string: &CFormatString, params: &Expr) -> bool {
for (.., format_part) in format_string.iter() {
let CFormatPart::Spec(fmt) = format_part else {
continue;
};
// These require out-of-order parameter consumption.
if matches!(fmt.min_field_width, Some(CFormatQuantity::FromValuesTuple)) {
return false;
}
if matches!(
fmt.precision,
Some(CFormatPrecision::Quantity(CFormatQuantity::FromValuesTuple))
) {
return false;
}
// These conversions require modification of parameters.
if fmt.format_char == 'd'
|| fmt.format_char == 'i'
|| fmt.format_char == 'u'
|| fmt.format_char == 'c'
{
return false;
}
// No equivalent in format.
if fmt.mapping_key.as_ref().is_some_and(String::is_empty) {
return false;
}
let is_nontrivial =
!fmt.flags.is_empty() || fmt.min_field_width.is_some() || fmt.precision.is_some();
// Conversion is subject to modifiers.
if is_nontrivial && fmt.format_char == '%' {
return false;
}
// No equivalent in `format`.
if is_nontrivial && (fmt.format_char == 'a' || fmt.format_char == 'r') {
return false;
}
// "%s" with None and width is not supported.
if fmt.min_field_width.is_some() && fmt.format_char == 's' {
return false;
}
// All dict substitutions must be named.
if let Expr::Dict(_) = ¶ms {
if fmt.mapping_key.is_none() {
return false;
}
}
}
true
}
/// UP031
pub(crate) fn printf_string_formatting(
checker: &Checker,
bin_op: &ast::ExprBinOp,
string_expr: &ast::ExprStringLiteral,
) {
let right = &*bin_op.right;
let mut num_positional_arguments = 0;
let mut num_keyword_arguments = 0;
let mut format_strings: Vec<(TextRange, String)> =
Vec::with_capacity(string_expr.value.as_slice().len());
// Parse each string segment.
for string_literal in &string_expr.value {
let string = checker.locator().slice(string_literal);
let flags = AnyStringFlags::from(string_literal.flags);
let string = &string
[usize::from(flags.opener_len())..(string.len() - usize::from(flags.closer_len()))];
// Parse the format string (e.g. `"%s"`) into a list of `PercentFormat`.
let Ok(format_string) = CFormatString::from_str(string) else {
return;
};
if !convertible(&format_string, right) {
checker.report_diagnostic(PrintfStringFormatting, string_expr.range());
return;
}
// Count the number of positional and keyword arguments.
for (.., format_part) in format_string.iter() {
let CFormatPart::Spec(fmt) = format_part else {
continue;
};
if fmt.mapping_key.is_none() {
num_positional_arguments += 1;
} else {
num_keyword_arguments += 1;
}
}
// Convert the `%`-format string to a `.format` string.
format_strings.push((
string_literal.range(),
flags
.display_contents(&percent_to_format(&format_string))
.to_string(),
));
}
// Parse the parameters.
let params_string = match right {
Expr::StringLiteral(_)
| Expr::BytesLiteral(_)
| Expr::NumberLiteral(_)
| Expr::BooleanLiteral(_)
| Expr::NoneLiteral(_)
| Expr::EllipsisLiteral(_)
| Expr::FString(_) => Cow::Owned(format!("({})", checker.locator().slice(right))),
Expr::Name(_) | Expr::Attribute(_) | Expr::Subscript(_) | Expr::Call(_) => {
if num_keyword_arguments > 0 {
// If we have _any_ named fields, assume the right-hand side is a mapping.
Cow::Owned(format!("(**{})", checker.locator().slice(right)))
} else if num_positional_arguments > 1 {
// If we have multiple fields, but no named fields, assume the right-hand side is a
// tuple.
Cow::Owned(format!("(*{})", checker.locator().slice(right)))
} else {
// Otherwise, if we have a single field, we can't make any assumptions about the
// right-hand side. It _could_ be a tuple, but it could also be a single value,
// and we can't differentiate between them.
// For example:
// ```python
// x = (1,)
// print("%s" % x)
// print("{}".format(x))
// ```
// So we offer an unsafe fix:
Cow::Owned(format!("({})", checker.locator().slice(right)))
}
}
Expr::Tuple(_) => clean_params_tuple(right, checker.locator()),
Expr::Dict(_) => {
let Some(params_string) =
clean_params_dictionary(right, checker.locator(), checker.stylist())
else {
checker.report_diagnostic(PrintfStringFormatting, string_expr.range());
return;
};
Cow::Owned(params_string)
}
_ => return,
};
// Reconstruct the string.
let mut contents = String::new();
let mut prev_end = None;
for (range, format_string) in format_strings {
// Add the content before the string segment.
match prev_end {
None => {
contents.push_str(
checker
.locator()
.slice(TextRange::new(bin_op.start(), range.start())),
);
}
Some(prev_end) => {
contents.push_str(
checker
.locator()
.slice(TextRange::new(prev_end, range.start())),
);
}
}
// Add the string itself.
contents.push_str(&format_string);
prev_end = Some(range.end());
}
if let Some(prev_end) = prev_end {
for token in checker.tokens().after(prev_end) {
match token.kind() {
// If we hit a right paren, we have to preserve it.
TokenKind::Rpar => {
contents.push_str(
checker
.locator()
.slice(TextRange::new(prev_end, token.end())),
);
}
// Break as soon as we find the modulo symbol.
TokenKind::Percent => break,
_ => {}
}
}
}
// Add the `.format` call.
let _ = write!(&mut contents, ".format{params_string}");
let mut diagnostic = checker.report_diagnostic(PrintfStringFormatting, bin_op.range());
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
contents,
bin_op.range(),
)));
}
#[cfg(test)]
mod tests {
use test_case::test_case;
use super::*;
#[test_case("\"%s\"", "\"{}\""; "simple string")]
#[test_case("\"%%%s\"", "\"%{}\""; "three percents")]
#[test_case("\"%(foo)s\"", "\"{foo}\""; "word in string")]
#[test_case("\"%2f\"", "\"{:2f}\""; "formatting in string")]
#[test_case("\"%r\"", "\"{!r}\""; "format an r")]
#[test_case("\"%a\"", "\"{!a}\""; "format an a")]
fn test_percent_to_format(sample: &str, expected: &str) {
let format_string = CFormatString::from_str(sample).unwrap();
let actual = percent_to_format(&format_string);
assert_eq!(actual, expected);
}
#[test]
fn preserve_blanks() {
assert_eq!(
simplify_conversion_flag(CConversionFlags::empty()),
String::new()
);
}
#[test]
fn preserve_space() {
assert_eq!(
simplify_conversion_flag(CConversionFlags::BLANK_SIGN),
" ".to_string()
);
}
#[test]
fn complex_format() {
assert_eq!(
simplify_conversion_flag(CConversionFlags::all()),
"<+#".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/pyupgrade/rules/redundant_open_modes.rs | crates/ruff_linter/src/rules/pyupgrade/rules/redundant_open_modes.rs | use anyhow::Result;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::{TokenKind, Tokens};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_stdlib::open_mode::OpenMode;
use ruff_text_size::{Ranged, TextSize};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for redundant `open` mode arguments.
///
/// ## Why is this bad?
/// Redundant `open` mode arguments are unnecessary and should be removed to
/// avoid confusion.
///
/// ## Example
/// ```python
/// with open("foo.txt", "r") as f:
/// ...
/// ```
///
/// Use instead:
/// ```python
/// with open("foo.txt") as f:
/// ...
/// ```
///
/// ## References
/// - [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct RedundantOpenModes {
replacement: String,
}
impl AlwaysFixableViolation for RedundantOpenModes {
#[derive_message_formats]
fn message(&self) -> String {
let RedundantOpenModes { replacement } = self;
if replacement.is_empty() {
"Unnecessary mode argument".to_string()
} else {
format!("Unnecessary modes, use `{replacement}`")
}
}
fn fix_title(&self) -> String {
let RedundantOpenModes { replacement } = self;
if replacement.is_empty() {
"Remove mode argument".to_string()
} else {
format!("Replace with `{replacement}`")
}
}
}
/// UP015
pub(crate) fn redundant_open_modes(checker: &Checker, call: &ast::ExprCall) {
if !checker
.semantic()
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["" | "builtins" | "aiofiles", "open"]
)
})
{
return;
}
let Some(mode_arg) = call.arguments.find_argument_value("mode", 1) else {
return;
};
let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &mode_arg else {
return;
};
let Ok(mode) = OpenMode::from_chars(value.chars()) else {
return;
};
let reduced = mode.reduce();
if reduced != mode {
create_diagnostic(call, mode_arg, reduced, checker);
}
}
fn create_diagnostic(call: &ast::ExprCall, mode_arg: &Expr, mode: OpenMode, checker: &Checker) {
let mut diagnostic = checker.report_diagnostic(
RedundantOpenModes {
replacement: mode.to_string(),
},
mode_arg.range(),
);
if mode.is_empty() {
diagnostic.try_set_fix(|| {
create_remove_argument_fix(call, mode_arg, checker.tokens()).map(Fix::safe_edit)
});
} else {
let stylist = checker.stylist();
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
format!("{}{mode}{}", stylist.quote(), stylist.quote()),
mode_arg.range(),
)));
}
}
fn create_remove_argument_fix(
call: &ast::ExprCall,
mode_arg: &Expr,
tokens: &Tokens,
) -> Result<Edit> {
// Find the last comma before mode_arg and create a deletion fix
// starting from the comma and ending after mode_arg.
let mut fix_start: Option<TextSize> = None;
let mut fix_end: Option<TextSize> = None;
let mut is_first_arg: bool = false;
let mut delete_first_arg: bool = false;
for token in tokens.in_range(call.range()) {
if token.start() == mode_arg.start() {
if is_first_arg {
delete_first_arg = true;
continue;
}
fix_end = Some(token.end());
break;
}
match token.kind() {
TokenKind::Name if delete_first_arg => {
fix_end = Some(token.start());
break;
}
TokenKind::Lpar => {
is_first_arg = true;
fix_start = Some(token.end());
}
TokenKind::Comma => {
is_first_arg = false;
if !delete_first_arg {
fix_start = Some(token.start());
}
}
_ => {}
}
}
match (fix_start, fix_end) {
(Some(start), Some(end)) => Ok(Edit::deletion(start, end)),
_ => Err(anyhow::anyhow!(
"Failed to locate start and end parentheses"
)),
}
}
| 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/pyupgrade/rules/mod.rs | crates/ruff_linter/src/rules/pyupgrade/rules/mod.rs | pub(crate) use convert_named_tuple_functional_to_class::*;
pub(crate) use convert_typed_dict_functional_to_class::*;
pub(crate) use datetime_utc_alias::*;
pub(crate) use deprecated_c_element_tree::*;
pub(crate) use deprecated_import::*;
pub(crate) use deprecated_mock_import::*;
pub(crate) use deprecated_unittest_alias::*;
pub(crate) use extraneous_parentheses::*;
pub(crate) use f_strings::*;
pub(crate) use format_literals::*;
pub(crate) use lru_cache_with_maxsize_none::*;
pub(crate) use lru_cache_without_parameters::*;
pub(crate) use native_literals::*;
pub(crate) use non_pep646_unpack::*;
pub(crate) use open_alias::*;
pub(crate) use os_error_alias::*;
pub(crate) use outdated_version_block::*;
pub(crate) use pep695::*;
pub(crate) use printf_string_formatting::*;
pub(crate) use quoted_annotation::*;
pub(crate) use redundant_open_modes::*;
pub(crate) use replace_stdout_stderr::*;
pub(crate) use replace_str_enum::*;
pub(crate) use replace_universal_newlines::*;
pub(crate) use super_call_with_parameters::*;
pub(crate) use timeout_error_alias::*;
pub(crate) use type_of_primitive::*;
pub(crate) use typing_text_str_alias::*;
pub(crate) use unicode_kind_prefix::*;
pub(crate) use unnecessary_builtin_import::*;
pub(crate) use unnecessary_class_parentheses::*;
pub(crate) use unnecessary_coding_comment::*;
pub(crate) use unnecessary_default_type_args::*;
pub(crate) use unnecessary_encode_utf8::*;
pub(crate) use unnecessary_future_import::*;
pub(crate) use unpacked_list_comprehension::*;
pub(crate) use use_pep585_annotation::*;
pub(crate) use use_pep604_annotation::*;
pub(crate) use use_pep604_isinstance::*;
pub(crate) use useless_class_metaclass_type::*;
pub(crate) use useless_metaclass_type::*;
pub(crate) use useless_object_inheritance::*;
pub(crate) use yield_in_for_loop::*;
mod convert_named_tuple_functional_to_class;
mod convert_typed_dict_functional_to_class;
mod datetime_utc_alias;
mod deprecated_c_element_tree;
mod deprecated_import;
mod deprecated_mock_import;
mod deprecated_unittest_alias;
mod extraneous_parentheses;
mod f_strings;
mod format_literals;
mod lru_cache_with_maxsize_none;
mod lru_cache_without_parameters;
mod native_literals;
mod non_pep646_unpack;
mod open_alias;
mod os_error_alias;
mod outdated_version_block;
pub(crate) mod pep695;
mod printf_string_formatting;
mod quoted_annotation;
mod redundant_open_modes;
mod replace_stdout_stderr;
mod replace_str_enum;
mod replace_universal_newlines;
mod super_call_with_parameters;
mod timeout_error_alias;
mod type_of_primitive;
mod typing_text_str_alias;
mod unicode_kind_prefix;
mod unnecessary_builtin_import;
mod unnecessary_class_parentheses;
mod unnecessary_coding_comment;
mod unnecessary_default_type_args;
mod unnecessary_encode_utf8;
mod unnecessary_future_import;
mod unpacked_list_comprehension;
mod use_pep585_annotation;
mod use_pep604_annotation;
mod use_pep604_isinstance;
mod useless_class_metaclass_type;
mod useless_metaclass_type;
mod useless_object_inheritance;
mod yield_in_for_loop;
| 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/pyupgrade/rules/convert_typed_dict_functional_to_class.rs | crates/ruff_linter/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Identifier, Keyword, Stmt};
use ruff_python_codegen::Generator;
use ruff_python_semantic::SemanticModel;
use ruff_python_stdlib::identifiers::is_identifier;
use ruff_python_trivia::CommentRanges;
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `TypedDict` declarations that use functional syntax.
///
/// ## Why is this bad?
/// `TypedDict` types can be defined either through a functional syntax
/// (`Foo = TypedDict(...)`) or a class syntax (`class Foo(TypedDict): ...`).
///
/// The class syntax is more readable and generally preferred over the
/// functional syntax.
///
/// Nonetheless, there are some situations in which it is impossible to use
/// the class-based syntax. This rule will not apply to those cases. Namely,
/// it is impossible to use the class-based syntax if any `TypedDict` fields are:
/// - Not valid [python identifiers] (for example, `@x`)
/// - [Python keywords] such as `in`
/// - [Private names] such as `__id` that would undergo [name mangling] at runtime
/// if the class-based syntax was used
/// - [Dunder names] such as `__int__` that can confuse type checkers if they're used
/// with the class-based syntax.
///
/// ## Example
/// ```python
/// from typing import TypedDict
///
/// Foo = TypedDict("Foo", {"a": int, "b": str})
/// ```
///
/// Use instead:
/// ```python
/// from typing import TypedDict
///
///
/// class Foo(TypedDict):
/// a: int
/// b: str
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe if there are any comments within the
/// range of the `TypedDict` definition, as these will be dropped by the
/// autofix.
///
/// ## References
/// - [Python documentation: `typing.TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict)
///
/// [Private names]: https://docs.python.org/3/tutorial/classes.html#private-variables
/// [name mangling]: https://docs.python.org/3/reference/expressions.html#private-name-mangling
/// [python identifiers]: https://docs.python.org/3/reference/lexical_analysis.html#identifiers
/// [Python keywords]: https://docs.python.org/3/reference/lexical_analysis.html#keywords
/// [Dunder names]: https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct ConvertTypedDictFunctionalToClass {
name: String,
}
impl Violation for ConvertTypedDictFunctionalToClass {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let ConvertTypedDictFunctionalToClass { name } = self;
format!("Convert `{name}` from `TypedDict` functional to class syntax")
}
fn fix_title(&self) -> Option<String> {
let ConvertTypedDictFunctionalToClass { name } = self;
Some(format!("Convert `{name}` to class syntax"))
}
}
/// UP013
pub(crate) fn convert_typed_dict_functional_to_class(
checker: &Checker,
stmt: &Stmt,
targets: &[Expr],
value: &Expr,
) {
let Some((class_name, arguments, base_class)) =
match_typed_dict_assign(targets, value, checker.semantic())
else {
return;
};
let Some((body, total_keyword)) = match_fields_and_total(arguments) else {
return;
};
let mut diagnostic = checker.report_diagnostic(
ConvertTypedDictFunctionalToClass {
name: class_name.to_string(),
},
stmt.range(),
);
// TODO(charlie): Preserve indentation, to remove the first-column requirement.
if checker.locator().is_at_start_of_line(stmt.start()) {
diagnostic.set_fix(convert_to_class(
stmt,
class_name,
body,
total_keyword,
base_class,
checker.generator(),
checker.comment_ranges(),
));
}
}
/// Return the class name, arguments, keywords and base class for a `TypedDict`
/// assignment.
fn match_typed_dict_assign<'a>(
targets: &'a [Expr],
value: &'a Expr,
semantic: &SemanticModel,
) -> Option<(&'a str, &'a Arguments, &'a Expr)> {
let [Expr::Name(ast::ExprName { id: class_name, .. })] = targets else {
return None;
};
let Expr::Call(ast::ExprCall {
func,
arguments,
range: _,
node_index: _,
}) = value
else {
return None;
};
if !semantic.match_typing_expr(func, "TypedDict") {
return None;
}
Some((class_name, arguments, func))
}
/// Generate a [`Stmt::AnnAssign`] representing the provided field definition.
fn create_field_assignment_stmt(field: &str, annotation: &Expr) -> Stmt {
ast::StmtAnnAssign {
target: Box::new(
ast::ExprName {
id: field.into(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
),
annotation: Box::new(annotation.clone()),
value: None,
simple: true,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into()
}
/// Generate a `StmtKind:ClassDef` statement based on the provided body, keywords, and base class.
fn create_class_def_stmt(
class_name: &str,
body: Vec<Stmt>,
total_keyword: Option<&Keyword>,
base_class: &Expr,
) -> Stmt {
ast::StmtClassDef {
name: Identifier::new(class_name.to_string(), TextRange::default()),
arguments: Some(Box::new(Arguments {
args: Box::from([base_class.clone()]),
keywords: match total_keyword {
Some(keyword) => Box::from([keyword.clone()]),
None => Box::from([]),
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})),
body,
type_params: None,
decorator_list: vec![],
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into()
}
fn fields_from_dict_literal(items: &[ast::DictItem]) -> Option<Vec<Stmt>> {
if items.is_empty() {
let node = Stmt::Pass(ast::StmtPass {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
Some(vec![node])
} else {
items
.iter()
.map(|ast::DictItem { key, value }| match key {
Some(Expr::StringLiteral(ast::ExprStringLiteral { value: field, .. })) => {
if !is_identifier(field.to_str()) {
return None;
}
// Converting TypedDict to class-based syntax is not safe if fields contain
// private or dunder names, because private names will be mangled and dunder
// names can confuse type checkers.
if field.to_str().starts_with("__") {
return None;
}
Some(create_field_assignment_stmt(field.to_str(), value))
}
_ => None,
})
.collect()
}
}
fn fields_from_dict_call(func: &Expr, keywords: &[Keyword]) -> Option<Vec<Stmt>> {
let ast::ExprName { id, .. } = func.as_name_expr()?;
if id != "dict" {
return None;
}
if keywords.is_empty() {
let node = Stmt::Pass(ast::StmtPass {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
Some(vec![node])
} else {
fields_from_keywords(keywords)
}
}
// Deprecated in Python 3.11, removed in Python 3.13.
fn fields_from_keywords(keywords: &[Keyword]) -> Option<Vec<Stmt>> {
if keywords.is_empty() {
let node = Stmt::Pass(ast::StmtPass {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
return Some(vec![node]);
}
keywords
.iter()
.map(|keyword| {
keyword
.arg
.as_ref()
.map(|field| create_field_assignment_stmt(field, &keyword.value))
})
.collect()
}
/// Match the fields and `total` keyword from a `TypedDict` call.
fn match_fields_and_total(arguments: &Arguments) -> Option<(Vec<Stmt>, Option<&Keyword>)> {
match (&*arguments.args, &*arguments.keywords) {
// Ex) `TypedDict("MyType", {"a": int, "b": str})`
([_typename, fields], [..]) => {
let total = arguments.find_keyword("total");
match fields {
Expr::Dict(ast::ExprDict {
items,
range: _,
node_index: _,
}) => Some((fields_from_dict_literal(items)?, total)),
Expr::Call(ast::ExprCall {
func,
arguments: Arguments { keywords, .. },
range: _,
node_index: _,
}) => Some((fields_from_dict_call(func, keywords)?, total)),
_ => None,
}
}
// Ex) `TypedDict("MyType")`
([_typename], []) => {
let node = Stmt::Pass(ast::StmtPass {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
Some((vec![node], None))
}
// Ex) `TypedDict("MyType", a=int, b=str)`
([_typename], fields) => Some((fields_from_keywords(fields)?, None)),
// Ex) `TypedDict()`
_ => None,
}
}
/// Generate a `Fix` to convert a `TypedDict` from functional to class.
fn convert_to_class(
stmt: &Stmt,
class_name: &str,
body: Vec<Stmt>,
total_keyword: Option<&Keyword>,
base_class: &Expr,
generator: Generator,
comment_ranges: &CommentRanges,
) -> Fix {
Fix::applicable_edit(
Edit::range_replacement(
generator.stmt(&create_class_def_stmt(
class_name,
body,
total_keyword,
base_class,
)),
stmt.range(),
),
if comment_ranges.intersects(stmt.range()) {
Applicability::Unsafe
} else {
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/pyupgrade/rules/convert_named_tuple_functional_to_class.rs | crates/ruff_linter/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs | use log::debug;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_dunder;
use ruff_python_ast::name::Name;
use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Identifier, Keyword, Stmt};
use ruff_python_codegen::Generator;
use ruff_python_semantic::SemanticModel;
use ruff_python_stdlib::identifiers::is_identifier;
use ruff_python_trivia::CommentRanges;
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `NamedTuple` declarations that use functional syntax.
///
/// ## Why is this bad?
/// `NamedTuple` subclasses can be defined either through a functional syntax
/// (`Foo = NamedTuple(...)`) or a class syntax (`class Foo(NamedTuple): ...`).
///
/// The class syntax is more readable and generally preferred over the
/// functional syntax, which exists primarily for backwards compatibility
/// with `collections.namedtuple`.
///
/// ## Example
/// ```python
/// from typing import NamedTuple
///
/// Foo = NamedTuple("Foo", [("a", int), ("b", str)])
/// ```
///
/// Use instead:
/// ```python
/// from typing import NamedTuple
///
///
/// class Foo(NamedTuple):
/// a: int
/// b: str
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe if there are any comments within the
/// range of the `NamedTuple` definition, as these will be dropped by the
/// autofix.
///
/// ## References
/// - [Python documentation: `typing.NamedTuple`](https://docs.python.org/3/library/typing.html#typing.NamedTuple)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct ConvertNamedTupleFunctionalToClass {
name: String,
}
impl Violation for ConvertNamedTupleFunctionalToClass {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let ConvertNamedTupleFunctionalToClass { name } = self;
format!("Convert `{name}` from `NamedTuple` functional to class syntax")
}
fn fix_title(&self) -> Option<String> {
let ConvertNamedTupleFunctionalToClass { name } = self;
Some(format!("Convert `{name}` to class syntax"))
}
}
/// UP014
pub(crate) fn convert_named_tuple_functional_to_class(
checker: &Checker,
stmt: &Stmt,
targets: &[Expr],
value: &Expr,
) {
let Some((typename, args, keywords, base_class)) =
match_named_tuple_assign(targets, value, checker.semantic())
else {
return;
};
let fields = match (args, keywords) {
// Ex) `NamedTuple("MyType")`
([_typename], []) => vec![Stmt::Pass(ast::StmtPass {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})],
// Ex) `NamedTuple("MyType", [("a", int), ("b", str)])`
([_typename, fields], []) => {
if let Some(fields) = create_fields_from_fields_arg(fields) {
fields
} else {
debug!("Skipping `NamedTuple` \"{typename}\": unable to parse fields");
return;
}
}
// Ex) `NamedTuple("MyType", a=int, b=str)`
([_typename], keywords) => {
if let Some(fields) = create_fields_from_keywords(keywords) {
fields
} else {
debug!("Skipping `NamedTuple` \"{typename}\": unable to parse keywords");
return;
}
}
// Ex) `NamedTuple()`
_ => {
debug!("Skipping `NamedTuple` \"{typename}\": mixed fields and keywords");
return;
}
};
let mut diagnostic = checker.report_diagnostic(
ConvertNamedTupleFunctionalToClass {
name: typename.to_string(),
},
stmt.range(),
);
// TODO(charlie): Preserve indentation, to remove the first-column requirement.
if checker.locator().is_at_start_of_line(stmt.start()) {
diagnostic.set_fix(convert_to_class(
stmt,
typename,
fields,
base_class,
checker.generator(),
checker.comment_ranges(),
));
}
}
/// Return the typename, args, keywords, and base class.
fn match_named_tuple_assign<'a>(
targets: &'a [Expr],
value: &'a Expr,
semantic: &SemanticModel,
) -> Option<(&'a str, &'a [Expr], &'a [Keyword], &'a Expr)> {
let [Expr::Name(ast::ExprName { id: typename, .. })] = targets else {
return None;
};
let Expr::Call(ast::ExprCall {
func,
arguments: Arguments { args, keywords, .. },
range: _,
node_index: _,
}) = value
else {
return None;
};
if !semantic.match_typing_expr(func, "NamedTuple") {
return None;
}
Some((typename, args, keywords, func))
}
/// Generate a [`Stmt::AnnAssign`] representing the provided field definition.
fn create_field_assignment_stmt(field: Name, annotation: &Expr) -> Stmt {
ast::StmtAnnAssign {
target: Box::new(
ast::ExprName {
id: field,
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
),
annotation: Box::new(annotation.clone()),
value: None,
simple: true,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into()
}
/// Create a list of field assignments from the `NamedTuple` fields argument.
fn create_fields_from_fields_arg(fields: &Expr) -> Option<Vec<Stmt>> {
let fields = fields.as_list_expr()?;
if fields.is_empty() {
let node = Stmt::Pass(ast::StmtPass {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
Some(vec![node])
} else {
fields
.iter()
.map(|field| {
let ast::ExprTuple { elts, .. } = field.as_tuple_expr()?;
let [field, annotation] = elts.as_slice() else {
return None;
};
if annotation.is_starred_expr() {
return None;
}
let ast::ExprStringLiteral { value: field, .. } = field.as_string_literal_expr()?;
if !is_identifier(field.to_str()) {
return None;
}
if is_dunder(field.to_str()) {
return None;
}
Some(create_field_assignment_stmt(
Name::new(field.to_str()),
annotation,
))
})
.collect()
}
}
/// Create a list of field assignments from the `NamedTuple` keyword arguments.
fn create_fields_from_keywords(keywords: &[Keyword]) -> Option<Vec<Stmt>> {
keywords
.iter()
.map(|keyword| {
keyword
.arg
.as_ref()
.map(|field| create_field_assignment_stmt(field.id.clone(), &keyword.value))
})
.collect()
}
/// Generate a `StmtKind:ClassDef` statement based on the provided body and
/// keywords.
fn create_class_def_stmt(typename: &str, body: Vec<Stmt>, base_class: &Expr) -> Stmt {
ast::StmtClassDef {
name: Identifier::new(typename.to_string(), TextRange::default()),
arguments: Some(Box::new(Arguments {
args: Box::from([base_class.clone()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})),
body,
type_params: None,
decorator_list: vec![],
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into()
}
/// Generate a `Fix` to convert a `NamedTuple` assignment to a class definition.
fn convert_to_class(
stmt: &Stmt,
typename: &str,
body: Vec<Stmt>,
base_class: &Expr,
generator: Generator,
comment_ranges: &CommentRanges,
) -> Fix {
Fix::applicable_edit(
Edit::range_replacement(
generator.stmt(&create_class_def_stmt(typename, body, base_class)),
stmt.range(),
),
if comment_ranges.intersects(stmt.range()) {
Applicability::Unsafe
} else {
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/pyupgrade/rules/datetime_utc_alias.rs | crates/ruff_linter/src/rules/pyupgrade/rules/datetime_utc_alias.rs | use ruff_python_ast::Expr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `datetime.timezone.utc`.
///
/// ## Why is this bad?
/// As of Python 3.11, `datetime.UTC` is an alias for `datetime.timezone.utc`.
/// The alias is more readable and generally preferred over the full path.
///
/// ## Example
/// ```python
/// import datetime
///
/// datetime.timezone.utc
/// ```
///
/// Use instead:
/// ```python
/// import datetime
///
/// datetime.UTC
/// ```
///
/// ## Options
/// - `target-version`
///
/// ## References
/// - [Python documentation: `datetime.UTC`](https://docs.python.org/3/library/datetime.html#datetime.UTC)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.192")]
pub(crate) struct DatetimeTimezoneUTC;
impl Violation for DatetimeTimezoneUTC {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use `datetime.UTC` alias".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Convert to `datetime.UTC` alias".to_string())
}
}
/// UP017
pub(crate) fn datetime_utc_alias(checker: &Checker, expr: &Expr) {
if checker
.semantic()
.resolve_qualified_name(expr)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["datetime", "timezone", "utc"])
})
{
let mut diagnostic = checker.report_diagnostic(DatetimeTimezoneUTC, expr.range());
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import_from("datetime", "UTC"),
expr.start(),
checker.semantic(),
)?;
let reference_edit = Edit::range_replacement(binding, expr.range());
Ok(Fix::safe_edits(import_edit, [reference_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/pyupgrade/rules/outdated_version_block.rs | crates/ruff_linter/src/rules/pyupgrade/rules/outdated_version_block.rs | use std::cmp::Ordering;
use anyhow::Result;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::map_subscript;
use ruff_python_ast::stmt_if::{BranchKind, IfElifBranch, if_elif_branches};
use ruff_python_ast::whitespace::indentation;
use ruff_python_ast::{self as ast, CmpOp, ElifElseClause, Expr, Int, StmtIf};
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextLen, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::edits::{adjust_indentation, delete_stmt};
use crate::{Edit, Fix, FixAvailability, Violation};
use ruff_python_ast::PythonVersion;
use ruff_python_semantic::SemanticModel;
/// ## What it does
/// Checks for conditional blocks gated on `sys.version_info` comparisons
/// that are outdated for the minimum supported Python version.
///
/// ## Why is this bad?
/// In Python, code can be conditionally executed based on the active
/// Python version by comparing against the `sys.version_info` tuple.
///
/// If a code block is only executed for Python versions older than the
/// minimum supported version, it should be removed.
///
/// ## Example
/// ```python
/// import sys
///
/// if sys.version_info < (3, 0):
/// print("py2")
/// else:
/// print("py3")
/// ```
///
/// Use instead:
/// ```python
/// print("py3")
/// ```
///
/// ## Options
/// - `target-version`
///
/// ## Fix safety
/// This rule's fix is marked as unsafe because it will remove all code,
/// comments, and annotations within unreachable version blocks.
///
/// ## References
/// - [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.240")]
pub(crate) struct OutdatedVersionBlock {
reason: Reason,
}
impl Violation for OutdatedVersionBlock {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
match self.reason {
Reason::AlwaysFalse | Reason::AlwaysTrue => {
"Version block is outdated for minimum Python version".to_string()
}
Reason::Invalid => "Version specifier is invalid".to_string(),
}
}
fn fix_title(&self) -> Option<String> {
match self.reason {
Reason::AlwaysFalse | Reason::AlwaysTrue => {
Some("Remove outdated version block".to_string())
}
Reason::Invalid => None,
}
}
}
#[derive(Debug, PartialEq, Eq)]
enum Reason {
AlwaysTrue,
AlwaysFalse,
Invalid,
}
/// UP036
pub(crate) fn outdated_version_block(checker: &Checker, stmt_if: &StmtIf) {
for branch in if_elif_branches(stmt_if) {
let Expr::Compare(ast::ExprCompare {
left,
ops,
comparators,
range: _,
node_index: _,
}) = &branch.test
else {
continue;
};
let ([op], [comparison]) = (&**ops, &**comparators) else {
continue;
};
if !is_valid_version_info(checker.semantic(), left) {
continue;
}
match comparison {
Expr::Tuple(ast::ExprTuple { elts, .. }) => match op {
CmpOp::Lt | CmpOp::LtE | CmpOp::Gt | CmpOp::GtE => {
let Some(version) = extract_version(elts) else {
return;
};
let target = checker.target_version();
match version_always_less_than(
&version,
target,
// `x <= y` and `x > y` are cases where `x == y` will not stop the comparison
// from always evaluating to true or false respectively
op.is_lt_e() || op.is_gt(),
) {
Ok(false) => {}
Ok(true) => {
let mut diagnostic = checker.report_diagnostic(
OutdatedVersionBlock {
reason: if op.is_lt() || op.is_lt_e() {
Reason::AlwaysFalse
} else {
Reason::AlwaysTrue
},
},
branch.test.range(),
);
if let Some(fix) = if op.is_lt() || op.is_lt_e() {
fix_always_false_branch(checker, stmt_if, &branch)
} else {
fix_always_true_branch(checker, stmt_if, &branch)
} {
diagnostic.set_fix(fix);
}
}
Err(_) => {
checker.report_diagnostic(
OutdatedVersionBlock {
reason: Reason::Invalid,
},
comparison.range(),
);
}
}
}
_ => {}
},
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(int),
..
}) => {
let reason = match (int.as_u8(), op) {
(Some(2), CmpOp::Eq) => Reason::AlwaysFalse,
(Some(3), CmpOp::Eq) => Reason::AlwaysTrue,
(Some(2), CmpOp::NotEq) => Reason::AlwaysTrue,
(Some(3), CmpOp::NotEq) => Reason::AlwaysFalse,
(Some(2), CmpOp::Lt) => Reason::AlwaysFalse,
(Some(3), CmpOp::Lt) => Reason::AlwaysFalse,
(Some(2), CmpOp::LtE) => Reason::AlwaysFalse,
(Some(3), CmpOp::LtE) => Reason::AlwaysTrue,
(Some(2), CmpOp::Gt) => Reason::AlwaysTrue,
(Some(3), CmpOp::Gt) => Reason::AlwaysFalse,
(Some(2), CmpOp::GtE) => Reason::AlwaysTrue,
(Some(3), CmpOp::GtE) => Reason::AlwaysTrue,
(None, _) => Reason::Invalid,
_ => return,
};
match reason {
Reason::AlwaysTrue => {
let mut diagnostic = checker.report_diagnostic(
OutdatedVersionBlock { reason },
branch.test.range(),
);
if let Some(fix) = fix_always_true_branch(checker, stmt_if, &branch) {
diagnostic.set_fix(fix);
}
}
Reason::AlwaysFalse => {
let mut diagnostic = checker.report_diagnostic(
OutdatedVersionBlock { reason },
branch.test.range(),
);
if let Some(fix) = fix_always_false_branch(checker, stmt_if, &branch) {
diagnostic.set_fix(fix);
}
}
Reason::Invalid => {
checker.report_diagnostic(
OutdatedVersionBlock {
reason: Reason::Invalid,
},
comparison.range(),
);
}
}
}
_ => (),
}
}
}
/// Returns true if the `check_version` is always less than the [`PythonVersion`].
fn version_always_less_than(
check_version: &[Int],
py_version: PythonVersion,
or_equal: bool,
) -> Result<bool> {
let mut check_version_iter = check_version.iter();
let Some(if_major) = check_version_iter.next() else {
return Ok(false);
};
let Some(if_major) = if_major.as_u8() else {
return Err(anyhow::anyhow!("invalid major version: {if_major}"));
};
let (py_major, py_minor) = py_version.as_tuple();
match if_major.cmp(&py_major) {
Ordering::Less => Ok(true),
Ordering::Greater => Ok(false),
Ordering::Equal => {
let Some(if_minor) = check_version_iter.next() else {
return Ok(true);
};
let Some(if_minor) = if_minor.as_u8() else {
return Err(anyhow::anyhow!("invalid minor version: {if_minor}"));
};
let if_micro = match check_version_iter.next() {
None => None,
Some(micro) => match micro.as_u8() {
Some(micro) => Some(micro),
None => anyhow::bail!("invalid micro version: {micro}"),
},
};
Ok(if or_equal {
// Ex) `sys.version_info <= 3.8`. If Python 3.8 is the minimum supported version,
// the condition won't always evaluate to `false`, so we want to return `false`.
if_minor < py_minor
} else {
if let Some(if_micro) = if_micro {
// Ex) `sys.version_info < 3.8.3`
if_minor < py_minor || if_minor == py_minor && if_micro == 0
} else {
// Ex) `sys.version_info < 3.8`. If Python 3.8 is the minimum supported version,
// the condition _will_ always evaluate to `false`, so we want to return `true`.
if_minor <= py_minor
}
})
}
}
}
/// Fix a branch that is known to always evaluate to `false`.
///
/// For example, when running with a minimum supported version of Python 3.8, the following branch
/// would be considered redundant:
/// ```python
/// if sys.version_info < (3, 7): ...
/// ```
///
/// In this case, the fix would involve removing the branch; however, there are multiple cases to
/// consider. For example, if the `if` has an `else`, then the `if` should be removed, and the
/// `else` should be inlined at the top level.
fn fix_always_false_branch(
checker: &Checker,
stmt_if: &StmtIf,
branch: &IfElifBranch,
) -> Option<Fix> {
match branch.kind {
BranchKind::If => match stmt_if.elif_else_clauses.first() {
// If we have a lone `if`, delete as statement (insert pass in parent if required)
None => {
let stmt = checker.semantic().current_statement();
let parent = checker.semantic().current_statement_parent();
let edit = delete_stmt(stmt, parent, checker.locator(), checker.indexer());
Some(Fix::unsafe_edit(edit))
}
// If we have an `if` and an `elif`, turn the `elif` into an `if`
Some(ElifElseClause {
test: Some(_),
range,
..
}) => {
debug_assert!(
checker
.locator()
.slice(TextRange::at(range.start(), "elif".text_len()))
== "elif"
);
let end_location = range.start() + ("elif".text_len() - "if".text_len());
Some(Fix::unsafe_edit(Edit::deletion(
stmt_if.start(),
end_location,
)))
}
// If we only have an `if` and an `else`, dedent the `else` block
Some(ElifElseClause {
body, test: None, ..
}) => {
let start = body.first()?;
let end = body.last()?;
if indentation(checker.source(), start).is_none() {
// Inline `else` block (e.g., `else: x = 1`).
Some(Fix::unsafe_edit(Edit::range_replacement(
checker
.locator()
.slice(TextRange::new(start.start(), end.end()))
.to_string(),
stmt_if.range(),
)))
} else {
indentation(checker.source(), stmt_if)
.and_then(|indentation| {
adjust_indentation(
TextRange::new(
checker.locator().line_start(start.start()),
end.end(),
),
indentation,
checker.locator(),
checker.indexer(),
checker.stylist(),
)
.ok()
})
.map(|contents| {
Fix::unsafe_edit(Edit::replacement(
contents,
checker.locator().line_start(stmt_if.start()),
stmt_if.end(),
))
})
}
}
},
BranchKind::Elif => {
// The range of the `ElifElseClause` ends in the line of the last statement. To avoid
// inserting an empty line between the end of `if` branch and the beginning `elif` or
// `else` branch after the deleted branch we find the next branch after the current, if
// any, and delete to its start.
// ```python
// if cond:
// x = 1
// elif sys.version < (3.0):
// delete from here ... ^ x = 2
// else:
// ... to here (exclusive) ^ x = 3
// ```
let next_start = stmt_if
.elif_else_clauses
.iter()
.map(Ranged::start)
.find(|start| *start > branch.start());
Some(Fix::unsafe_edit(Edit::deletion(
branch.start(),
next_start.unwrap_or(branch.end()),
)))
}
}
}
/// Fix a branch that is known to always evaluate to `true`.
///
/// For example, when running with a minimum supported version of Python 3.8, the following branch
/// would be considered redundant, as it's known to always evaluate to `true`:
/// ```python
/// if sys.version_info >= (3, 8): ...
/// ```
fn fix_always_true_branch(
checker: &Checker,
stmt_if: &StmtIf,
branch: &IfElifBranch,
) -> Option<Fix> {
match branch.kind {
BranchKind::If => {
// If the first statement is an `if`, use the body of this statement, and ignore
// the rest.
let start = branch.body.first()?;
let end = branch.body.last()?;
if indentation(checker.source(), start).is_none() {
// Inline `if` block (e.g., `if ...: x = 1`).
Some(Fix::unsafe_edit(Edit::range_replacement(
checker
.locator()
.slice(TextRange::new(start.start(), end.end()))
.to_string(),
stmt_if.range,
)))
} else {
indentation(checker.source(), &stmt_if)
.and_then(|indentation| {
adjust_indentation(
TextRange::new(checker.locator().line_start(start.start()), end.end()),
indentation,
checker.locator(),
checker.indexer(),
checker.stylist(),
)
.ok()
})
.map(|contents| {
Fix::unsafe_edit(Edit::replacement(
contents,
checker.locator().line_start(stmt_if.start()),
stmt_if.end(),
))
})
}
}
BranchKind::Elif => {
// Replace the `elif` with an `else`, preserve the body of the elif, and remove
// the rest.
let end = branch.body.last()?;
let text = checker
.locator()
.slice(TextRange::new(branch.test.end(), end.end()));
Some(Fix::unsafe_edit(Edit::range_replacement(
format!("else{text}"),
TextRange::new(branch.start(), stmt_if.end()),
)))
}
}
}
/// Return the version tuple as a sequence of [`Int`] values.
fn extract_version(elts: &[Expr]) -> Option<Vec<Int>> {
let mut version: Vec<Int> = vec![];
for elt in elts {
let Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(int),
..
}) = &elt
else {
return None;
};
version.push(int.clone());
}
Some(version)
}
/// Returns `true` if the expression is related to `sys.version_info`.
///
/// This includes:
/// - Direct access: `sys.version_info`
/// - Subscript access: `sys.version_info[:2]`, `sys.version_info[0]`
/// - Major version attribute: `sys.version_info.major`
fn is_valid_version_info(semantic: &SemanticModel, left: &Expr) -> bool {
semantic
.resolve_qualified_name(map_subscript(left))
.is_some_and(|name| matches!(name.segments(), ["sys", "version_info"]))
|| semantic
.resolve_qualified_name(left)
.is_some_and(|name| matches!(name.segments(), ["sys", "version_info", "major"]))
}
#[cfg(test)]
mod tests {
use test_case::test_case;
use super::*;
#[test_case(PythonVersion::PY37, & [2], true, true; "compare-2.0")]
#[test_case(PythonVersion::PY37, & [2, 0], true, true; "compare-2.0-whole")]
#[test_case(PythonVersion::PY37, & [3], true, true; "compare-3.0")]
#[test_case(PythonVersion::PY37, & [3, 0], true, true; "compare-3.0-whole")]
#[test_case(PythonVersion::PY37, & [3, 1], true, true; "compare-3.1")]
#[test_case(PythonVersion::PY37, & [3, 5], true, true; "compare-3.5")]
#[test_case(PythonVersion::PY37, & [3, 7], true, false; "compare-3.7")]
#[test_case(PythonVersion::PY37, & [3, 7], false, true; "compare-3.7-not-equal")]
#[test_case(PythonVersion::PY37, & [3, 8], false, false; "compare-3.8")]
#[test_case(PythonVersion::PY310, & [3, 9], true, true; "compare-3.9")]
#[test_case(PythonVersion::PY310, & [3, 11], true, false; "compare-3.11")]
fn test_compare_version(
version: PythonVersion,
target_versions: &[u8],
or_equal: bool,
expected: bool,
) -> Result<()> {
let target_versions: Vec<_> = target_versions.iter().map(|int| Int::from(*int)).collect();
let actual = version_always_less_than(&target_versions, version, or_equal)?;
assert_eq!(actual, expected);
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/pyupgrade/rules/replace_stdout_stderr.rs | crates/ruff_linter/src/rules/pyupgrade/rules/replace_stdout_stderr.rs | use anyhow::Result;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Keyword, token::Tokens};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `subprocess.run` that send `stdout` and `stderr` to a
/// pipe.
///
/// ## Why is this bad?
/// As of Python 3.7, `subprocess.run` has a `capture_output` keyword argument
/// that can be set to `True` to capture `stdout` and `stderr` outputs. This is
/// equivalent to setting `stdout` and `stderr` to `subprocess.PIPE`, but is
/// more explicit and readable.
///
/// ## Example
/// ```python
/// import subprocess
///
/// subprocess.run(["foo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
/// ```
///
/// Use instead:
/// ```python
/// import subprocess
///
/// subprocess.run(["foo"], capture_output=True)
/// ```
///
/// ## Fix safety
///
/// This rule's fix is marked as unsafe because replacing `stdout=subprocess.PIPE` and
/// `stderr=subprocess.PIPE` with `capture_output=True` may delete comments attached
/// to the original arguments.
///
/// ## References
/// - [Python 3.7 release notes](https://docs.python.org/3/whatsnew/3.7.html#subprocess)
/// - [Python documentation: `subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.199")]
pub(crate) struct ReplaceStdoutStderr;
impl Violation for ReplaceStdoutStderr {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Prefer `capture_output` over sending `stdout` and `stderr` to `PIPE`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `capture_output` keyword argument".to_string())
}
}
/// UP022
pub(crate) fn replace_stdout_stderr(checker: &Checker, call: &ast::ExprCall) {
if !checker.semantic().seen_module(Modules::SUBPROCESS) {
return;
}
if checker
.semantic()
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["subprocess", "run"]))
{
// Find `stdout` and `stderr` kwargs.
let Some(stdout) = call.arguments.find_keyword("stdout") else {
return;
};
let Some(stderr) = call.arguments.find_keyword("stderr") else {
return;
};
// Verify that they're both set to `subprocess.PIPE`.
if !checker
.semantic()
.resolve_qualified_name(&stdout.value)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["subprocess", "PIPE"])
})
|| !checker
.semantic()
.resolve_qualified_name(&stderr.value)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["subprocess", "PIPE"])
})
{
return;
}
let mut diagnostic = checker.report_diagnostic(ReplaceStdoutStderr, call.range());
if call.arguments.find_keyword("capture_output").is_none() {
diagnostic.try_set_fix(|| {
generate_fix(
stdout,
stderr,
call,
checker.locator().contents(),
checker.tokens(),
)
});
}
}
}
/// Generate a [`Edit`] for a `stdout` and `stderr` [`Keyword`] pair.
fn generate_fix(
stdout: &Keyword,
stderr: &Keyword,
call: &ast::ExprCall,
source: &str,
tokens: &Tokens,
) -> Result<Fix> {
let (first, second) = if stdout.start() < stderr.start() {
(stdout, stderr)
} else {
(stderr, stdout)
};
// Replace one argument with `capture_output=True`, and remove the other.
Ok(Fix::unsafe_edits(
Edit::range_replacement("capture_output=True".to_string(), first.range()),
[remove_argument(
second,
&call.arguments,
Parentheses::Preserve,
source,
tokens,
)?],
))
}
| 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/pyupgrade/rules/useless_object_inheritance.rs | crates/ruff_linter/src/rules/pyupgrade/rules/useless_object_inheritance.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::{AlwaysFixableViolation, Fix};
/// ## What it does
/// Checks for classes that inherit from `object`.
///
/// ## Why is this bad?
/// Since Python 3, all classes inherit from `object` by default, so `object` can
/// be omitted from the list of base classes.
///
/// ## Example
///
/// ```python
/// class Foo(object): ...
/// ```
///
/// Use instead:
///
/// ```python
/// class Foo: ...
/// ```
///
/// ## Fix safety
/// This fix is unsafe if it would cause comments to be deleted.
///
/// ## References
/// - [PEP 3115 – Metaclasses in Python 3000](https://peps.python.org/pep-3115/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct UselessObjectInheritance {
name: String,
}
impl AlwaysFixableViolation for UselessObjectInheritance {
#[derive_message_formats]
fn message(&self) -> String {
let UselessObjectInheritance { name } = self;
format!("Class `{name}` inherits from `object`")
}
fn fix_title(&self) -> String {
"Remove `object` inheritance".to_string()
}
}
/// UP004
pub(crate) fn useless_object_inheritance(checker: &Checker, class_def: &ast::StmtClassDef) {
let Some(arguments) = class_def.arguments.as_deref() else {
return;
};
for base in &*arguments.args {
if !checker.semantic().match_builtin_expr(base, "object") {
continue;
}
let mut diagnostic = checker.report_diagnostic(
UselessObjectInheritance {
name: class_def.name.to_string(),
},
base.range(),
);
diagnostic.try_set_fix(|| {
let edit = remove_argument(
base,
arguments,
Parentheses::Remove,
checker.locator().contents(),
checker.tokens(),
)?;
let range = edit.range();
let applicability = if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
Ok(Fix::applicable_edit(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/pyupgrade/rules/lru_cache_without_parameters.rs | crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Decorator, Expr};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for unnecessary parentheses on `functools.lru_cache` decorators.
///
/// ## Why is this bad?
/// Since Python 3.8, `functools.lru_cache` can be used as a decorator without
/// trailing parentheses, as long as no arguments are passed to it.
///
/// ## Example
///
/// ```python
/// import functools
///
///
/// @functools.lru_cache()
/// def foo(): ...
/// ```
///
/// Use instead:
///
/// ```python
/// import functools
///
///
/// @functools.lru_cache
/// def foo(): ...
/// ```
///
/// ## Options
/// - `target-version`
///
/// ## References
/// - [Python documentation: `@functools.lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache)
/// - [Let lru_cache be used as a decorator with no arguments](https://github.com/python/cpython/issues/80953)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct LRUCacheWithoutParameters;
impl AlwaysFixableViolation for LRUCacheWithoutParameters {
#[derive_message_formats]
fn message(&self) -> String {
"Unnecessary parentheses to `functools.lru_cache`".to_string()
}
fn fix_title(&self) -> String {
"Remove unnecessary parentheses".to_string()
}
}
/// UP011
pub(crate) fn lru_cache_without_parameters(checker: &Checker, decorator_list: &[Decorator]) {
for decorator in decorator_list {
let Expr::Call(ast::ExprCall {
func,
arguments,
range: _,
node_index: _,
}) = &decorator.expression
else {
continue;
};
// Look for, e.g., `import functools; @functools.lru_cache()`.
if arguments.args.is_empty()
&& arguments.keywords.is_empty()
&& checker
.semantic()
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["functools", "lru_cache"])
})
{
let mut diagnostic = checker.report_diagnostic(
LRUCacheWithoutParameters,
TextRange::new(func.end(), decorator.end()),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(arguments.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/pyupgrade/rules/unnecessary_default_type_args.rs | crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_default_type_args.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Applicability, Edit, Fix};
/// ## What it does
/// Checks for unnecessary default type arguments for `Generator` and
/// `AsyncGenerator` on Python 3.13+.
/// In [preview], this rule will also apply to stub files.
///
/// ## Why is this bad?
/// Python 3.13 introduced the ability for type parameters to specify default
/// values. Following this change, several standard-library classes were
/// updated to add default values for some of their type parameters. For
/// example, `Generator[int]` is now equivalent to
/// `Generator[int, None, None]`, as the second and third type parameters of
/// `Generator` now default to `None`.
///
/// Omitting type arguments that match the default values can make the code
/// more concise and easier to read.
///
/// ## Example
///
/// ```python
/// from collections.abc import Generator, AsyncGenerator
///
///
/// def sync_gen() -> Generator[int, None, None]:
/// yield 42
///
///
/// async def async_gen() -> AsyncGenerator[int, None]:
/// yield 42
/// ```
///
/// Use instead:
///
/// ```python
/// from collections.abc import Generator, AsyncGenerator
///
///
/// def sync_gen() -> Generator[int]:
/// yield 42
///
///
/// async def async_gen() -> AsyncGenerator[int]:
/// yield 42
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as safe, unless the type annotation contains comments.
///
/// ## Options
/// - `target-version`
///
/// ## References
/// - [PEP 696 – Type Defaults for Type Parameters](https://peps.python.org/pep-0696/)
/// - [Annotating generators and coroutines](https://docs.python.org/3/library/typing.html#annotating-generators-and-coroutines)
/// - [Python documentation: `typing.Generator`](https://docs.python.org/3/library/typing.html#typing.Generator)
/// - [Python documentation: `typing.AsyncGenerator`](https://docs.python.org/3/library/typing.html#typing.AsyncGenerator)
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.8.0")]
pub(crate) struct UnnecessaryDefaultTypeArgs;
impl AlwaysFixableViolation for UnnecessaryDefaultTypeArgs {
#[derive_message_formats]
fn message(&self) -> String {
"Unnecessary default type arguments".to_string()
}
fn fix_title(&self) -> String {
"Remove default type arguments".to_string()
}
}
/// UP043
pub(crate) fn unnecessary_default_type_args(checker: &Checker, expr: &Expr) {
let Expr::Subscript(ast::ExprSubscript { value, slice, .. }) = expr else {
return;
};
let Expr::Tuple(ast::ExprTuple {
elts,
ctx: _,
range: _,
node_index: _,
parenthesized: _,
}) = slice.as_ref()
else {
return;
};
// The type annotation must be `Generator` or `AsyncGenerator`.
let Some(type_annotation) = DefaultedTypeAnnotation::from_expr(value, checker.semantic())
else {
return;
};
let valid_elts = type_annotation.trim_unnecessary_defaults(elts);
// If we didn't trim any elements, then the default type arguments are necessary.
if *elts == valid_elts {
return;
}
let mut diagnostic = checker.report_diagnostic(UnnecessaryDefaultTypeArgs, expr.range());
let applicability = if checker
.comment_ranges()
.has_comments(expr, checker.source())
{
Applicability::Unsafe
} else {
Applicability::Safe
};
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement(
checker
.generator()
.expr(&Expr::Subscript(ast::ExprSubscript {
value: value.clone(),
slice: Box::new(if let [elt] = valid_elts.as_slice() {
elt.clone()
} else {
Expr::Tuple(ast::ExprTuple {
elts: valid_elts,
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: true,
})
}),
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})),
expr.range(),
),
applicability,
));
}
/// Trim trailing `None` literals from the given elements.
///
/// For example, given `[int, None, None]`, return `[int]`.
fn trim_trailing_none(elts: &[Expr]) -> &[Expr] {
match elts.iter().rposition(|elt| !elt.is_none_literal_expr()) {
Some(trimmed_last_index) => elts[..=trimmed_last_index].as_ref(),
None => &[],
}
}
/// Type annotations that include default type arguments as of Python 3.13.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DefaultedTypeAnnotation {
/// `typing.Generator[YieldType, SendType = None, ReturnType = None]`
Generator,
/// `typing.AsyncGenerator[YieldType, SendType = None]`
AsyncGenerator,
}
impl DefaultedTypeAnnotation {
/// Returns the [`DefaultedTypeAnnotation`], if the given expression is a type annotation that
/// includes default type arguments.
fn from_expr(expr: &Expr, semantic: &ruff_python_semantic::SemanticModel) -> Option<Self> {
let qualified_name = semantic.resolve_qualified_name(expr)?;
if semantic.match_typing_qualified_name(&qualified_name, "Generator")
|| matches!(
qualified_name.segments(),
["collections", "abc", "Generator"]
)
{
Some(Self::Generator)
} else if semantic.match_typing_qualified_name(&qualified_name, "AsyncGenerator")
|| matches!(
qualified_name.segments(),
["collections", "abc", "AsyncGenerator"]
)
{
Some(Self::AsyncGenerator)
} else {
None
}
}
/// Trim any unnecessary default type arguments from the given elements.
fn trim_unnecessary_defaults(self, elts: &[Expr]) -> Vec<Expr> {
match self {
Self::Generator => {
// Check only if the number of elements is 2 or 3 (e.g., `Generator[int, None]` or `Generator[int, None, None]`).
// Otherwise, ignore (e.g., `Generator[]`, `Generator[int]`, `Generator[int, None, None, None]`)
if elts.len() != 2 && elts.len() != 3 {
return elts.to_vec();
}
std::iter::once(elts[0].clone())
.chain(trim_trailing_none(&elts[1..]).iter().cloned())
.collect::<Vec<_>>()
}
Self::AsyncGenerator => {
// Check only if the number of elements is 2 (e.g., `AsyncGenerator[int, None]`).
// Otherwise, ignore (e.g., `AsyncGenerator[]`, `AsyncGenerator[int]`, `AsyncGenerator[int, None, None]`)
if elts.len() != 2 {
return elts.to_vec();
}
std::iter::once(elts[0].clone())
.chain(trim_trailing_none(&elts[1..]).iter().cloned())
.collect::<Vec<_>>()
}
}
}
}
| 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/pyupgrade/rules/unnecessary_coding_comment.rs | crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_coding_comment.rs | use std::iter::FusedIterator;
use std::sync::LazyLock;
use regex::Regex;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_trivia::CommentRanges;
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::Locator;
use crate::checkers::ast::LintContext;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for unnecessary UTF-8 encoding declarations.
///
/// ## Why is this bad?
/// [PEP 3120] makes UTF-8 the default encoding, so a UTF-8 encoding
/// declaration is unnecessary.
///
/// ## Example
/// ```python
/// # -*- coding: utf-8 -*-
/// print("Hello, world!")
/// ```
///
/// Use instead:
/// ```python
/// print("Hello, world!")
/// ```
///
/// [PEP 3120]: https://peps.python.org/pep-3120/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct UTF8EncodingDeclaration;
impl AlwaysFixableViolation for UTF8EncodingDeclaration {
#[derive_message_formats]
fn message(&self) -> String {
"UTF-8 encoding declaration is unnecessary".to_string()
}
fn fix_title(&self) -> String {
"Remove unnecessary coding comment".to_string()
}
}
// Regex from PEP263.
static CODING_COMMENT_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^[ \t\f]*#.*?coding[:=][ \t]*(?<name>[-_.a-zA-Z0-9]+)").unwrap());
#[derive(Debug)]
enum CodingComment {
/// A UTF-8 encoding declaration.
UTF8(CodingCommentRange),
/// A declaration for any non utf8 encoding
OtherEncoding,
/// Any other comment
NoEncoding,
}
#[derive(Debug)]
struct CodingCommentRange {
comment: TextRange,
line: TextRange,
}
/// UP009
pub(crate) fn unnecessary_coding_comment(
context: &LintContext,
locator: &Locator,
comment_ranges: &CommentRanges,
) {
let mut iter = CodingCommentIterator::new(locator, comment_ranges)
.skip_while(|comment| matches!(comment, CodingComment::NoEncoding));
let Some(CodingComment::UTF8(range)) = iter.next() else {
return;
};
let line_index = locator.count_lines(TextRange::up_to(range.comment.start()));
// Comment must be on the first or second line
if line_index > 1 {
return;
}
// ```python
// # -*- coding: utf-8 -*-
// # -*- coding: latin-1 -*-
// ```
// or
// ```python
// # -*- coding: utf-8 -*-
// # comment
// # -*- coding: latin-1 -*-
// ```
if matches!(
(iter.next(), iter.next()),
(Some(CodingComment::OtherEncoding), _)
| (
Some(CodingComment::NoEncoding),
Some(CodingComment::OtherEncoding)
)
) {
return;
}
let fix = Fix::safe_edit(Edit::range_deletion(range.line));
if let Some(mut diagnostic) =
context.report_diagnostic_if_enabled(UTF8EncodingDeclaration, range.comment)
{
diagnostic.set_fix(fix);
}
}
struct CodingCommentIterator<'a> {
/// End offset of the last comment trivia or `None` if there
/// was any non-comment comment since the iterator started (e.g. a print statement)
last_trivia_end: Option<TextSize>,
locator: &'a Locator<'a>,
comments: std::slice::Iter<'a, TextRange>,
}
impl<'a> CodingCommentIterator<'a> {
fn new(locator: &'a Locator<'a>, comments: &'a CommentRanges) -> Self {
Self {
last_trivia_end: Some(locator.bom_start_offset()),
locator,
comments: comments.iter(),
}
}
}
impl Iterator for CodingCommentIterator<'_> {
type Item = CodingComment;
fn next(&mut self) -> Option<Self::Item> {
let comment = self.comments.next()?;
let line_range = self.locator.full_line_range(comment.start());
// If leading content is not whitespace then it's not a valid coding comment e.g.
// ```py
// print(x) # coding=utf8
// ```
// or
// ```python
// print(test)
// # -*- coding: utf-8 -*-
// ```
let last_trivia_end = self.last_trivia_end.take()?;
let before_hash_sign = self
.locator
.slice(TextRange::new(last_trivia_end, comment.start()));
if !before_hash_sign.trim().is_empty() {
return None;
}
self.last_trivia_end = Some(comment.end());
let result = if let Some(parts_of_interest) =
CODING_COMMENT_REGEX.captures(self.locator.slice(line_range))
{
let coding_name = parts_of_interest.name("name").unwrap();
match coding_name.as_str() {
"utf8" | "utf-8" => CodingComment::UTF8(CodingCommentRange {
comment: comment.range(),
line: line_range,
}),
_ => CodingComment::OtherEncoding,
}
} else {
CodingComment::NoEncoding
};
Some(result)
}
}
impl FusedIterator for CodingCommentIterator<'_> {}
| 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/pyupgrade/rules/deprecated_mock_import.rs | crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_mock_import.rs | use anyhow::Result;
use libcst_native::{
AsName, AssignTargetExpression, Attribute, Dot, Expression, Import, ImportAlias, ImportFrom,
ImportNames, Name, NameOrAttribute, ParenthesizableWhitespace,
};
use log::debug;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::UnqualifiedName;
use ruff_python_ast::whitespace::indentation;
use ruff_python_ast::{self as ast, Stmt};
use ruff_python_codegen::Stylist;
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::cst::matchers::{match_import, match_import_from, match_statement};
use crate::fix::codemods::CodegenStylist;
use crate::rules::pyupgrade::rules::is_import_required_by_isort;
use crate::{AlwaysFixableViolation, Edit, Fix};
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub(crate) enum MockReference {
Import,
Attribute,
}
/// ## What it does
/// Checks for imports of the `mock` module that should be replaced with
/// `unittest.mock`.
///
/// ## Why is this bad?
/// Since Python 3.3, `mock` has been a part of the standard library as
/// `unittest.mock`. The `mock` package is deprecated; use `unittest.mock`
/// instead.
///
/// ## Example
/// ```python
/// import mock
/// ```
///
/// Use instead:
/// ```python
/// from unittest import mock
/// ```
///
/// ## Options
///
/// This rule will not trigger if the `mock` import is required by the `isort` configuration.
///
/// - `lint.isort.required-imports`
///
/// ## References
/// - [Python documentation: `unittest.mock`](https://docs.python.org/3/library/unittest.mock.html)
/// - [PyPI: `mock`](https://pypi.org/project/mock/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.206")]
pub(crate) struct DeprecatedMockImport {
reference_type: MockReference,
}
impl AlwaysFixableViolation for DeprecatedMockImport {
#[derive_message_formats]
fn message(&self) -> String {
"`mock` is deprecated, use `unittest.mock`".to_string()
}
fn fix_title(&self) -> String {
let DeprecatedMockImport { reference_type } = self;
match reference_type {
MockReference::Import => "Import from `unittest.mock` instead".to_string(),
MockReference::Attribute => "Replace `mock.mock` with `mock`".to_string(),
}
}
}
/// Return a vector of all non-`mock` imports.
fn clean_import_aliases(aliases: Vec<ImportAlias>) -> (Vec<ImportAlias>, Vec<Option<AsName>>) {
// Preserve the trailing comma (or not) from the last entry.
let trailing_comma = aliases.last().and_then(|alias| alias.comma.clone());
let mut clean_aliases: Vec<ImportAlias> = vec![];
let mut mock_aliases: Vec<Option<AsName>> = vec![];
for alias in aliases {
match &alias.name {
// Ex) `import mock`
NameOrAttribute::N(name_struct) => {
if name_struct.value == "mock" {
mock_aliases.push(alias.asname.clone());
continue;
}
clean_aliases.push(alias);
}
// Ex) `import mock.mock`
NameOrAttribute::A(attribute_struct) => {
if let Expression::Name(name_struct) = &*attribute_struct.value {
if name_struct.value == "mock" && attribute_struct.attr.value == "mock" {
mock_aliases.push(alias.asname.clone());
continue;
}
}
clean_aliases.push(alias);
}
}
}
// But avoid destroying any trailing comments.
if let Some(alias) = clean_aliases.last_mut() {
let has_comment = if let Some(comma) = &alias.comma {
match &comma.whitespace_after {
ParenthesizableWhitespace::SimpleWhitespace(_) => false,
ParenthesizableWhitespace::ParenthesizedWhitespace(whitespace) => {
whitespace.first_line.comment.is_some()
}
}
} else {
false
};
if !has_comment {
alias.comma = trailing_comma;
}
}
(clean_aliases, mock_aliases)
}
fn format_mocks(aliases: Vec<Option<AsName>>, indent: &str, stylist: &Stylist) -> String {
let mut content = String::new();
for alias in aliases {
match alias {
None => {
if !content.is_empty() {
content.push_str(&stylist.line_ending());
content.push_str(indent);
}
content.push_str("from unittest import mock");
}
Some(as_name) => {
if let AssignTargetExpression::Name(name) = as_name.name {
if !content.is_empty() {
content.push_str(&stylist.line_ending());
content.push_str(indent);
}
content.push_str("from unittest import mock as ");
content.push_str(name.value);
}
}
}
}
content
}
/// Format the `import mock` rewrite.
fn format_import(
stmt: &Stmt,
indent: &str,
locator: &Locator,
stylist: &Stylist,
) -> Result<String> {
let module_text = locator.slice(stmt);
let mut tree = match_statement(module_text)?;
let import = match_import(&mut tree)?;
let Import { names, .. } = import.clone();
let (clean_aliases, mock_aliases) = clean_import_aliases(names);
Ok(if clean_aliases.is_empty() {
format_mocks(mock_aliases, indent, stylist)
} else {
import.names = clean_aliases;
let mut content = tree.codegen_stylist(stylist);
content.push_str(&stylist.line_ending());
content.push_str(indent);
content.push_str(&format_mocks(mock_aliases, indent, stylist));
content
})
}
/// Format the `from mock import ...` rewrite.
fn format_import_from(
stmt: &Stmt,
indent: &str,
locator: &Locator,
stylist: &Stylist,
) -> Result<String> {
let module_text = locator.slice(stmt);
let mut tree = match_statement(module_text).unwrap();
let import = match_import_from(&mut tree)?;
if let ImportFrom {
names: ImportNames::Star(..),
..
} = import
{
// Ex) `from mock import *`
import.module = Some(NameOrAttribute::A(Box::new(Attribute {
value: Box::new(Expression::Name(Box::new(Name {
value: "unittest",
lpar: vec![],
rpar: vec![],
}))),
attr: Name {
value: "mock",
lpar: vec![],
rpar: vec![],
},
dot: Dot {
whitespace_before: ParenthesizableWhitespace::default(),
whitespace_after: ParenthesizableWhitespace::default(),
},
lpar: vec![],
rpar: vec![],
})));
Ok(tree.codegen_stylist(stylist))
} else if let ImportFrom {
names: ImportNames::Aliases(aliases),
..
} = import
{
// Ex) `from mock import mock`
let (clean_aliases, mock_aliases) = clean_import_aliases(aliases.clone());
Ok(if clean_aliases.is_empty() {
format_mocks(mock_aliases, indent, stylist)
} else {
import.names = ImportNames::Aliases(clean_aliases);
import.module = Some(NameOrAttribute::A(Box::new(Attribute {
value: Box::new(Expression::Name(Box::new(Name {
value: "unittest",
lpar: vec![],
rpar: vec![],
}))),
attr: Name {
value: "mock",
lpar: vec![],
rpar: vec![],
},
dot: Dot {
whitespace_before: ParenthesizableWhitespace::default(),
whitespace_after: ParenthesizableWhitespace::default(),
},
lpar: vec![],
rpar: vec![],
})));
let mut content = tree.codegen_stylist(stylist);
if !mock_aliases.is_empty() {
content.push_str(&stylist.line_ending());
content.push_str(indent);
content.push_str(&format_mocks(mock_aliases, indent, stylist));
}
content
})
} else {
panic!("Expected ImportNames::Aliases | ImportNames::Star");
}
}
/// UP026
pub(crate) fn deprecated_mock_attribute(checker: &Checker, attribute: &ast::ExprAttribute) {
if !checker.semantic().seen_module(Modules::MOCK) {
return;
}
if UnqualifiedName::from_expr(&attribute.value)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["mock", "mock"]))
{
let mut diagnostic = checker.report_diagnostic(
DeprecatedMockImport {
reference_type: MockReference::Attribute,
},
attribute.value.range(),
);
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
"mock".to_string(),
attribute.value.range(),
)));
}
}
/// UP026
pub(crate) fn deprecated_mock_import(checker: &Checker, stmt: &Stmt) {
match stmt {
Stmt::Import(ast::StmtImport {
names,
range: _,
node_index: _,
}) => {
// Find all `mock` imports.
if names
.iter()
.any(|name| &name.name == "mock" || &name.name == "mock.mock")
{
// Generate the fix, if needed, which is shared between all `mock` imports.
let content = if let Some(indent) = indentation(checker.source(), stmt) {
match format_import(stmt, indent, checker.locator(), checker.stylist()) {
Ok(content) => Some(content),
Err(e) => {
debug!("Failed to rewrite `mock` import: {e}");
None
}
}
} else {
None
};
// Add a `Diagnostic` for each `mock` import.
for name in names {
if (&name.name == "mock" || &name.name == "mock.mock")
&& !is_import_required_by_isort(
&checker.settings().isort.required_imports,
stmt.into(),
name,
)
{
let mut diagnostic = checker.report_diagnostic(
DeprecatedMockImport {
reference_type: MockReference::Import,
},
name.range(),
);
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
if let Some(content) = content.as_ref() {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
content.clone(),
stmt.range(),
)));
}
}
}
}
}
Stmt::ImportFrom(ast::StmtImportFrom {
module: Some(module),
level,
names,
..
}) => {
if *level > 0 {
return;
}
if module == "mock" {
if names.iter().any(|alias| {
alias.name.as_str() == "mock"
&& is_import_required_by_isort(
&checker.settings().isort.required_imports,
stmt.into(),
alias,
)
}) {
return;
}
let mut diagnostic = checker.report_diagnostic(
DeprecatedMockImport {
reference_type: MockReference::Import,
},
stmt.range(),
);
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
if let Some(indent) = indentation(checker.source(), stmt) {
diagnostic.try_set_fix(|| {
format_import_from(stmt, indent, checker.locator(), checker.stylist())
.map(|content| Edit::range_replacement(content, stmt.range()))
.map(Fix::safe_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/pyupgrade/rules/unnecessary_builtin_import.rs | crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs | use itertools::Itertools;
use ruff_python_ast::{Alias, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix;
use crate::rules::pyupgrade::rules::is_import_required_by_isort;
use crate::{AlwaysFixableViolation, Fix};
/// ## What it does
/// Checks for unnecessary imports of builtins.
///
/// ## Why is this bad?
/// Builtins are always available. Importing them is unnecessary and should be
/// removed to avoid confusion.
///
/// ## Example
/// ```python
/// from builtins import str
///
/// str(1)
/// ```
///
/// Use instead:
/// ```python
/// str(1)
/// ```
///
/// ## Fix safety
/// This fix is marked as unsafe because removing the import
/// may change program behavior. For example, in the following
/// situation:
///
/// ```python
/// def str(x):
/// return x
///
///
/// from builtins import str
///
/// str(1) # `"1"` with the import, `1` without
/// ```
///
/// ## Options
///
/// This rule will not trigger on imports required by the `isort` configuration.
///
/// - `lint.isort.required-imports`
///
/// ## References
/// - [Python documentation: The Python Standard Library](https://docs.python.org/3/library/index.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.211")]
pub(crate) struct UnnecessaryBuiltinImport {
pub names: Vec<String>,
}
impl AlwaysFixableViolation for UnnecessaryBuiltinImport {
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryBuiltinImport { names } = self;
if names.len() == 1 {
let import = &names[0];
format!("Unnecessary builtin import: `{import}`")
} else {
let imports = names.iter().map(|name| format!("`{name}`")).join(", ");
format!("Unnecessary builtin imports: {imports}")
}
}
fn fix_title(&self) -> String {
"Remove unnecessary builtin import".to_string()
}
}
/// UP029
pub(crate) fn unnecessary_builtin_import(
checker: &Checker,
stmt: &Stmt,
module: &str,
names: &[Alias],
level: u32,
) {
// Ignore relative imports (they're importing from local modules, not Python's builtins).
if level > 0 {
return;
}
// Ignore irrelevant modules.
if !matches!(
module,
"builtins" | "io" | "six" | "six.moves" | "six.moves.builtins"
) {
return;
}
// Identify unaliased, builtin imports.
let unused_imports: Vec<&Alias> = names
.iter()
.filter(|alias| {
!is_import_required_by_isort(
&checker.settings().isort.required_imports,
stmt.into(),
alias,
)
})
.filter(|alias| alias.asname.is_none())
.filter(|alias| {
matches!(
(module, alias.name.as_str()),
(
"builtins" | "six.moves.builtins",
"*" | "ascii"
| "bytes"
| "chr"
| "dict"
| "filter"
| "hex"
| "input"
| "int"
| "isinstance"
| "list"
| "map"
| "max"
| "min"
| "next"
| "object"
| "oct"
| "open"
| "pow"
| "range"
| "round"
| "str"
| "super"
| "zip"
) | ("io", "open")
| ("six", "callable" | "next")
| ("six.moves", "filter" | "input" | "map" | "range" | "zip")
)
})
.collect();
if unused_imports.is_empty() {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryBuiltinImport {
names: unused_imports
.iter()
.map(|alias| alias.name.to_string())
.sorted()
.collect(),
},
stmt.range(),
);
diagnostic.try_set_fix(|| {
let statement = checker.semantic().current_statement();
let parent = checker.semantic().current_statement_parent();
let edit = fix::edits::remove_unused_imports(
unused_imports
.iter()
.map(|alias| &alias.name)
.map(ruff_python_ast::Identifier::as_str),
statement,
parent,
checker.locator(),
checker.stylist(),
checker.indexer(),
)?;
Ok(Fix::unsafe_edit(edit).isolate(Checker::isolation(
checker.semantic().current_statement_parent_id(),
)))
});
}
| 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/pyupgrade/rules/type_of_primitive.rs | crates/ruff_linter/src/rules/pyupgrade/rules/type_of_primitive.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::Expr;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::pad;
use crate::{Edit, Fix, FixAvailability, Violation};
use crate::rules::pyupgrade::types::Primitive;
/// ## What it does
/// Checks for uses of `type` that take a primitive as an argument.
///
/// ## Why is this bad?
/// `type()` returns the type of a given object. A type of a primitive can
/// always be known in advance and accessed directly, which is more concise
/// and explicit than using `type()`.
///
/// ## Example
/// ```python
/// type(1)
/// ```
///
/// Use instead:
/// ```python
/// int
/// ```
///
/// ## References
/// - [Python documentation: `type()`](https://docs.python.org/3/library/functions.html#type)
/// - [Python documentation: Built-in types](https://docs.python.org/3/library/stdtypes.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct TypeOfPrimitive {
primitive: Primitive,
}
impl Violation for TypeOfPrimitive {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let TypeOfPrimitive { primitive } = self;
format!("Use `{}` instead of `type(...)`", primitive.builtin())
}
fn fix_title(&self) -> Option<String> {
let TypeOfPrimitive { primitive } = self;
Some(format!(
"Replace `type(...)` with `{}`",
primitive.builtin()
))
}
}
/// UP003
pub(crate) fn type_of_primitive(checker: &Checker, expr: &Expr, func: &Expr, args: &[Expr]) {
let [arg] = args else {
return;
};
let Some(primitive) = Primitive::from_expr(arg) else {
return;
};
let semantic = checker.semantic();
if !semantic.match_builtin_expr(func, "type") {
return;
}
let mut diagnostic = checker.report_diagnostic(TypeOfPrimitive { primitive }, expr.range());
let builtin = primitive.builtin();
if semantic.has_builtin_binding(&builtin) {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
pad(primitive.builtin(), expr.range(), checker.locator()),
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/pyupgrade/rules/deprecated_unittest_alias.rs | crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs | use ruff_python_ast::{self as ast, Expr};
use rustc_hash::FxHashMap;
use std::sync::LazyLock;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of deprecated methods from the `unittest` module.
///
/// ## Why is this bad?
/// The `unittest` module has deprecated aliases for some of its methods.
/// The deprecated aliases were removed in Python 3.12. Instead of aliases,
/// use their non-deprecated counterparts.
///
/// ## Example
/// ```python
/// from unittest import TestCase
///
///
/// class SomeTest(TestCase):
/// def test_something(self):
/// self.assertEquals(1, 1)
/// ```
///
/// Use instead:
/// ```python
/// from unittest import TestCase
///
///
/// class SomeTest(TestCase):
/// def test_something(self):
/// self.assertEqual(1, 1)
/// ```
///
/// ## References
/// - [Python 3.11 documentation: Deprecated aliases](https://docs.python.org/3.11/library/unittest.html#deprecated-aliases)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct DeprecatedUnittestAlias {
alias: String,
target: String,
}
impl AlwaysFixableViolation for DeprecatedUnittestAlias {
#[derive_message_formats]
fn message(&self) -> String {
let DeprecatedUnittestAlias { alias, target } = self;
format!("`{alias}` is deprecated, use `{target}`")
}
fn fix_title(&self) -> String {
let DeprecatedUnittestAlias { alias, target } = self;
format!("Replace `{target}` with `{alias}`")
}
}
static DEPRECATED_ALIASES: LazyLock<FxHashMap<&'static str, &'static str>> = LazyLock::new(|| {
FxHashMap::from_iter([
("assertAlmostEquals", "assertAlmostEqual"),
("assertEquals", "assertEqual"),
("assertNotAlmostEquals", "assertNotAlmostEqual"),
("assertNotEquals", "assertNotEqual"),
("assertNotRegexpMatches", "assertNotRegex"),
("assertRaisesRegexp", "assertRaisesRegex"),
("assertRegexpMatches", "assertRegex"),
("assert_", "assertTrue"),
("failIf", "assertFalse"),
("failIfAlmostEqual", "assertNotAlmostEqual"),
("failIfEqual", "assertNotEqual"),
("failUnless", "assertTrue"),
("failUnlessAlmostEqual", "assertAlmostEqual"),
("failUnlessEqual", "assertEqual"),
("failUnlessRaises", "assertRaises"),
])
});
/// UP005
pub(crate) fn deprecated_unittest_alias(checker: &Checker, expr: &Expr) {
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = expr else {
return;
};
let Some(target) = DEPRECATED_ALIASES.get(attr.as_str()) else {
return;
};
let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() else {
return;
};
if id != "self" {
return;
}
let mut diagnostic = checker.report_diagnostic(
DeprecatedUnittestAlias {
alias: attr.to_string(),
target: (*target).to_string(),
},
expr.range(),
);
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
format!("self.{target}"),
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/pyupgrade/rules/super_call_with_parameters.rs | crates/ruff_linter/src/rules/pyupgrade/rules/super_call_with_parameters.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::visitor::{Visitor, walk_expr, walk_stmt};
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::{Ranged, TextSize};
use crate::checkers::ast::Checker;
use crate::preview::is_safe_super_call_with_parameters_fix_enabled;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `super` calls that pass redundant arguments.
///
/// ## Why is this bad?
/// In Python 3, `super` can be invoked without any arguments when: (1) the
/// first argument is `__class__`, and (2) the second argument is equivalent to
/// the first argument of the enclosing method.
///
/// When possible, omit the arguments to `super` to make the code more concise
/// and maintainable.
///
/// ## Example
/// ```python
/// class A:
/// def foo(self):
/// pass
///
///
/// class B(A):
/// def bar(self):
/// super(B, self).foo()
/// ```
///
/// Use instead:
/// ```python
/// class A:
/// def foo(self):
/// pass
///
///
/// class B(A):
/// def bar(self):
/// super().foo()
/// ```
///
/// ## Fix safety
///
/// This rule's fix is marked as unsafe because removing the arguments from a call
/// may delete comments that are attached to the arguments.
///
/// In [preview], the fix is marked safe if no comments are present.
///
/// [preview]: https://docs.astral.sh/ruff/preview/
///
/// ## References
/// - [Python documentation: `super`](https://docs.python.org/3/library/functions.html#super)
/// - [super/MRO, Python's most misunderstood feature.](https://www.youtube.com/watch?v=X1PQ7zzltz4)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct SuperCallWithParameters;
impl Violation for SuperCallWithParameters {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use `super()` instead of `super(__class__, self)`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Remove `super()` parameters".to_string())
}
}
/// UP008
pub(crate) fn super_call_with_parameters(checker: &Checker, call: &ast::ExprCall) {
// Only bother going through the super check at all if we're in a `super` call.
// (We check this in `super_args` too, so this is just an optimization.)
if !is_super_call_with_arguments(call, checker) {
return;
}
let scope = checker.semantic().current_scope();
// Check: are we in a Function scope?
if !scope.kind.is_function() {
return;
}
let mut parents = checker.semantic().current_statements();
// For a `super` invocation to be unnecessary, the first argument needs to match
// the enclosing class, and the second argument needs to match the first
// argument to the enclosing function.
let [first_arg, second_arg] = &*call.arguments.args else {
return;
};
// Find the enclosing function definition (if any).
let Some(
func_stmt @ Stmt::FunctionDef(ast::StmtFunctionDef {
parameters: parent_parameters,
..
}),
) = parents.find(|stmt| stmt.is_function_def_stmt())
else {
return;
};
if is_builtins_super(checker.semantic(), call)
&& !has_local_dunder_class_var_ref(checker.semantic(), func_stmt)
{
return;
}
// Extract the name of the first argument to the enclosing function.
let Some(parent_arg) = parent_parameters.args.first() else {
return;
};
// Find the enclosing class definition (if any).
let Some(Stmt::ClassDef(ast::StmtClassDef {
name: parent_name,
decorator_list,
..
})) = parents.find(|stmt| stmt.is_class_def_stmt())
else {
return;
};
let (
Expr::Name(ast::ExprName {
id: first_arg_id, ..
}),
Expr::Name(ast::ExprName {
id: second_arg_id, ..
}),
) = (first_arg, second_arg)
else {
return;
};
// The `super(__class__, self)` and `super(ParentClass, self)` patterns are redundant in Python 3
// when the first argument refers to the implicit `__class__` cell or to the enclosing class.
// Avoid triggering if a local variable shadows either name.
if !(((first_arg_id == "__class__") || (first_arg_id == parent_name.as_str()))
&& !checker.semantic().current_scope().has(first_arg_id)
&& second_arg_id == parent_arg.name().as_str())
{
return;
}
drop(parents);
// If the class is an `@dataclass` with `slots=True`, calling `super()` without arguments raises
// a `TypeError`.
//
// See: https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass
if decorator_list.iter().any(|decorator| {
let Expr::Call(ast::ExprCall {
func, arguments, ..
}) = &decorator.expression
else {
return false;
};
if checker
.semantic()
.resolve_qualified_name(func)
.is_some_and(|name| name.segments() == ["dataclasses", "dataclass"])
{
arguments.find_keyword("slots").is_some_and(|keyword| {
matches!(
keyword.value,
Expr::BooleanLiteral(ast::ExprBooleanLiteral { value: true, .. })
)
})
} else {
false
}
}) {
return;
}
let mut diagnostic = checker.report_diagnostic(SuperCallWithParameters, call.arguments.range());
// Only provide a fix if there are no keyword arguments, since super() doesn't accept keyword arguments
if call.arguments.keywords.is_empty() {
let applicability = if !checker.comment_ranges().intersects(call.arguments.range())
&& is_safe_super_call_with_parameters_fix_enabled(checker.settings())
{
Applicability::Safe
} else {
Applicability::Unsafe
};
diagnostic.set_fix(Fix::applicable_edit(
Edit::deletion(
call.arguments.start() + TextSize::new(1),
call.arguments.end() - TextSize::new(1),
),
applicability,
));
}
}
/// Returns `true` if a call is an argumented `super` invocation.
fn is_super_call_with_arguments(call: &ast::ExprCall, checker: &Checker) -> bool {
checker.semantic().match_builtin_expr(&call.func, "super") && !call.arguments.is_empty()
}
/// Returns `true` if the function contains load references to `__class__` or `super` without
/// local binding.
///
/// This indicates that the function relies on the implicit `__class__` cell variable created by
/// Python when `super()` is called without arguments, making it unsafe to remove `super()` parameters.
fn has_local_dunder_class_var_ref(semantic: &SemanticModel, func_stmt: &Stmt) -> bool {
if semantic.current_scope().has("__class__") {
return false;
}
let mut finder = ClassCellReferenceFinder::new();
finder.visit_stmt(func_stmt);
finder.found()
}
/// Returns `true` if the call is to the built-in `builtins.super` function.
fn is_builtins_super(semantic: &SemanticModel, call: &ast::ExprCall) -> bool {
semantic
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["builtins", "super"]))
}
/// A [`Visitor`] that searches for implicit reference to `__class__` cell,
/// excluding nested class definitions.
#[derive(Debug)]
struct ClassCellReferenceFinder {
has_class_cell: bool,
}
impl ClassCellReferenceFinder {
pub(crate) fn new() -> Self {
ClassCellReferenceFinder {
has_class_cell: false,
}
}
pub(crate) fn found(&self) -> bool {
self.has_class_cell
}
}
impl<'a> Visitor<'a> for ClassCellReferenceFinder {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt {
Stmt::ClassDef(_) => {}
_ => {
if !self.has_class_cell {
walk_stmt(self, stmt);
}
}
}
}
fn visit_expr(&mut self, expr: &'a Expr) {
if expr.as_name_expr().is_some_and(|name| {
matches!(name.id.as_str(), "super" | "__class__") && name.ctx.is_load()
}) {
self.has_class_cell = true;
return;
}
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/pyupgrade/rules/pep695/non_pep695_type_alias.rs | crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_type_alias.rs | use itertools::Itertools;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::Name;
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{Expr, ExprCall, ExprName, Keyword, StmtAnnAssign, StmtAssign, StmtRef};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::preview::is_type_var_default_enabled;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
use ruff_python_ast::PythonVersion;
use super::{
DisplayTypeVars, TypeParamKind, TypeVar, TypeVarReferenceVisitor, expr_name_to_type_var,
};
/// ## What it does
/// Checks for use of `TypeAlias` annotations and `TypeAliasType` assignments
/// for declaring type aliases.
///
/// ## Why is this bad?
/// The `type` keyword was introduced in Python 3.12 by [PEP 695] for defining
/// type aliases. The `type` keyword is easier to read and provides cleaner
/// support for generics.
///
/// ## Known problems
/// [PEP 695] uses inferred variance for type parameters, instead of the
/// `covariant` and `contravariant` keywords used by `TypeVar` variables. As
/// such, rewriting a type alias using a PEP-695 `type` statement may change
/// the variance of the alias's type parameters.
///
/// Unlike type aliases that use simple assignments, definitions created using
/// [PEP 695] `type` statements cannot be used as drop-in replacements at
/// runtime for the value on the right-hand side of the statement. This means
/// that while for some simple old-style type aliases you can use them as the
/// second argument to an `isinstance()` call (for example), doing the same
/// with a [PEP 695] `type` statement will always raise `TypeError` at
/// runtime.
///
/// ## Example
/// ```python
/// from typing import Annotated, TypeAlias, TypeAliasType
/// from annotated_types import Gt
///
/// ListOfInt: TypeAlias = list[int]
/// PositiveInt = TypeAliasType("PositiveInt", Annotated[int, Gt(0)])
/// ```
///
/// Use instead:
/// ```python
/// from typing import Annotated
/// from annotated_types import Gt
///
/// type ListOfInt = list[int]
/// type PositiveInt = Annotated[int, Gt(0)]
/// ```
///
/// ## Fix safety
///
/// This fix is marked unsafe for `TypeAlias` assignments outside of stub files because of the
/// runtime behavior around `isinstance()` calls noted above. The fix is also unsafe for
/// `TypeAliasType` assignments if there are any comments in the replacement range that would be
/// deleted.
///
/// ## See also
///
/// This rule only applies to `TypeAlias`es and `TypeAliasType`s. See
/// [`non-pep695-generic-class`][UP046] and [`non-pep695-generic-function`][UP047] for similar
/// transformations for generic classes and functions.
///
/// This rule replaces standalone type variables in aliases but doesn't remove the corresponding
/// type variables even if they are unused after the fix. See [`unused-private-type-var`][PYI018]
/// for a rule to clean up unused private type variables.
///
/// This rule will not rename private type variables to remove leading underscores, even though the
/// new type parameters are restricted in scope to their associated aliases. See
/// [`private-type-parameter`][UP049] for a rule to update these names.
///
/// ## Options
///
/// - `target-version`
///
/// [PEP 695]: https://peps.python.org/pep-0695/
/// [PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var/
/// [UP046]: https://docs.astral.sh/ruff/rules/non-pep695-generic-class/
/// [UP047]: https://docs.astral.sh/ruff/rules/non-pep695-generic-function/
/// [UP049]: https://docs.astral.sh/ruff/rules/private-type-parameter/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.283")]
pub(crate) struct NonPEP695TypeAlias {
name: String,
type_alias_kind: TypeAliasKind,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum TypeAliasKind {
TypeAlias,
TypeAliasType,
}
impl Violation for NonPEP695TypeAlias {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always;
#[derive_message_formats]
fn message(&self) -> String {
let NonPEP695TypeAlias {
name,
type_alias_kind,
} = self;
let type_alias_method = match type_alias_kind {
TypeAliasKind::TypeAlias => "`TypeAlias` annotation",
TypeAliasKind::TypeAliasType => "`TypeAliasType` assignment",
};
format!("Type alias `{name}` uses {type_alias_method} instead of the `type` keyword")
}
fn fix_title(&self) -> Option<String> {
Some("Use the `type` keyword".to_string())
}
}
/// UP040
pub(crate) fn non_pep695_type_alias_type(checker: &Checker, stmt: &StmtAssign) {
if checker.target_version() < PythonVersion::PY312 {
return;
}
let StmtAssign { targets, value, .. } = stmt;
let Expr::Call(ExprCall {
func, arguments, ..
}) = value.as_ref()
else {
return;
};
let [Expr::Name(target_name)] = targets.as_slice() else {
return;
};
let [Expr::StringLiteral(name), value] = arguments.args.as_ref() else {
return;
};
if &name.value != target_name.id.as_str() {
return;
}
let type_params = match arguments.keywords.as_ref() {
[] => &[],
[
Keyword {
arg: Some(name),
value: Expr::Tuple(type_params),
..
},
] if name.as_str() == "type_params" => type_params.elts.as_slice(),
_ => return,
};
if !checker
.semantic()
.match_typing_expr(func.as_ref(), "TypeAliasType")
{
return;
}
let Some(vars) = type_params
.iter()
.map(|expr| {
expr.as_name_expr().map(|name| {
expr_name_to_type_var(checker.semantic(), name).unwrap_or(TypeVar {
name: &name.id,
restriction: None,
kind: TypeParamKind::TypeVar,
default: None,
})
})
})
.collect::<Option<Vec<_>>>()
else {
return;
};
create_diagnostic(
checker,
stmt.into(),
&target_name.id,
value,
&vars,
TypeAliasKind::TypeAliasType,
);
}
/// UP040
pub(crate) fn non_pep695_type_alias(checker: &Checker, stmt: &StmtAnnAssign) {
if checker.target_version() < PythonVersion::PY312 {
return;
}
let StmtAnnAssign {
target,
annotation,
value,
..
} = stmt;
if !checker
.semantic()
.match_typing_expr(annotation, "TypeAlias")
{
return;
}
let Expr::Name(ExprName { id: name, .. }) = target.as_ref() else {
return;
};
let Some(value) = value else {
return;
};
let vars = {
let mut visitor = TypeVarReferenceVisitor {
vars: vec![],
semantic: checker.semantic(),
any_skipped: false,
};
visitor.visit_expr(value);
visitor.vars
};
// Type variables must be unique; filter while preserving order.
let vars = vars
.into_iter()
.unique_by(|tvar| tvar.name)
.collect::<Vec<_>>();
// Skip if any TypeVar has defaults and preview mode is not enabled
if vars.iter().any(|tv| tv.default.is_some())
&& !is_type_var_default_enabled(checker.settings())
{
return;
}
create_diagnostic(
checker,
stmt.into(),
name,
value,
&vars,
TypeAliasKind::TypeAlias,
);
}
/// Generate a [`Diagnostic`] for a non-PEP 695 type alias or type alias type.
fn create_diagnostic(
checker: &Checker,
stmt: StmtRef,
name: &Name,
value: &Expr,
type_vars: &[TypeVar],
type_alias_kind: TypeAliasKind,
) {
let source = checker.source();
let tokens = checker.tokens();
let comment_ranges = checker.comment_ranges();
let range_with_parentheses =
parenthesized_range(value.into(), stmt.into(), tokens).unwrap_or(value.range());
let content = format!(
"type {name}{type_params} = {value}",
type_params = DisplayTypeVars { type_vars, source },
value = &source[range_with_parentheses]
);
let edit = Edit::range_replacement(content, stmt.range());
let applicability =
if type_alias_kind == TypeAliasKind::TypeAlias && !checker.source_type.is_stub() {
// The fix is always unsafe in non-stubs
// because new-style aliases have different runtime behavior.
// See https://github.com/astral-sh/ruff/issues/6434
Applicability::Unsafe
} else {
// In stub files, or in non-stub files for `TypeAliasType` assignments,
// the fix is only unsafe if it would delete comments.
//
// it would be easier to check for comments in the whole `stmt.range`, but because
// `create_diagnostic` uses the full source text of `value`, comments within `value` are
// actually preserved. thus, we have to check for comments in `stmt` but outside of `value`
let pre_value = TextRange::new(stmt.start(), range_with_parentheses.start());
let post_value = TextRange::new(range_with_parentheses.end(), stmt.end());
if comment_ranges.intersects(pre_value) || comment_ranges.intersects(post_value) {
Applicability::Unsafe
} else {
Applicability::Safe
}
};
checker
.report_diagnostic(
NonPEP695TypeAlias {
name: name.to_string(),
type_alias_kind,
},
stmt.range(),
)
.set_fix(Fix::applicable_edit(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/pyupgrade/rules/pep695/non_pep695_generic_class.rs | crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_class.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{ExprSubscript, StmtClassDef};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::{Edit, Fix, FixAvailability, Violation};
use ruff_python_ast::PythonVersion;
use super::{
DisplayTypeVars, TypeVarReferenceVisitor, check_type_vars, find_generic, in_nested_context,
};
/// ## What it does
///
/// Checks for use of standalone type variables and parameter specifications in generic classes.
///
/// ## Why is this bad?
///
/// Special type parameter syntax was introduced in Python 3.12 by [PEP 695] for defining generic
/// classes. This syntax is easier to read and provides cleaner support for generics.
///
/// ## Known problems
///
/// The rule currently skips generic classes nested inside of other functions or classes. It also
/// skips type parameters with the `default` argument introduced in [PEP 696] and implemented in
/// Python 3.13.
///
/// This rule can only offer a fix if all of the generic types in the class definition are defined
/// in the current module. For external type parameters, a diagnostic is emitted without a suggested
/// fix.
///
/// Not all type checkers fully support PEP 695 yet, so even valid fixes suggested by this rule may
/// cause type checking to [fail].
///
/// ## Fix safety
///
/// This fix is marked as unsafe, as [PEP 695] uses inferred variance for type parameters, instead
/// of the `covariant` and `contravariant` keywords used by `TypeVar` variables. As such, replacing
/// a `TypeVar` variable with an inline type parameter may change its variance.
///
/// ## Example
///
/// ```python
/// from typing import Generic, TypeVar
///
/// T = TypeVar("T")
///
///
/// class GenericClass(Generic[T]):
/// var: T
/// ```
///
/// Use instead:
///
/// ```python
/// class GenericClass[T]:
/// var: T
/// ```
///
/// ## See also
///
/// This rule replaces standalone type variables in classes but doesn't remove
/// the corresponding type variables even if they are unused after the fix. See
/// [`unused-private-type-var`][PYI018] for a rule to clean up unused
/// private type variables.
///
/// This rule will not rename private type variables to remove leading underscores, even though the
/// new type parameters are restricted in scope to their associated class. See
/// [`private-type-parameter`][UP049] for a rule to update these names.
///
/// This rule will correctly handle classes with multiple base classes, as long as the single
/// `Generic` base class is at the end of the argument list, as checked by
/// [`generic-not-last-base-class`][PYI059]. If a `Generic` base class is
/// found outside of the last position, a diagnostic is emitted without a suggested fix.
///
/// This rule only applies to generic classes and does not include generic functions. See
/// [`non-pep695-generic-function`][UP047] for the function version.
///
/// ## Options
///
/// - `target-version`
///
/// [PEP 695]: https://peps.python.org/pep-0695/
/// [PEP 696]: https://peps.python.org/pep-0696/
/// [PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var/
/// [PYI059]: https://docs.astral.sh/ruff/rules/generic-not-last-base-class/
/// [UP047]: https://docs.astral.sh/ruff/rules/non-pep695-generic-function/
/// [UP049]: https://docs.astral.sh/ruff/rules/private-type-parameter/
/// [fail]: https://github.com/python/mypy/issues/18507
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct NonPEP695GenericClass {
name: String,
}
impl Violation for NonPEP695GenericClass {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let NonPEP695GenericClass { name } = self;
format!("Generic class `{name}` uses `Generic` subclass instead of type parameters")
}
fn fix_title(&self) -> Option<String> {
Some("Use type parameters".to_string())
}
}
/// UP046
pub(crate) fn non_pep695_generic_class(checker: &Checker, class_def: &StmtClassDef) {
// PEP-695 syntax is only available on Python 3.12+
if checker.target_version() < PythonVersion::PY312 {
return;
}
// don't try to handle generic classes inside other functions or classes
if in_nested_context(checker) {
return;
}
let StmtClassDef {
name,
type_params,
arguments,
..
} = class_def;
// it's a runtime error to mix type_params and Generic, so bail out early if we see existing
// type_params
if type_params.is_some() {
return;
}
let Some(arguments) = arguments.as_ref() else {
return;
};
let Some((generic_idx, generic_expr @ ExprSubscript { slice, range, .. })) =
find_generic(arguments, checker.semantic())
else {
return;
};
let mut diagnostic = checker.report_diagnostic(
NonPEP695GenericClass {
name: name.to_string(),
},
*range,
);
// only handle the case where Generic is at the end of the argument list, in line with PYI059
// (generic-not-last-base-class). If it comes elsewhere, it results in a runtime error. In stubs
// it's not *strictly* necessary for `Generic` to come last in the bases tuple, but it would
// cause more complication for us to handle stubs specially, and probably isn't worth the
// bother. we still offer a diagnostic here but not a fix
//
// because `find_generic` also finds the *first* Generic argument, this has the additional
// benefit of bailing out with a diagnostic if multiple Generic arguments are present
if generic_idx != arguments.len() - 1 {
return;
}
let mut visitor = TypeVarReferenceVisitor {
vars: vec![],
semantic: checker.semantic(),
any_skipped: false,
};
visitor.visit_expr(slice);
// if any of the parameters have been skipped, this indicates that we could not resolve the type
// to a `TypeVar`, `TypeVarTuple`, or `ParamSpec`, and thus our fix would remove it from the
// signature incorrectly. We can still offer the diagnostic created above without a Fix. For
// example,
//
// ```python
// from somewhere import SomethingElse
//
// T = TypeVar("T")
//
// class Class(Generic[T, SomethingElse]): ...
// ```
//
// should not be converted to
//
// ```python
// class Class[T]: ...
// ```
//
// just because we can't confirm that `SomethingElse` is a `TypeVar`
if !visitor.any_skipped {
let Some(type_vars) = check_type_vars(visitor.vars, checker) else {
diagnostic.defuse();
return;
};
// build the fix as a String to avoid removing comments from the entire function body
let type_params = DisplayTypeVars {
type_vars: &type_vars,
source: checker.source(),
};
diagnostic.try_set_fix(|| {
let removal_edit = remove_argument(
generic_expr,
arguments,
Parentheses::Remove,
checker.source(),
checker.tokens(),
)?;
Ok(Fix::unsafe_edits(
Edit::insertion(type_params.to_string(), name.end()),
[removal_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/pyupgrade/rules/pep695/non_pep695_generic_function.rs | crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_function.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::StmtFunctionDef;
use ruff_python_ast::visitor::Visitor;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
use ruff_python_ast::PythonVersion;
use super::{DisplayTypeVars, TypeVarReferenceVisitor, check_type_vars, in_nested_context};
/// ## What it does
///
/// Checks for use of standalone type variables and parameter specifications in generic functions.
///
/// ## Why is this bad?
///
/// Special type parameter syntax was introduced in Python 3.12 by [PEP 695] for defining generic
/// functions. This syntax is easier to read and provides cleaner support for generics.
///
/// ## Known problems
///
/// The rule currently skips generic functions nested inside of other functions or classes and those
/// with type parameters containing the `default` argument introduced in [PEP 696] and implemented
/// in Python 3.13.
///
/// Not all type checkers fully support PEP 695 yet, so even valid fixes suggested by this rule may
/// cause type checking to [fail].
///
/// ## Fix safety
///
/// This fix is marked unsafe, as [PEP 695] uses inferred variance for type parameters, instead of
/// the `covariant` and `contravariant` keywords used by `TypeVar` variables. As such, replacing a
/// `TypeVar` variable with an inline type parameter may change its variance.
///
/// Additionally, if the rule cannot determine whether a parameter annotation corresponds to a type
/// variable (e.g. for a type imported from another module), it will not add the type to the generic
/// type parameter list. This causes the function to have a mix of old-style type variables and
/// new-style generic type parameters, which will be rejected by type checkers.
///
/// ## Example
///
/// ```python
/// from typing import TypeVar
///
/// T = TypeVar("T")
///
///
/// def generic_function(var: T) -> T:
/// return var
/// ```
///
/// Use instead:
///
/// ```python
/// def generic_function[T](var: T) -> T:
/// return var
/// ```
///
/// ## See also
///
/// This rule replaces standalone type variables in function signatures but doesn't remove
/// the corresponding type variables even if they are unused after the fix. See
/// [`unused-private-type-var`][PYI018] for a rule to clean up unused
/// private type variables.
///
/// This rule will not rename private type variables to remove leading underscores, even though the
/// new type parameters are restricted in scope to their associated function. See
/// [`private-type-parameter`][UP049] for a rule to update these names.
///
/// This rule only applies to generic functions and does not include generic classes. See
/// [`non-pep695-generic-class`][UP046] for the class version.
///
/// ## Options
///
/// - `target-version`
///
/// [PEP 695]: https://peps.python.org/pep-0695/
/// [PEP 696]: https://peps.python.org/pep-0696/
/// [PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var/
/// [UP046]: https://docs.astral.sh/ruff/rules/non-pep695-generic-class/
/// [UP049]: https://docs.astral.sh/ruff/rules/private-type-parameter/
/// [fail]: https://github.com/python/mypy/issues/18507
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct NonPEP695GenericFunction {
name: String,
}
impl Violation for NonPEP695GenericFunction {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always;
#[derive_message_formats]
fn message(&self) -> String {
let NonPEP695GenericFunction { name } = self;
format!("Generic function `{name}` should use type parameters")
}
fn fix_title(&self) -> Option<String> {
Some("Use type parameters".to_string())
}
}
/// UP047
pub(crate) fn non_pep695_generic_function(checker: &Checker, function_def: &StmtFunctionDef) {
// PEP-695 syntax is only available on Python 3.12+
if checker.target_version() < PythonVersion::PY312 {
return;
}
// don't try to handle generic functions inside other functions or classes
if in_nested_context(checker) {
return;
}
let StmtFunctionDef {
name,
type_params,
parameters,
..
} = function_def;
// TODO(brent) handle methods, for now return early in a class body. For example, an additional
// generic parameter on the method needs to be handled separately from one already on the class
//
// ```python
// T = TypeVar("T")
// S = TypeVar("S")
//
// class Foo(Generic[T]):
// def bar(self, x: T, y: S) -> S: ...
//
//
// class Foo[T]:
// def bar[S](self, x: T, y: S) -> S: ...
// ```
if checker.semantic().current_scope().kind.is_class() {
return;
}
// invalid to mix old-style and new-style generics
if type_params.is_some() {
return;
}
let mut type_vars = Vec::new();
for parameter in parameters {
if let Some(annotation) = parameter.annotation() {
let vars = {
let mut visitor = TypeVarReferenceVisitor {
vars: vec![],
semantic: checker.semantic(),
any_skipped: false,
};
visitor.visit_expr(annotation);
visitor.vars
};
type_vars.extend(vars);
}
}
let Some(type_vars) = check_type_vars(type_vars, checker) else {
return;
};
// build the fix as a String to avoid removing comments from the entire function body
let type_params = DisplayTypeVars {
type_vars: &type_vars,
source: checker.source(),
};
checker
.report_diagnostic(
NonPEP695GenericFunction {
name: name.to_string(),
},
TextRange::new(name.start(), parameters.end()),
)
.set_fix(Fix::unsafe_edit(Edit::insertion(
type_params.to_string(),
name.end(),
)));
}
| 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/pyupgrade/rules/pep695/mod.rs | crates/ruff_linter/src/rules/pyupgrade/rules/pep695/mod.rs | //! Shared code for [`non_pep695_type_alias`] (UP040),
//! [`non_pep695_generic_class`] (UP046), and [`non_pep695_generic_function`]
//! (UP047)
use std::fmt::Display;
use itertools::Itertools;
use ruff_python_ast::{
self as ast, Arguments, Expr, ExprCall, ExprName, ExprSubscript, Identifier, PythonVersion,
Stmt, StmtAssign, TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple,
name::Name,
visitor::{self, Visitor},
};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::preview::is_type_var_default_enabled;
pub(crate) use non_pep695_generic_class::*;
pub(crate) use non_pep695_generic_function::*;
pub(crate) use non_pep695_type_alias::*;
pub(crate) use private_type_parameter::*;
mod non_pep695_generic_class;
mod non_pep695_generic_function;
mod non_pep695_type_alias;
mod private_type_parameter;
#[derive(Debug)]
pub(crate) enum TypeVarRestriction<'a> {
/// A type variable with a bound, e.g., `TypeVar("T", bound=int)`.
Bound(&'a Expr),
/// A type variable with constraints, e.g., `TypeVar("T", int, str)`.
Constraint(Vec<&'a Expr>),
/// `AnyStr` is a special case: the only public `TypeVar` defined in the standard library,
/// and thus the only one that we recognise when imported from another module.
AnyStr,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum TypeParamKind {
TypeVar,
TypeVarTuple,
ParamSpec,
}
#[derive(Debug)]
pub(crate) struct TypeVar<'a> {
pub(crate) name: &'a str,
pub(crate) restriction: Option<TypeVarRestriction<'a>>,
pub(crate) kind: TypeParamKind,
pub(crate) default: Option<&'a Expr>,
}
/// Wrapper for formatting a sequence of [`TypeVar`]s for use as a generic type parameter (e.g. `[T,
/// *Ts, **P]`). See [`DisplayTypeVar`] for further details.
pub(crate) struct DisplayTypeVars<'a> {
pub(crate) type_vars: &'a [TypeVar<'a>],
pub(crate) source: &'a str,
}
impl Display for DisplayTypeVars<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let nvars = self.type_vars.len();
if nvars == 0 {
return Ok(());
}
f.write_str("[")?;
for (i, tv) in self.type_vars.iter().enumerate() {
write!(f, "{}", tv.display(self.source))?;
if i < nvars - 1 {
f.write_str(", ")?;
}
}
f.write_str("]")?;
Ok(())
}
}
/// Used for displaying `type_var`. `source` is the whole file, which will be sliced to recover the
/// `TypeVarRestriction` values for generic bounds and constraints.
pub(crate) struct DisplayTypeVar<'a> {
type_var: &'a TypeVar<'a>,
source: &'a str,
}
impl TypeVar<'_> {
fn display<'a>(&'a self, source: &'a str) -> DisplayTypeVar<'a> {
DisplayTypeVar {
type_var: self,
source,
}
}
}
impl Display for DisplayTypeVar<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.type_var.kind {
TypeParamKind::TypeVar => {}
TypeParamKind::TypeVarTuple => f.write_str("*")?,
TypeParamKind::ParamSpec => f.write_str("**")?,
}
f.write_str(self.type_var.name)?;
if let Some(restriction) = &self.type_var.restriction {
f.write_str(": ")?;
match restriction {
TypeVarRestriction::Bound(bound) => {
f.write_str(&self.source[bound.range()])?;
}
TypeVarRestriction::AnyStr => f.write_str("(bytes, str)")?,
TypeVarRestriction::Constraint(vec) => {
let len = vec.len();
f.write_str("(")?;
for (i, v) in vec.iter().enumerate() {
f.write_str(&self.source[v.range()])?;
if i < len - 1 {
f.write_str(", ")?;
}
}
f.write_str(")")?;
}
}
}
if let Some(default) = self.type_var.default {
f.write_str(" = ")?;
f.write_str(&self.source[default.range()])?;
}
Ok(())
}
}
impl<'a> From<&'a TypeVar<'a>> for TypeParam {
fn from(
TypeVar {
name,
restriction,
kind,
default,
}: &'a TypeVar<'a>,
) -> Self {
let default = default.map(|expr| Box::new(expr.clone()));
match kind {
TypeParamKind::TypeVar => TypeParam::TypeVar(TypeParamTypeVar {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
name: Identifier::new(*name, TextRange::default()),
bound: match restriction {
Some(TypeVarRestriction::Bound(bound)) => Some(Box::new((*bound).clone())),
Some(TypeVarRestriction::Constraint(constraints)) => {
Some(Box::new(Expr::Tuple(ast::ExprTuple {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
elts: constraints.iter().map(|expr| (*expr).clone()).collect(),
ctx: ast::ExprContext::Load,
parenthesized: true,
})))
}
Some(TypeVarRestriction::AnyStr) => {
Some(Box::new(Expr::Tuple(ast::ExprTuple {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
elts: vec![
Expr::Name(ExprName {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
id: Name::from("str"),
ctx: ast::ExprContext::Load,
}),
Expr::Name(ExprName {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
id: Name::from("bytes"),
ctx: ast::ExprContext::Load,
}),
],
ctx: ast::ExprContext::Load,
parenthesized: true,
})))
}
None => None,
},
default,
}),
TypeParamKind::TypeVarTuple => TypeParam::TypeVarTuple(TypeParamTypeVarTuple {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
name: Identifier::new(*name, TextRange::default()),
default,
}),
TypeParamKind::ParamSpec => TypeParam::ParamSpec(TypeParamParamSpec {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
name: Identifier::new(*name, TextRange::default()),
default,
}),
}
}
}
impl<'a> From<&'a TypeParam> for TypeVar<'a> {
fn from(param: &'a TypeParam) -> Self {
let (kind, restriction) = match param {
TypeParam::TypeVarTuple(_) => (TypeParamKind::TypeVarTuple, None),
TypeParam::ParamSpec(_) => (TypeParamKind::ParamSpec, None),
TypeParam::TypeVar(param) => {
let restriction = match param.bound.as_deref() {
None => None,
Some(Expr::Tuple(constraints)) => Some(TypeVarRestriction::Constraint(
constraints.elts.iter().collect::<Vec<_>>(),
)),
Some(bound) => Some(TypeVarRestriction::Bound(bound)),
};
(TypeParamKind::TypeVar, restriction)
}
};
Self {
name: param.name(),
kind,
restriction,
default: param.default(),
}
}
}
struct TypeVarReferenceVisitor<'a> {
vars: Vec<TypeVar<'a>>,
semantic: &'a SemanticModel<'a>,
/// Tracks whether any non-TypeVars have been seen to avoid replacing generic parameters when an
/// unknown `TypeVar` is encountered.
any_skipped: bool,
}
/// Recursively collects the names of type variable references present in an expression.
impl<'a> Visitor<'a> for TypeVarReferenceVisitor<'a> {
fn visit_expr(&mut self, expr: &'a Expr) {
// special case for typing.AnyStr, which is a commonly-imported type variable in the
// standard library with the definition:
//
// ```python
// AnyStr = TypeVar('AnyStr', bytes, str)
// ```
//
// As of 01/2025, this line hasn't been modified in 8 years, so hopefully there won't be
// much to keep updated here. See
// https://github.com/python/cpython/blob/383af395af828f40d9543ee0a8fdc5cc011d43db/Lib/typing.py#L2806
//
// to replace AnyStr with an annotation like [AnyStr: (bytes, str)], we also have to make
// sure that `bytes` and `str` have their builtin values and have not been shadowed
if self.semantic.match_typing_expr(expr, "AnyStr")
&& self.semantic.has_builtin_binding("bytes")
&& self.semantic.has_builtin_binding("str")
{
self.vars.push(TypeVar {
name: "AnyStr",
restriction: Some(TypeVarRestriction::AnyStr),
kind: TypeParamKind::TypeVar,
default: None,
});
return;
}
match expr {
Expr::Name(name) if name.ctx.is_load() => {
if let Some(var) = expr_name_to_type_var(self.semantic, name) {
self.vars.push(var);
} else {
self.any_skipped = true;
}
}
_ => visitor::walk_expr(self, expr),
}
}
}
pub(crate) fn expr_name_to_type_var<'a>(
semantic: &'a SemanticModel,
name: &'a ExprName,
) -> Option<TypeVar<'a>> {
let StmtAssign { value, .. } = semantic
.lookup_symbol(name.id.as_str())
.and_then(|binding_id| semantic.binding(binding_id).source)
.map(|node_id| semantic.statement(node_id))?
.as_assign_stmt()?;
match value.as_ref() {
Expr::Subscript(ExprSubscript {
value: subscript_value,
..
}) => {
if semantic.match_typing_expr(subscript_value, "TypeVar") {
return Some(TypeVar {
name: &name.id,
restriction: None,
kind: TypeParamKind::TypeVar,
default: None,
});
}
}
Expr::Call(ExprCall {
func, arguments, ..
}) => {
let kind = if semantic.match_typing_expr(func, "TypeVar") {
TypeParamKind::TypeVar
} else if semantic.match_typing_expr(func, "TypeVarTuple") {
TypeParamKind::TypeVarTuple
} else if semantic.match_typing_expr(func, "ParamSpec") {
TypeParamKind::ParamSpec
} else {
return None;
};
if arguments
.args
.first()
.is_some_and(Expr::is_string_literal_expr)
{
// `default` was added in PEP 696 and Python 3.13. We now support converting
// TypeVars with defaults to PEP 695 type parameters.
//
// ```python
// T = TypeVar("T", default=Any, bound=str)
// class slice(Generic[T]): ...
// ```
//
// becomes
//
// ```python
// class slice[T: str = Any]: ...
// ```
let default = arguments
.find_keyword("default")
.map(|default| &default.value);
let restriction = if let Some(bound) = arguments.find_keyword("bound") {
Some(TypeVarRestriction::Bound(&bound.value))
} else if arguments.args.len() > 1 {
Some(TypeVarRestriction::Constraint(
arguments.args.iter().skip(1).collect(),
))
} else {
None
};
return Some(TypeVar {
name: &name.id,
restriction,
kind,
default,
});
}
}
_ => {}
}
None
}
/// Check if the current statement is nested within another [`StmtClassDef`] or [`StmtFunctionDef`].
fn in_nested_context(checker: &Checker) -> bool {
checker
.semantic()
.current_statements()
.skip(1) // skip the immediate parent, we only call this within a class or function
.any(|stmt| matches!(stmt, Stmt::ClassDef(_) | Stmt::FunctionDef(_)))
}
/// Deduplicate `vars`, returning `None` if `vars` is empty or any duplicates are found.
/// Also returns `None` if any `TypeVar` has a default value and the target Python version
/// is below 3.13 or preview mode is not enabled. Note that `typing_extensions` backports
/// the default argument, but the rule should be skipped in that case.
fn check_type_vars<'a>(vars: Vec<TypeVar<'a>>, checker: &Checker) -> Option<Vec<TypeVar<'a>>> {
if vars.is_empty() {
return None;
}
// If any type variables have defaults, skip the rule unless
// running with preview mode enabled and targeting Python 3.13+.
if vars.iter().any(|tv| tv.default.is_some())
&& (checker.target_version() < PythonVersion::PY313
|| !is_type_var_default_enabled(checker.settings()))
{
return None;
}
// If any type variables were not unique, just bail out here. this is a runtime error and we
// can't predict what the user wanted.
(vars.iter().unique_by(|tvar| tvar.name).count() == vars.len()).then_some(vars)
}
/// Search `class_bases` for a `typing.Generic` base class. Returns the `Generic` expression (if
/// any), along with its index in the class's bases tuple.
pub(crate) fn find_generic<'a>(
class_bases: &'a Arguments,
semantic: &SemanticModel,
) -> Option<(usize, &'a ExprSubscript)> {
class_bases.args.iter().enumerate().find_map(|(idx, expr)| {
expr.as_subscript_expr().and_then(|sub_expr| {
semantic
.match_typing_expr(&sub_expr.value, "Generic")
.then_some((idx, sub_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/pyupgrade/rules/pep695/private_type_parameter.rs | crates/ruff_linter/src/rules/pyupgrade/rules/pep695/private_type_parameter.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::Stmt;
use ruff_python_semantic::Binding;
use ruff_python_stdlib::identifiers::is_identifier;
use ruff_text_size::Ranged;
use crate::{Applicability, Fix, FixAvailability, Violation};
use crate::{
checkers::ast::Checker,
renamer::{Renamer, ShadowedKind},
};
/// ## What it does
///
/// Checks for use of [PEP 695] type parameters with leading underscores in generic classes and
/// functions.
///
/// ## Why is this bad?
///
/// [PEP 695] type parameters are already restricted in scope to the class or function in which they
/// appear, so leading underscores just hurt readability without the usual privacy benefits.
///
/// However, neither a diagnostic nor a fix will be emitted for "sunder" (`_T_`) or "dunder"
/// (`__T__`) type parameter names as these are not considered private.
///
/// ## Example
///
/// ```python
/// class GenericClass[_T]:
/// var: _T
///
///
/// def generic_function[_T](var: _T) -> list[_T]:
/// return var[0]
/// ```
///
/// Use instead:
///
/// ```python
/// class GenericClass[T]:
/// var: T
///
///
/// def generic_function[T](var: T) -> list[T]:
/// return var[0]
/// ```
///
/// ## Fix availability
///
/// If the name without an underscore would shadow a builtin or another variable, would be a
/// keyword, or would otherwise be an invalid identifier, a fix will not be available. In these
/// situations, you can consider using a trailing underscore or a different name entirely to satisfy
/// the lint rule.
///
/// ## See also
///
/// This rule renames private [PEP 695] type parameters but doesn't convert pre-[PEP 695] generics
/// to the new format. See [`non-pep695-generic-function`][UP047] and
/// [`non-pep695-generic-class`][UP046] for rules that will make this transformation.
/// Those rules do not remove unused type variables after their changes,
/// so you may also want to consider enabling [`unused-private-type-var`][PYI018] to complete
/// the transition to [PEP 695] generics.
///
/// [PEP 695]: https://peps.python.org/pep-0695/
/// [UP047]: https://docs.astral.sh/ruff/rules/non-pep695-generic-function
/// [UP046]: https://docs.astral.sh/ruff/rules/non-pep695-generic-class
/// [PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct PrivateTypeParameter {
kind: ParamKind,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ParamKind {
Class,
Function,
}
impl ParamKind {
const fn as_str(self) -> &'static str {
match self {
ParamKind::Class => "class",
ParamKind::Function => "function",
}
}
}
impl Violation for PrivateTypeParameter {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Generic {} uses private type parameters",
self.kind.as_str()
)
}
fn fix_title(&self) -> Option<String> {
Some("Rename type parameter to remove leading underscores".to_string())
}
}
/// UP049
pub(crate) fn private_type_parameter(checker: &Checker, binding: &Binding) {
let semantic = checker.semantic();
let Some(stmt) = binding.statement(semantic) else {
return;
};
if !binding.kind.is_type_param() {
return;
}
let kind = match stmt {
Stmt::FunctionDef(_) => ParamKind::Function,
Stmt::ClassDef(_) => ParamKind::Class,
_ => return,
};
let old_name = binding.name(checker.source());
if !old_name.starts_with('_') {
return;
}
// Sunder `_T_`, dunder `__T__`, and all all-under `_` or `__` cases should all be skipped, as
// these are not "private" names
if old_name.ends_with('_') {
return;
}
let mut diagnostic = checker.report_diagnostic(PrivateTypeParameter { kind }, binding.range);
let new_name = old_name.trim_start_matches('_');
// if the new name would shadow another variable, keyword, or builtin, emit a diagnostic without
// a suggested fix
if ShadowedKind::new(binding, new_name, checker).shadows_any() {
return;
}
if !is_identifier(new_name) {
return;
}
let source = checker.source();
diagnostic.try_set_fix(|| {
let (first, rest) = Renamer::rename(
old_name,
new_name,
&semantic.scopes[binding.scope],
semantic,
checker.stylist(),
)?;
let applicability = if binding
.references()
.any(|id| &source[semantic.reference(id).range()] != old_name)
{
Applicability::DisplayOnly
} else {
Applicability::Safe
};
let fix_isolation = Checker::isolation(binding.source);
Ok(Fix::applicable_edits(first, rest, applicability).isolate(fix_isolation))
});
}
| 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_django/helpers.rs | crates/ruff_linter/src/rules/flake8_django/helpers.rs | use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::{SemanticModel, analyze};
/// Return `true` if a Python class appears to be a Django model, based on its base classes.
pub(super) fn is_model(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> bool {
analyze::class::any_qualified_base_class(class_def, semantic, &|qualified_name| {
matches!(
qualified_name.segments(),
["django", "db", "models", "Model"]
)
})
}
/// Return `true` if a Python class appears to be a Django model form, based on its base classes.
pub(super) fn is_model_form(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> bool {
analyze::class::any_qualified_base_class(class_def, semantic, &|qualified_name| {
matches!(
qualified_name.segments(),
["django", "forms", "ModelForm"] | ["django", "forms", "models", "ModelForm"]
)
})
}
/// Return `true` if the expression is constructor for a Django model field.
pub(super) fn is_model_field(expr: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(expr)
.is_some_and(|qualified_name| {
qualified_name
.segments()
.starts_with(&["django", "db", "models"])
})
}
/// Return the name of the field type, if the expression is constructor for a Django model field.
pub(super) fn get_model_field_name<'a>(
expr: &'a Expr,
semantic: &'a SemanticModel,
) -> Option<&'a str> {
semantic
.resolve_qualified_name(expr)
.and_then(|qualified_name| {
let qualified_name = qualified_name.segments();
if !qualified_name.starts_with(&["django", "db", "models"]) {
return None;
}
qualified_name.last().copied()
})
}
| 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_django/mod.rs | crates/ruff_linter/src/rules/flake8_django/mod.rs | //! Rules from [django-flake8](https://pypi.org/project/flake8-django/)
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::DjangoNullableModelStringField, Path::new("DJ001.py"))]
#[test_case(Rule::DjangoLocalsInRenderFunction, Path::new("DJ003.py"))]
#[test_case(Rule::DjangoExcludeWithModelForm, Path::new("DJ006.py"))]
#[test_case(Rule::DjangoAllWithModelForm, Path::new("DJ007.py"))]
#[test_case(Rule::DjangoModelWithoutDunderStr, Path::new("DJ008.py"))]
#[test_case(Rule::DjangoUnorderedBodyContentInModel, Path::new("DJ012.py"))]
#[test_case(Rule::DjangoNonLeadingReceiverDecorator, Path::new("DJ013.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_django").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_django/rules/nullable_model_string_field.rs | crates/ruff_linter/src/rules/flake8_django/rules/nullable_model_string_field.rs | use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_const_true;
use ruff_python_semantic::{Modules, SemanticModel};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_django::helpers;
/// ## What it does
/// Checks nullable string-based fields (like `CharField` and `TextField`)
/// in Django models.
///
/// ## Why is this bad?
/// If a string-based field is nullable, then your model will have two possible
/// representations for "no data": `None` and the empty string. This can lead to
/// confusion, as clients of the API have to check for both `None` and the
/// empty string when trying to determine if the field has data.
///
/// The Django convention is to use the empty string in lieu of `None` for
/// string-based fields.
///
/// ## Example
/// ```python
/// from django.db import models
///
///
/// class MyModel(models.Model):
/// field = models.CharField(max_length=255, null=True)
/// ```
///
/// Use instead:
/// ```python
/// from django.db import models
///
///
/// class MyModel(models.Model):
/// field = models.CharField(max_length=255, default="")
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.246")]
pub(crate) struct DjangoNullableModelStringField {
field_name: String,
}
impl Violation for DjangoNullableModelStringField {
#[derive_message_formats]
fn message(&self) -> String {
let DjangoNullableModelStringField { field_name } = self;
format!("Avoid using `null=True` on string-based fields such as `{field_name}`")
}
}
/// DJ001
pub(crate) fn nullable_model_string_field(checker: &Checker, body: &[Stmt]) {
if !checker.semantic().seen_module(Modules::DJANGO) {
return;
}
for statement in body {
let value = match statement {
Stmt::Assign(ast::StmtAssign { value, .. }) => value,
Stmt::AnnAssign(ast::StmtAnnAssign {
value: Some(value), ..
}) => value,
_ => continue,
};
if let Some(field_name) = is_nullable_field(value, checker.semantic()) {
checker.report_diagnostic(
DjangoNullableModelStringField {
field_name: field_name.to_string(),
},
value.range(),
);
}
}
}
fn is_nullable_field<'a>(value: &'a Expr, semantic: &'a SemanticModel) -> Option<&'a str> {
let call = value.as_call_expr()?;
let field_name = helpers::get_model_field_name(&call.func, semantic)?;
if !matches!(
field_name,
"CharField" | "TextField" | "SlugField" | "EmailField" | "FilePathField" | "URLField"
) {
return None;
}
let mut null_key = false;
let mut blank_key = false;
let mut unique_key = false;
for keyword in &*call.arguments.keywords {
let Some(argument) = &keyword.arg else {
continue;
};
if !is_const_true(&keyword.value) {
continue;
}
match argument.as_str() {
"blank" => blank_key = true,
"null" => null_key = true,
"unique" => unique_key = true,
_ => continue,
}
}
if blank_key && unique_key {
return None;
}
if !null_key {
return None;
}
Some(field_name)
}
| 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_django/rules/exclude_with_model_form.rs | crates/ruff_linter/src/rules/flake8_django/rules/exclude_with_model_form.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_django::helpers::is_model_form;
/// ## What it does
/// Checks for the use of `exclude` in Django `ModelForm` classes.
///
/// ## Why is this bad?
/// If a `ModelForm` includes the `exclude` attribute, any new field that
/// is added to the model will automatically be exposed for modification.
///
/// ## Example
/// ```python
/// from django.forms import ModelForm
///
///
/// class PostForm(ModelForm):
/// class Meta:
/// model = Post
/// exclude = ["author"]
/// ```
///
/// Use instead:
/// ```python
/// from django.forms import ModelForm
///
///
/// class PostForm(ModelForm):
/// class Meta:
/// model = Post
/// fields = ["title", "content"]
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.253")]
pub(crate) struct DjangoExcludeWithModelForm;
impl Violation for DjangoExcludeWithModelForm {
#[derive_message_formats]
fn message(&self) -> String {
"Do not use `exclude` with `ModelForm`, use `fields` instead".to_string()
}
}
/// DJ006
pub(crate) fn exclude_with_model_form(checker: &Checker, class_def: &ast::StmtClassDef) {
if !checker.semantic().seen_module(Modules::DJANGO) {
return;
}
if !is_model_form(class_def, checker.semantic()) {
return;
}
for element in &class_def.body {
let Stmt::ClassDef(ast::StmtClassDef { name, body, .. }) = element else {
continue;
};
if name != "Meta" {
continue;
}
for element in body {
let Stmt::Assign(ast::StmtAssign { targets, .. }) = element else {
continue;
};
for target in targets {
let Expr::Name(ast::ExprName { id, .. }) = target else {
continue;
};
if id == "exclude" {
checker.report_diagnostic(DjangoExcludeWithModelForm, target.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_django/rules/locals_in_render_function.rs | crates/ruff_linter/src/rules/flake8_django/rules/locals_in_render_function.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::{Modules, SemanticModel};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for the use of `locals()` in `render` functions.
///
/// ## Why is this bad?
/// Using `locals()` can expose internal variables or other unintentional
/// data to the rendered template.
///
/// ## Example
/// ```python
/// from django.shortcuts import render
///
///
/// def index(request):
/// posts = Post.objects.all()
/// return render(request, "app/index.html", locals())
/// ```
///
/// Use instead:
/// ```python
/// from django.shortcuts import render
///
///
/// def index(request):
/// posts = Post.objects.all()
/// context = {"posts": posts}
/// return render(request, "app/index.html", context)
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.253")]
pub(crate) struct DjangoLocalsInRenderFunction;
impl Violation for DjangoLocalsInRenderFunction {
#[derive_message_formats]
fn message(&self) -> String {
"Avoid passing `locals()` as context to a `render` function".to_string()
}
}
/// DJ003
pub(crate) fn locals_in_render_function(checker: &Checker, call: &ast::ExprCall) {
if !checker.semantic().seen_module(Modules::DJANGO) {
return;
}
if !checker
.semantic()
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["django", "shortcuts", "render"])
})
{
return;
}
if let Some(argument) = call.arguments.find_argument_value("context", 2) {
if is_locals_call(argument, checker.semantic()) {
checker.report_diagnostic(DjangoLocalsInRenderFunction, argument.range());
}
}
}
fn is_locals_call(expr: &Expr, semantic: &SemanticModel) -> bool {
let Expr::Call(ast::ExprCall { func, .. }) = expr else {
return false;
};
semantic.match_builtin_expr(func, "locals")
}
| 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_django/rules/mod.rs | crates/ruff_linter/src/rules/flake8_django/rules/mod.rs | pub(crate) use all_with_model_form::*;
pub(crate) use exclude_with_model_form::*;
pub(crate) use locals_in_render_function::*;
pub(crate) use model_without_dunder_str::*;
pub(crate) use non_leading_receiver_decorator::*;
pub(crate) use nullable_model_string_field::*;
pub(crate) use unordered_body_content_in_model::*;
mod all_with_model_form;
mod exclude_with_model_form;
mod locals_in_render_function;
mod model_without_dunder_str;
mod non_leading_receiver_decorator;
mod nullable_model_string_field;
mod unordered_body_content_in_model;
| 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_django/rules/model_without_dunder_str.rs | crates/ruff_linter/src/rules/flake8_django/rules/model_without_dunder_str.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_const_true;
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_semantic::{Modules, SemanticModel, analyze};
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_django::helpers;
/// ## What it does
/// Checks that a `__str__` method is defined in Django models.
///
/// ## Why is this bad?
/// Django models should define a `__str__` method to return a string representation
/// of the model instance, as Django calls this method to display the object in
/// the Django Admin and elsewhere.
///
/// Models without a `__str__` method will display a non-meaningful representation
/// of the object in the Django Admin.
///
/// ## Example
/// ```python
/// from django.db import models
///
///
/// class MyModel(models.Model):
/// field = models.CharField(max_length=255)
/// ```
///
/// Use instead:
/// ```python
/// from django.db import models
///
///
/// class MyModel(models.Model):
/// field = models.CharField(max_length=255)
///
/// def __str__(self):
/// return f"{self.field}"
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.246")]
pub(crate) struct DjangoModelWithoutDunderStr;
impl Violation for DjangoModelWithoutDunderStr {
#[derive_message_formats]
fn message(&self) -> String {
"Model does not define `__str__` method".to_string()
}
}
/// DJ008
pub(crate) fn model_without_dunder_str(checker: &Checker, class_def: &ast::StmtClassDef) {
if !checker.semantic().seen_module(Modules::DJANGO) {
return;
}
if !is_non_abstract_model(class_def, checker.semantic()) {
return;
}
if has_dunder_method(class_def, checker.semantic()) {
return;
}
checker.report_diagnostic(DjangoModelWithoutDunderStr, class_def.identifier());
}
/// Returns `true` if the class has `__str__` method.
fn has_dunder_method(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> bool {
analyze::class::any_super_class(class_def, semantic, &|class_def| {
class_def.body.iter().any(|val| match val {
Stmt::FunctionDef(ast::StmtFunctionDef { name, .. }) => name == "__str__",
_ => false,
})
})
}
/// Returns `true` if the class is a non-abstract Django model.
fn is_non_abstract_model(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> bool {
if class_def.bases().is_empty() || is_model_abstract(class_def) {
false
} else {
helpers::is_model(class_def, semantic)
}
}
/// Check if class is abstract, in terms of Django model inheritance.
fn is_model_abstract(class_def: &ast::StmtClassDef) -> bool {
for element in &class_def.body {
let Stmt::ClassDef(ast::StmtClassDef { name, body, .. }) = element else {
continue;
};
if name != "Meta" {
continue;
}
for element in body {
match element {
Stmt::Assign(ast::StmtAssign { targets, value, .. }) => {
if targets
.iter()
.any(|target| is_abstract_true_assignment(target, Some(value)))
{
return true;
}
}
Stmt::AnnAssign(ast::StmtAnnAssign { target, value, .. }) => {
if is_abstract_true_assignment(target, value.as_deref()) {
return true;
}
}
_ => {}
}
}
}
false
}
fn is_abstract_true_assignment(target: &Expr, value: Option<&Expr>) -> bool {
let Expr::Name(ast::ExprName { id, .. }) = target else {
return false;
};
if id != "abstract" {
return false;
}
let Some(value) = value else {
return false;
};
if !is_const_true(value) {
return false;
}
true
}
| 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_django/rules/unordered_body_content_in_model.rs | crates/ruff_linter/src/rules/flake8_django/rules/unordered_body_content_in_model.rs | use std::fmt;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_dunder;
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_semantic::{Modules, SemanticModel};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_django::helpers;
/// ## What it does
/// Checks for the order of Model's inner classes, methods, and fields as per
/// the [Django Style Guide].
///
/// ## Why is this bad?
/// The [Django Style Guide] specifies that the order of Model inner classes,
/// attributes and methods should be as follows:
///
/// 1. All database fields
/// 2. Custom manager attributes
/// 3. `class Meta`
/// 4. `def __str__()`
/// 5. `def save()`
/// 6. `def get_absolute_url()`
/// 7. Any custom methods
///
/// ## Example
/// ```python
/// from django.db import models
///
///
/// class StrBeforeFieldModel(models.Model):
/// class Meta:
/// verbose_name = "test"
/// verbose_name_plural = "tests"
///
/// def __str__(self):
/// return "foobar"
///
/// first_name = models.CharField(max_length=32)
/// last_name = models.CharField(max_length=40)
/// ```
///
/// Use instead:
/// ```python
/// from django.db import models
///
///
/// class StrBeforeFieldModel(models.Model):
/// first_name = models.CharField(max_length=32)
/// last_name = models.CharField(max_length=40)
///
/// class Meta:
/// verbose_name = "test"
/// verbose_name_plural = "tests"
///
/// def __str__(self):
/// return "foobar"
/// ```
///
/// [Django Style Guide]: https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#model-style
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.258")]
pub(crate) struct DjangoUnorderedBodyContentInModel {
element_type: ContentType,
prev_element_type: ContentType,
}
impl Violation for DjangoUnorderedBodyContentInModel {
#[derive_message_formats]
fn message(&self) -> String {
let DjangoUnorderedBodyContentInModel {
element_type,
prev_element_type,
} = self;
format!(
"Order of model's inner classes, methods, and fields does not follow the Django Style Guide: {element_type} should come before {prev_element_type}"
)
}
}
/// DJ012
pub(crate) fn unordered_body_content_in_model(checker: &Checker, class_def: &ast::StmtClassDef) {
if !checker.semantic().seen_module(Modules::DJANGO) {
return;
}
if !helpers::is_model(class_def, checker.semantic()) {
return;
}
// Track all the element types we've seen so far.
let mut element_types = Vec::new();
let mut prev_element_type = None;
for element in &class_def.body {
let Some(element_type) = get_element_type(element, checker.semantic()) else {
continue;
};
// Skip consecutive elements of the same type. It's less noisy to only report
// violations at type boundaries (e.g., avoid raising a violation for _every_
// field declaration that's out of order).
if prev_element_type == Some(element_type) {
continue;
}
prev_element_type = Some(element_type);
if let Some(&prev_element_type) = element_types
.iter()
.find(|&&prev_element_type| prev_element_type > element_type)
{
checker.report_diagnostic(
DjangoUnorderedBodyContentInModel {
element_type,
prev_element_type,
},
element.range(),
);
} else {
element_types.push(element_type);
}
}
}
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
enum ContentType {
FieldDeclaration,
ManagerDeclaration,
MetaClass,
MagicMethod,
SaveMethod,
GetAbsoluteUrlMethod,
CustomMethod,
}
impl fmt::Display for ContentType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ContentType::FieldDeclaration => f.write_str("field declaration"),
ContentType::ManagerDeclaration => f.write_str("manager declaration"),
ContentType::MetaClass => f.write_str("`Meta` class"),
ContentType::MagicMethod => f.write_str("Magic method"),
ContentType::SaveMethod => f.write_str("`save` method"),
ContentType::GetAbsoluteUrlMethod => f.write_str("`get_absolute_url` method"),
ContentType::CustomMethod => f.write_str("custom method"),
}
}
}
fn get_element_type(element: &Stmt, semantic: &SemanticModel) -> Option<ContentType> {
match element {
Stmt::Assign(ast::StmtAssign { targets, value, .. }) => {
if let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() {
if helpers::is_model_field(func, semantic) {
return Some(ContentType::FieldDeclaration);
}
}
let expr = targets.first()?;
let Expr::Name(ast::ExprName { id, .. }) = expr else {
return None;
};
if id == "objects" {
Some(ContentType::ManagerDeclaration)
} else {
None
}
}
Stmt::ClassDef(ast::StmtClassDef { name, .. }) => {
if name == "Meta" {
Some(ContentType::MetaClass)
} else {
None
}
}
Stmt::FunctionDef(ast::StmtFunctionDef { name, .. }) => match name.as_str() {
name if is_dunder(name) => Some(ContentType::MagicMethod),
"save" => Some(ContentType::SaveMethod),
"get_absolute_url" => Some(ContentType::GetAbsoluteUrlMethod),
_ => Some(ContentType::CustomMethod),
},
_ => 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_django/rules/non_leading_receiver_decorator.rs | crates/ruff_linter/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs | use ruff_python_ast::Decorator;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks that Django's `@receiver` decorator is listed first, prior to
/// any other decorators.
///
/// ## Why is this bad?
/// Django's `@receiver` decorator is special in that it does not return
/// a wrapped function. Rather, `@receiver` connects the decorated function
/// to a signal. If any other decorators are listed before `@receiver`,
/// the decorated function will not be connected to the signal.
///
/// ## Example
/// ```python
/// from django.dispatch import receiver
/// from django.db.models.signals import post_save
///
///
/// @transaction.atomic
/// @receiver(post_save, sender=MyModel)
/// def my_handler(sender, instance, created, **kwargs):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// from django.dispatch import receiver
/// from django.db.models.signals import post_save
///
///
/// @receiver(post_save, sender=MyModel)
/// @transaction.atomic
/// def my_handler(sender, instance, created, **kwargs):
/// pass
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.246")]
pub(crate) struct DjangoNonLeadingReceiverDecorator;
impl Violation for DjangoNonLeadingReceiverDecorator {
#[derive_message_formats]
fn message(&self) -> String {
"`@receiver` decorator must be on top of all the other decorators".to_string()
}
}
/// DJ013
pub(crate) fn non_leading_receiver_decorator(checker: &Checker, decorator_list: &[Decorator]) {
if !checker.semantic().seen_module(Modules::DJANGO) {
return;
}
let mut seen_receiver = false;
for (i, decorator) in decorator_list.iter().enumerate() {
let is_receiver = decorator.expression.as_call_expr().is_some_and(|call| {
checker
.semantic()
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["django", "dispatch", "receiver"]
)
})
});
if i > 0 && is_receiver && !seen_receiver {
checker.report_diagnostic(DjangoNonLeadingReceiverDecorator, decorator.range());
}
if !is_receiver && seen_receiver {
seen_receiver = false;
} else if is_receiver {
seen_receiver = true;
}
}
}
| 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_django/rules/all_with_model_form.rs | crates/ruff_linter/src/rules/flake8_django/rules/all_with_model_form.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_django::helpers::is_model_form;
/// ## What it does
/// Checks for the use of `fields = "__all__"` in Django `ModelForm`
/// classes.
///
/// ## Why is this bad?
/// If a `ModelForm` includes the `fields = "__all__"` attribute, any new
/// field that is added to the model will automatically be exposed for
/// modification.
///
/// ## Example
/// ```python
/// from django.forms import ModelForm
///
///
/// class PostForm(ModelForm):
/// class Meta:
/// model = Post
/// fields = "__all__"
/// ```
///
/// Use instead:
/// ```python
/// from django.forms import ModelForm
///
///
/// class PostForm(ModelForm):
/// class Meta:
/// model = Post
/// fields = ["title", "content"]
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.253")]
pub(crate) struct DjangoAllWithModelForm;
impl Violation for DjangoAllWithModelForm {
#[derive_message_formats]
fn message(&self) -> String {
"Do not use `__all__` with `ModelForm`, use `fields` instead".to_string()
}
}
/// DJ007
pub(crate) fn all_with_model_form(checker: &Checker, class_def: &ast::StmtClassDef) {
if !checker.semantic().seen_module(Modules::DJANGO) {
return;
}
if !is_model_form(class_def, checker.semantic()) {
return;
}
for element in &class_def.body {
let Stmt::ClassDef(ast::StmtClassDef { name, body, .. }) = element else {
continue;
};
if name != "Meta" {
continue;
}
for element in body {
let Stmt::Assign(ast::StmtAssign { targets, value, .. }) = element else {
continue;
};
for target in targets {
let Expr::Name(ast::ExprName { id, .. }) = target else {
continue;
};
if id != "fields" {
continue;
}
match value.as_ref() {
Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => {
if value == "__all__" {
checker.report_diagnostic(DjangoAllWithModelForm, element.range());
return;
}
}
Expr::BytesLiteral(ast::ExprBytesLiteral { value, .. }) => {
if value == "__all__".as_bytes() {
checker.report_diagnostic(DjangoAllWithModelForm, element.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/pandas_vet/helpers.rs | crates/ruff_linter/src/rules/pandas_vet/helpers.rs | use ruff_python_ast::Expr;
use ruff_python_semantic::{BindingKind, Imported, SemanticModel};
#[derive(Debug)]
pub(super) enum Resolution {
/// The expression resolves to an irrelevant expression type (e.g., a constant).
IrrelevantExpression,
/// The expression resolves to an irrelevant binding (e.g., a function definition).
IrrelevantBinding,
/// The expression resolves to a relevant local binding (e.g., a variable).
RelevantLocal,
/// The expression resolves to the `pandas` module itself.
PandasModule,
}
/// Test an [`Expr`] for relevance to Pandas-related operations.
pub(super) fn test_expression(expr: &Expr, semantic: &SemanticModel) -> Resolution {
match expr {
Expr::StringLiteral(_)
| Expr::BytesLiteral(_)
| Expr::NumberLiteral(_)
| Expr::BooleanLiteral(_)
| Expr::NoneLiteral(_)
| Expr::EllipsisLiteral(_)
| Expr::Tuple(_)
| Expr::List(_)
| Expr::Set(_)
| Expr::Dict(_)
| Expr::SetComp(_)
| Expr::ListComp(_)
| Expr::DictComp(_)
| Expr::Generator(_) => Resolution::IrrelevantExpression,
Expr::Name(name) => {
semantic
.resolve_name(name)
.map_or(Resolution::IrrelevantBinding, |id| {
match &semantic.binding(id).kind {
BindingKind::Argument => {
// Avoid, e.g., `self.values`.
if matches!(name.id.as_str(), "self" | "cls") {
Resolution::IrrelevantBinding
} else {
Resolution::RelevantLocal
}
}
BindingKind::Annotation
| BindingKind::Assignment
| BindingKind::NamedExprAssignment
| BindingKind::LoopVar
| BindingKind::Global(_)
| BindingKind::Nonlocal(_, _) => Resolution::RelevantLocal,
BindingKind::Import(import)
if matches!(import.qualified_name().segments(), ["pandas"]) =>
{
Resolution::PandasModule
}
_ => Resolution::IrrelevantBinding,
}
})
}
_ => Resolution::RelevantLocal,
}
}
| 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/pandas_vet/mod.rs | crates/ruff_linter/src/rules/pandas_vet/mod.rs | //! Rules from [pandas-vet](https://pypi.org/project/pandas-vet/).
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::{Linter, Rule};
use crate::test::{test_path, test_snippet};
use crate::{assert_diagnostics, settings};
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
x.drop(["a"], axis=1, inplace=False)
"#,
"PD002_pass"
)]
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
x.drop(["a"], axis=1, inplace=True)
"#,
"PD002_fail"
)]
#[test_case(
r"
import polars as pl
x = pl.DataFrame()
x.drop(['a'], inplace=True)
",
"PD002_pass_polars"
)]
#[test_case(
r"
x = DataFrame()
x.drop(['a'], inplace=True)
",
"PD002_pass_no_import"
)]
#[test_case(
r"
import pandas as pd
nas = pd.isna(val)
",
"PD003_pass"
)]
#[test_case(
r"
import pandas as pd
nulls = pd.isnull(val)
",
"PD003_fail"
)]
#[test_case(
r#"
import pandas as pd
print("bah humbug")
"#,
"PD003_allows_other_calls"
)]
#[test_case(
r"
import pandas as pd
not_nas = pd.notna(val)
",
"PD004_pass"
)]
#[test_case(
r"
import pandas as pd
not_nulls = pd.notnull(val)
",
"PD004_fail"
)]
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
new_x = x.loc["d":, "A":"C"]
"#,
"PD007_pass_loc"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
new_x = x.iloc[[1, 3, 5], [1, 3]]
",
"PD007_pass_iloc"
)]
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
y = x.ix[[0, 2], "A"]
"#,
"PD007_fail"
)]
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
index = x.loc[:, ["B", "A"]]
"#,
"PD008_pass"
)]
#[test_case(
r#"
import io
import zipfile
class MockBinaryFile(io.BytesIO):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def close(self):
pass # Don"t allow closing the file, it would clear the buffer
zip_buffer = MockBinaryFile()
with zipfile.ZipFile(zip_buffer, "w") as zf:
zf.writestr("dir/file.txt", "This is a test")
# Reset the BytesIO object"s cursor to the start.
zip_buffer.seek(0)
with zipfile.ZipFile(zip_buffer, "r") as zf:
zpath = zipfile.Path(zf, "/")
dir_name, file_name = zpath.at.split("/")
"#,
"PD008_pass_on_attr"
)]
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
index = x.at[:, ["B", "A"]]
"#,
"PD008_fail"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
index = x.iloc[:, 1:3]
",
"PD009_pass"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
index = x.iat[:, 1:3]
",
"PD009_fail"
)]
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
table = x.pivot_table(
x,
values="D",
index=["A", "B"],
columns=["C"],
aggfunc=np.sum,
fill_value=0
)
"#,
"PD010_pass"
)]
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
table = pd.pivot(
x,
index="foo",
columns="bar",
values="baz"
)
"#,
"PD010_fail_pivot"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
result = x.to_array()
",
"PD011_pass_to_array"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
result = x.array
",
"PD011_pass_array"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
result = x.values
",
"PD011_fail_values"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
result = x.values()
",
"PD011_pass_values_call"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
x.values = 1
",
"PD011_pass_values_store"
)]
#[test_case(
r"
class Class:
def __init__(self, values: str) -> None:
self.values = values
print(self.values)
",
"PD011_pass_values_instance"
)]
#[test_case(
r"
import pandas as pd
result = {}.values
",
"PD011_pass_values_dict"
)]
#[test_case(
r"
import pandas as pd
result = pd.values
",
"PD011_pass_values_import"
)]
#[test_case(
r"
import pandas as pd
result = x.values
",
"PD011_pass_values_unbound"
)]
#[test_case(
r"
import pandas as pd
result = values
",
"PD011_pass_node_name"
)]
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
y = x.melt(
id_vars="airline",
value_vars=["ATL", "DEN", "DFW"],
value_name="airline delay"
)
"#,
"PD013_pass"
)]
#[test_case(
r"
import numpy as np
arrays = [np.random.randn(3, 4) for _ in range(10)]
np.stack(arrays, axis=0).shape
",
"PD013_pass_numpy"
)]
#[test_case(
r"
import pandas as pd
y = x.stack(level=-1, dropna=True)
",
"PD013_pass_unbound"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
y = x.stack(level=-1, dropna=True)
",
"PD013_fail_stack"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
y = pd.DataFrame()
x.merge(y)
",
"PD015_pass_merge_on_dataframe"
)]
#[test_case(
r#"
import pandas as pd
x = pd.DataFrame()
y = pd.DataFrame()
x.merge(y, "inner")
"#,
"PD015_pass_merge_on_dataframe_with_multiple_args"
)]
#[test_case(
r"
import pandas as pd
x = pd.DataFrame()
y = pd.DataFrame()
pd.merge(x, y)
",
"PD015_fail_merge_on_pandas_object"
)]
#[test_case(
r#"
pd.to_datetime(timestamp * 10 ** 9).strftime("%Y-%m-%d %H:%M:%S.%f")
"#,
"PD015_pass_other_pd_function"
)]
#[test_case(
r"
import pandas as pd
employees = pd.DataFrame(employee_dict)
",
"PD901_pass_non_df"
)]
#[test_case(
r"
import pandas as pd
employees_df = pd.DataFrame(employee_dict)
",
"PD901_pass_part_df"
)]
#[test_case(
r"
import pandas as pd
my_function(df=data)
",
"PD901_pass_df_param"
)]
#[test_case(
r"
import pandas as pd
df = pd.DataFrame()
",
"PD901_fail_df_var"
)]
fn contents(contents: &str, snapshot: &str) {
let diagnostics = test_snippet(
contents,
&settings::LinterSettings::for_rules(Linter::PandasVet.rules()),
);
assert_diagnostics!(snapshot, diagnostics);
}
#[test_case(
Rule::PandasUseOfDotReadTable,
Path::new("pandas_use_of_dot_read_table.py")
)]
#[test_case(Rule::PandasUseOfInplaceArgument, Path::new("PD002.py"))]
#[test_case(Rule::PandasNuniqueConstantSeriesCheck, Path::new("PD101.py"))]
fn paths(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("pandas_vet").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/pandas_vet/rules/pd_merge.rs | crates/ruff_linter/src/rules/pandas_vet/rules/pd_merge.rs | use ruff_python_ast::{self as ast, Expr};
use ruff_macros::{ViolationMetadata, derive_message_formats};
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 `pd.merge` on Pandas objects.
///
/// ## Why is this bad?
/// In Pandas, the `.merge` method (exposed on, e.g., `DataFrame` objects) and
/// the `pd.merge` function (exposed on the Pandas module) are equivalent.
///
/// For consistency, prefer calling `.merge` on an object over calling
/// `pd.merge` on the Pandas module, as the former is more idiomatic.
///
/// Further, `pd.merge` is not a method, but a function, which prohibits it
/// from being used in method chains, a common pattern in Pandas code.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// cats_df = pd.read_csv("cats.csv")
/// dogs_df = pd.read_csv("dogs.csv")
/// rabbits_df = pd.read_csv("rabbits.csv")
/// pets_df = pd.merge(pd.merge(cats_df, dogs_df), rabbits_df) # Hard to read.
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// cats_df = pd.read_csv("cats.csv")
/// dogs_df = pd.read_csv("dogs.csv")
/// rabbits_df = pd.read_csv("rabbits.csv")
/// pets_df = cats_df.merge(dogs_df).merge(rabbits_df)
/// ```
///
/// ## References
/// - [Pandas documentation: `merge`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html#pandas.DataFrame.merge)
/// - [Pandas documentation: `pd.merge`](https://pandas.pydata.org/docs/reference/api/pandas.merge.html#pandas.merge)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfPdMerge;
impl Violation for PandasUseOfPdMerge {
#[derive_message_formats]
fn message(&self) -> String {
"Use `.merge` method instead of `pd.merge` function. They have equivalent \
functionality."
.to_string()
}
}
/// PD015
pub(crate) fn use_of_pd_merge(checker: &Checker, func: &Expr) {
if !checker.semantic().seen_module(Modules::PANDAS) {
return;
}
if let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func {
if let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() {
if id == "pd" && attr == "merge" {
checker.report_diagnostic(PandasUseOfPdMerge, 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/pandas_vet/rules/nunique_constant_series_check.rs | crates/ruff_linter/src/rules/pandas_vet/rules/nunique_constant_series_check.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, CmpOp, Expr, Int};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::pandas_vet::helpers::{Resolution, test_expression};
/// ## What it does
/// Check for uses of `.nunique()` to check if a Pandas Series is constant
/// (i.e., contains only one unique value).
///
/// ## Why is this bad?
/// `.nunique()` is computationally inefficient for checking if a Series is
/// constant.
///
/// Consider, for example, a Series of length `n` that consists of increasing
/// integer values (e.g., 1, 2, 3, 4). The `.nunique()` method will iterate
/// over the entire Series to count the number of unique values. But in this
/// case, we can detect that the Series is non-constant after visiting the
/// first two values, which are non-equal.
///
/// In general, `.nunique()` requires iterating over the entire Series, while a
/// more efficient approach allows short-circuiting the operation as soon as a
/// non-equal value is found.
///
/// Instead of calling `.nunique()`, convert the Series to a NumPy array, and
/// check if all values in the array are equal to the first observed value.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// data = pd.Series(range(1000))
/// if data.nunique() <= 1:
/// print("Series is constant")
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// data = pd.Series(range(1000))
/// array = data.to_numpy()
/// if array.shape[0] == 0 or (array[0] == array).all():
/// print("Series is constant")
/// ```
///
/// ## References
/// - [Pandas Cookbook: "Constant Series"](https://pandas.pydata.org/docs/user_guide/cookbook.html#constant-series)
/// - [Pandas documentation: `nunique`](https://pandas.pydata.org/docs/reference/api/pandas.Series.nunique.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.279")]
pub(crate) struct PandasNuniqueConstantSeriesCheck;
impl Violation for PandasNuniqueConstantSeriesCheck {
#[derive_message_formats]
fn message(&self) -> String {
"Using `series.nunique()` for checking that a series is constant is inefficient".to_string()
}
}
/// PD101
pub(crate) fn nunique_constant_series_check(
checker: &Checker,
expr: &Expr,
left: &Expr,
ops: &[CmpOp],
comparators: &[Expr],
) {
if !checker.semantic().seen_module(Modules::PANDAS) {
return;
}
let ([op], [right]) = (ops, comparators) else {
return;
};
// Operators may be ==, !=, <=, >.
if !matches!(op, CmpOp::Eq | CmpOp::NotEq | CmpOp::LtE | CmpOp::Gt,) {
return;
}
// Right should be the integer 1.
if !matches!(
right,
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(Int::ONE),
range: _,
node_index: _,
})
) {
return;
}
// Check if call is `.nuniuqe()`.
let Expr::Call(ast::ExprCall { func, .. }) = left else {
return;
};
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() else {
return;
};
if attr.as_str() != "nunique" {
return;
}
// Avoid flagging on non-Series (e.g., `{"a": 1}.at[0]`).
if !matches!(
test_expression(value, checker.semantic()),
Resolution::RelevantLocal
) {
return;
}
checker.report_diagnostic(PandasNuniqueConstantSeriesCheck, 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/pandas_vet/rules/attr.rs | crates/ruff_linter/src/rules/pandas_vet/rules/attr.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::pandas_vet::helpers::{Resolution, test_expression};
/// ## What it does
/// Checks for uses of `.values` on Pandas Series and Index objects.
///
/// ## Why is this bad?
/// The `.values` attribute is ambiguous as its return type is unclear. As
/// such, it is no longer recommended by the Pandas documentation.
///
/// Instead, use `.to_numpy()` to return a NumPy array, or `.array` to return a
/// Pandas `ExtensionArray`.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// animals = pd.read_csv("animals.csv").values # Ambiguous.
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// animals = pd.read_csv("animals.csv").to_numpy() # Explicit.
/// ```
///
/// ## References
/// - [Pandas documentation: Accessing the values in a Series or Index](https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.24.0.html#accessing-the-values-in-a-series-or-index)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfDotValues;
impl Violation for PandasUseOfDotValues {
#[derive_message_formats]
fn message(&self) -> String {
"Use `.to_numpy()` instead of `.values`".to_string()
}
}
/// PD011
pub(crate) fn attr(checker: &Checker, attribute: &ast::ExprAttribute) {
if !checker.semantic().seen_module(Modules::PANDAS) {
return;
}
// Avoid, e.g., `x.values = y`.
if !attribute.ctx.is_load() {
return;
}
// Check for, e.g., `df.values`.
if attribute.attr.as_str() != "values" {
return;
}
// Avoid flagging on function calls (e.g., `df.values()`).
if checker
.semantic()
.current_expression_parent()
.is_some_and(Expr::is_call_expr)
{
return;
}
// Avoid flagging on non-DataFrames (e.g., `{"a": 1}.values`), and on irrelevant bindings
// (like imports).
if !matches!(
test_expression(attribute.value.as_ref(), checker.semantic()),
Resolution::RelevantLocal
) {
return;
}
checker.report_diagnostic(PandasUseOfDotValues, attribute.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/pandas_vet/rules/call.rs | crates/ruff_linter/src/rules/pandas_vet/rules/call.rs | use ruff_python_ast::{self as ast, Expr};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use crate::rules::pandas_vet::helpers::{Resolution, test_expression};
/// ## What it does
/// Checks for uses of `.isnull` on Pandas objects.
///
/// ## Why is this bad?
/// In the Pandas API, `.isna` and `.isnull` are equivalent. For consistency,
/// prefer `.isna` over `.isnull`.
///
/// As a name, `.isna` more accurately reflects the behavior of the method,
/// since these methods check for `NaN` and `NaT` values in addition to `None`
/// values.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// animals_df = pd.read_csv("animals.csv")
/// pd.isnull(animals_df)
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// animals_df = pd.read_csv("animals.csv")
/// pd.isna(animals_df)
/// ```
///
/// ## References
/// - [Pandas documentation: `isnull`](https://pandas.pydata.org/docs/reference/api/pandas.isnull.html#pandas.isnull)
/// - [Pandas documentation: `isna`](https://pandas.pydata.org/docs/reference/api/pandas.isna.html#pandas.isna)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfDotIsNull;
impl Violation for PandasUseOfDotIsNull {
#[derive_message_formats]
fn message(&self) -> String {
"`.isna` is preferred to `.isnull`; functionality is equivalent".to_string()
}
}
/// ## What it does
/// Checks for uses of `.notnull` on Pandas objects.
///
/// ## Why is this bad?
/// In the Pandas API, `.notna` and `.notnull` are equivalent. For consistency,
/// prefer `.notna` over `.notnull`.
///
/// As a name, `.notna` more accurately reflects the behavior of the method,
/// since these methods check for `NaN` and `NaT` values in addition to `None`
/// values.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// animals_df = pd.read_csv("animals.csv")
/// pd.notnull(animals_df)
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// animals_df = pd.read_csv("animals.csv")
/// pd.notna(animals_df)
/// ```
///
/// ## References
/// - [Pandas documentation: `notnull`](https://pandas.pydata.org/docs/reference/api/pandas.notnull.html#pandas.notnull)
/// - [Pandas documentation: `notna`](https://pandas.pydata.org/docs/reference/api/pandas.notna.html#pandas.notna)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfDotNotNull;
impl Violation for PandasUseOfDotNotNull {
#[derive_message_formats]
fn message(&self) -> String {
"`.notna` is preferred to `.notnull`; functionality is equivalent".to_string()
}
}
/// ## What it does
/// Checks for uses of `.pivot` or `.unstack` on Pandas objects.
///
/// ## Why is this bad?
/// Prefer `.pivot_table` to `.pivot` or `.unstack`. `.pivot_table` is more general
/// and can be used to implement the same behavior as `.pivot` and `.unstack`.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// df = pd.read_csv("cities.csv")
/// df.pivot(index="city", columns="year", values="population")
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// df = pd.read_csv("cities.csv")
/// df.pivot_table(index="city", columns="year", values="population")
/// ```
///
/// ## References
/// - [Pandas documentation: Reshaping and pivot tables](https://pandas.pydata.org/docs/user_guide/reshaping.html)
/// - [Pandas documentation: `pivot_table`](https://pandas.pydata.org/docs/reference/api/pandas.pivot_table.html#pandas.pivot_table)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfDotPivotOrUnstack;
impl Violation for PandasUseOfDotPivotOrUnstack {
#[derive_message_formats]
fn message(&self) -> String {
"`.pivot_table` is preferred to `.pivot` or `.unstack`; provides same functionality"
.to_string()
}
}
/// ## What it does
/// Checks for uses of `.stack` on Pandas objects.
///
/// ## Why is this bad?
/// Prefer `.melt` to `.stack`, which has the same functionality but with
/// support for direct column renaming and no dependence on `MultiIndex`.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// cities_df = pd.read_csv("cities.csv")
/// cities_df.set_index("city").stack()
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// cities_df = pd.read_csv("cities.csv")
/// cities_df.melt(id_vars="city")
/// ```
///
/// ## References
/// - [Pandas documentation: `melt`](https://pandas.pydata.org/docs/reference/api/pandas.melt.html)
/// - [Pandas documentation: `stack`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.stack.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfDotStack;
impl Violation for PandasUseOfDotStack {
#[derive_message_formats]
fn message(&self) -> String {
"`.melt` is preferred to `.stack`; provides same functionality".to_string()
}
}
pub(crate) fn call(checker: &Checker, func: &Expr) {
if !checker.semantic().seen_module(Modules::PANDAS) {
return;
}
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func else {
return;
};
// Ignore irrelevant bindings (like imports).
if !matches!(
test_expression(value, checker.semantic()),
Resolution::RelevantLocal | Resolution::PandasModule
) {
return;
}
let range = func.range();
match attr.as_str() {
// PD003
"isnull" if checker.is_rule_enabled(Rule::PandasUseOfDotIsNull) => {
checker.report_diagnostic(PandasUseOfDotIsNull, range);
}
// PD004
"notnull" if checker.is_rule_enabled(Rule::PandasUseOfDotNotNull) => {
checker.report_diagnostic(PandasUseOfDotNotNull, range);
}
// PD010
"pivot" | "unstack" if checker.is_rule_enabled(Rule::PandasUseOfDotPivotOrUnstack) => {
checker.report_diagnostic(PandasUseOfDotPivotOrUnstack, range);
}
// PD013
"stack" if checker.is_rule_enabled(Rule::PandasUseOfDotStack) => {
checker.report_diagnostic(PandasUseOfDotStack, 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/pandas_vet/rules/inplace_argument.rs | crates/ruff_linter/src/rules/pandas_vet/rules/inplace_argument.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_const_true;
use ruff_python_ast::token::{Tokens, parenthesized_range};
use ruff_python_ast::{self as ast, Keyword, Stmt};
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::{Edit, Fix, FixAvailability, Violation};
use ruff_python_semantic::Modules;
/// ## What it does
/// Checks for `inplace=True` usages in `pandas` function and method
/// calls.
///
/// ## Why is this bad?
/// Using `inplace=True` encourages mutation rather than immutable data,
/// which is harder to reason about and may cause bugs. It also removes the
/// ability to use the method chaining style for `pandas` operations.
///
/// Further, in many cases, `inplace=True` does not provide a performance
/// benefit, as `pandas` will often copy `DataFrames` in the background.
///
/// ## Example
/// ```python
/// df.sort_values("col1", inplace=True)
/// ```
///
/// Use instead:
/// ```python
/// sorted_df = df.sort_values("col1")
/// ```
///
/// ## References
/// - [_Why You Should Probably Never Use pandas `inplace=True`_](https://towardsdatascience.com/why-you-should-probably-never-use-pandas-inplace-true-9f9f211849e4)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfInplaceArgument;
impl Violation for PandasUseOfInplaceArgument {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`inplace=True` should be avoided; it has inconsistent behavior".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Assign to variable; remove `inplace` arg".to_string())
}
}
/// PD002
pub(crate) fn inplace_argument(checker: &Checker, call: &ast::ExprCall) {
if !checker.semantic().seen_module(Modules::PANDAS) {
return;
}
// If the function doesn't take an `inplace` argument, abort.
if !call
.func
.as_attribute_expr()
.is_some_and(|func| accepts_inplace_argument(&func.attr))
{
return;
}
let mut seen_star = false;
for keyword in call.arguments.keywords.iter().rev() {
let Some(arg) = &keyword.arg else {
seen_star = true;
continue;
};
if arg == "inplace" {
if is_const_true(&keyword.value) {
let mut diagnostic =
checker.report_diagnostic(PandasUseOfInplaceArgument, keyword.range());
// Avoid applying the fix if:
// 1. The keyword argument is followed by a star argument (we can't be certain that
// the star argument _doesn't_ contain an override).
// 2. The call is part of a larger expression (we're converting an expression to a
// statement, and expressions can't contain statements).
let statement = checker.semantic().current_statement();
if !seen_star
&& checker.semantic().current_expression_parent().is_none()
&& statement.is_expr_stmt()
{
if let Some(fix) = convert_inplace_argument_to_assignment(
call,
keyword,
statement,
checker.tokens(),
checker.locator(),
) {
diagnostic.set_fix(fix);
}
}
}
// Duplicate keywords is a syntax error, so we can stop here.
break;
}
}
}
/// Remove the `inplace` argument from a function call and replace it with an
/// assignment.
fn convert_inplace_argument_to_assignment(
call: &ast::ExprCall,
keyword: &Keyword,
statement: &Stmt,
tokens: &Tokens,
locator: &Locator,
) -> Option<Fix> {
// Add the assignment.
let attr = call.func.as_attribute_expr()?;
let insert_assignment = Edit::insertion(
format!("{name} = ", name = locator.slice(attr.value.range())),
parenthesized_range(call.into(), statement.into(), tokens)
.unwrap_or(call.range())
.start(),
);
// Remove the `inplace` argument.
let remove_argument = remove_argument(
keyword,
&call.arguments,
Parentheses::Preserve,
locator.contents(),
tokens,
)
.ok()?;
Some(Fix::unsafe_edits(insert_assignment, [remove_argument]))
}
/// Returns `true` if the given method accepts an `inplace` argument when used on a Pandas
/// `DataFrame`, `Series`, or `Index`.
///
/// See: <https://pandas.pydata.org/docs/reference/frame.html>
fn accepts_inplace_argument(method: &str) -> bool {
matches!(
method,
"where"
| "mask"
| "query"
| "clip"
| "eval"
| "backfill"
| "bfill"
| "ffill"
| "fillna"
| "interpolate"
| "dropna"
| "pad"
| "replace"
| "drop"
| "drop_duplicates"
| "rename"
| "rename_axis"
| "reset_index"
| "set_index"
| "sort_values"
| "sort_index"
| "set_names"
)
}
| 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/pandas_vet/rules/mod.rs | crates/ruff_linter/src/rules/pandas_vet/rules/mod.rs | pub(crate) use assignment_to_df::*;
pub(crate) use attr::*;
pub(crate) use call::*;
pub(crate) use inplace_argument::*;
pub(crate) use nunique_constant_series_check::*;
pub(crate) use pd_merge::*;
pub(crate) use read_table::*;
pub(crate) use subscript::*;
pub(crate) mod assignment_to_df;
pub(crate) mod attr;
pub(crate) mod call;
pub(crate) mod inplace_argument;
pub(crate) mod nunique_constant_series_check;
pub(crate) mod pd_merge;
pub(crate) mod read_table;
pub(crate) mod subscript;
| 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/pandas_vet/rules/assignment_to_df.rs | crates/ruff_linter/src/rules/pandas_vet/rules/assignment_to_df.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::Ranged;
use crate::{Violation, checkers::ast::Checker};
/// ## Removed
///
/// This rule has been removed as it's highly opinionated and overly strict in most cases.
///
/// ## What it does
/// Checks for assignments to the variable `df`.
///
/// ## Why is this bad?
/// Although `df` is a common variable name for a Pandas `DataFrame`, it's not a
/// great variable name for production code, as it's non-descriptive and
/// prone to name conflicts.
///
/// Instead, use a more descriptive variable name.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// df = pd.read_csv("animals.csv")
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// animals = pd.read_csv("animals.csv")
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(removed_since = "0.13.0")]
pub(crate) struct PandasDfVariableName;
impl Violation for PandasDfVariableName {
#[derive_message_formats]
fn message(&self) -> String {
"Avoid using the generic variable name `df` for DataFrames".to_string()
}
}
/// PD901
pub(crate) fn assignment_to_df(checker: &Checker, targets: &[Expr]) {
let [target] = targets else {
return;
};
let Expr::Name(ast::ExprName { id, .. }) = target else {
return;
};
if id != "df" {
return;
}
checker.report_diagnostic(PandasDfVariableName, target.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/pandas_vet/rules/read_table.rs | crates/ruff_linter/src/rules/pandas_vet/rules/read_table.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::Expr;
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 `pd.read_table` to read CSV files.
///
/// ## Why is this bad?
/// In the Pandas API, `pd.read_csv` and `pd.read_table` are equivalent apart
/// from their default separator: `pd.read_csv` defaults to a comma (`,`),
/// while `pd.read_table` defaults to a tab (`\t`) as the default separator.
///
/// Prefer `pd.read_csv` over `pd.read_table` when reading comma-separated
/// data (like CSV files), as it is more idiomatic.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// cities_df = pd.read_table("cities.csv", sep=",")
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// cities_df = pd.read_csv("cities.csv")
/// ```
///
/// ## References
/// - [Pandas documentation: `read_csv`](https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html#pandas.read_csv)
/// - [Pandas documentation: `read_table`](https://pandas.pydata.org/docs/reference/api/pandas.read_table.html#pandas.read_table)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfDotReadTable;
impl Violation for PandasUseOfDotReadTable {
#[derive_message_formats]
fn message(&self) -> String {
"Use `.read_csv` instead of `.read_table` to read CSV files".to_string()
}
}
/// PD012
pub(crate) fn use_of_read_table(checker: &Checker, call: &ast::ExprCall) {
if !checker.semantic().seen_module(Modules::PANDAS) {
return;
}
if checker
.semantic()
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["pandas", "read_table"]))
{
if let Some(Expr::StringLiteral(ast::ExprStringLiteral { value, .. })) = call
.arguments
.find_keyword("sep")
.map(|keyword| &keyword.value)
{
if value == "," {
checker.report_diagnostic(PandasUseOfDotReadTable, 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/pandas_vet/rules/subscript.rs | crates/ruff_linter/src/rules/pandas_vet/rules/subscript.rs | use ruff_python_ast::{self as ast, Expr};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use crate::rules::pandas_vet::helpers::{Resolution, test_expression};
/// ## What it does
/// Checks for uses of `.ix` on Pandas objects.
///
/// ## Why is this bad?
/// The `.ix` method is deprecated as its behavior is ambiguous. Specifically,
/// it's often unclear whether `.ix` is indexing by label or by ordinal position.
///
/// Instead, prefer the `.loc` method for label-based indexing, and `.iloc` for
/// ordinal indexing.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// students_df = pd.read_csv("students.csv")
/// students_df.ix[0] # 0th row or row with label 0?
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// students_df = pd.read_csv("students.csv")
/// students_df.iloc[0] # 0th row.
/// ```
///
/// ## References
/// - [Pandas release notes: Deprecate `.ix`](https://pandas.pydata.org/pandas-docs/version/0.20/whatsnew.html#deprecate-ix)
/// - [Pandas documentation: `loc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html)
/// - [Pandas documentation: `iloc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfDotIx;
impl Violation for PandasUseOfDotIx {
#[derive_message_formats]
fn message(&self) -> String {
"`.ix` is deprecated; use more explicit `.loc` or `.iloc`".to_string()
}
}
/// ## What it does
/// Checks for uses of `.at` on Pandas objects.
///
/// ## Why is this bad?
/// The `.at` method selects a single value from a `DataFrame` or Series based on
/// a label index, and is slightly faster than using `.loc`. However, `.loc` is
/// more idiomatic and versatile, as it can be used to select multiple values at
/// once.
///
/// If performance is an important consideration, convert the object to a NumPy
/// array, which will provide a much greater performance boost than using `.at`
/// over `.loc`.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// students_df = pd.read_csv("students.csv")
/// students_df.at["Maria"]
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// students_df = pd.read_csv("students.csv")
/// students_df.loc["Maria"]
/// ```
///
/// ## References
/// - [Pandas documentation: `loc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html)
/// - [Pandas documentation: `at`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.at.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfDotAt;
impl Violation for PandasUseOfDotAt {
#[derive_message_formats]
fn message(&self) -> String {
"Use `.loc` instead of `.at`. If speed is important, use NumPy.".to_string()
}
}
/// ## What it does
/// Checks for uses of `.iat` on Pandas objects.
///
/// ## Why is this bad?
/// The `.iat` method selects a single value from a `DataFrame` or Series based
/// on an ordinal index, and is slightly faster than using `.iloc`. However,
/// `.iloc` is more idiomatic and versatile, as it can be used to select
/// multiple values at once.
///
/// If performance is an important consideration, convert the object to a NumPy
/// array, which will provide a much greater performance boost than using `.iat`
/// over `.iloc`.
///
/// ## Example
/// ```python
/// import pandas as pd
///
/// students_df = pd.read_csv("students.csv")
/// students_df.iat[0]
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
///
/// students_df = pd.read_csv("students.csv")
/// students_df.iloc[0]
/// ```
///
/// Or, using NumPy:
/// ```python
/// import numpy as np
/// import pandas as pd
///
/// students_df = pd.read_csv("students.csv")
/// students_df.to_numpy()[0]
/// ```
///
/// ## References
/// - [Pandas documentation: `iloc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html)
/// - [Pandas documentation: `iat`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iat.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.188")]
pub(crate) struct PandasUseOfDotIat;
impl Violation for PandasUseOfDotIat {
#[derive_message_formats]
fn message(&self) -> String {
"Use `.iloc` instead of `.iat`. If speed is important, use NumPy.".to_string()
}
}
pub(crate) fn subscript(checker: &Checker, value: &Expr, expr: &Expr) {
if !checker.semantic().seen_module(Modules::PANDAS) {
return;
}
let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = value else {
return;
};
// Avoid flagging on non-DataFrames (e.g., `{"a": 1}.at[0]`), and on irrelevant bindings
// (like imports).
if !matches!(
test_expression(value, checker.semantic()),
Resolution::RelevantLocal
) {
return;
}
let range = expr.range();
match attr.as_str() {
// PD007
"ix" if checker.is_rule_enabled(Rule::PandasUseOfDotIx) => {
let mut diagnostic = checker.report_diagnostic(PandasUseOfDotIx, range);
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Deprecated);
}
// PD008
"at" if checker.is_rule_enabled(Rule::PandasUseOfDotAt) => {
checker.report_diagnostic(PandasUseOfDotAt, range);
}
// PD009
"iat" if checker.is_rule_enabled(Rule::PandasUseOfDotIat) => {
checker.report_diagnostic(PandasUseOfDotIat, 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_pyi/mod.rs | crates/ruff_linter/src/rules/flake8_pyi/mod.rs | //! Rules from [flake8-pyi](https://pypi.org/project/flake8-pyi/).
pub(crate) mod rules;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use ruff_python_ast::PythonVersion;
use test_case::test_case;
use crate::registry::Rule;
use crate::rules::pep8_naming;
use crate::settings::types::PreviewMode;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test_case(Rule::AnyEqNeAnnotation, Path::new("PYI032.py"))]
#[test_case(Rule::AnyEqNeAnnotation, Path::new("PYI032.pyi"))]
#[test_case(Rule::ArgumentDefaultInStub, Path::new("PYI014.py"))]
#[test_case(Rule::ArgumentDefaultInStub, Path::new("PYI014.pyi"))]
#[test_case(Rule::AssignmentDefaultInStub, Path::new("PYI015.py"))]
#[test_case(Rule::AssignmentDefaultInStub, Path::new("PYI015.pyi"))]
#[test_case(Rule::BadExitAnnotation, Path::new("PYI036.py"))]
#[test_case(Rule::BadExitAnnotation, Path::new("PYI036.pyi"))]
#[test_case(Rule::BadVersionInfoComparison, Path::new("PYI006.py"))]
#[test_case(Rule::BadVersionInfoComparison, Path::new("PYI006.pyi"))]
#[test_case(Rule::BadVersionInfoOrder, Path::new("PYI066.py"))]
#[test_case(Rule::BadVersionInfoOrder, Path::new("PYI066.pyi"))]
#[test_case(Rule::ByteStringUsage, Path::new("PYI057.py"))]
#[test_case(Rule::ByteStringUsage, Path::new("PYI057.pyi"))]
#[test_case(Rule::CollectionsNamedTuple, Path::new("PYI024.py"))]
#[test_case(Rule::CollectionsNamedTuple, Path::new("PYI024.pyi"))]
#[test_case(Rule::ComplexAssignmentInStub, Path::new("PYI017.py"))]
#[test_case(Rule::ComplexAssignmentInStub, Path::new("PYI017.pyi"))]
#[test_case(Rule::ComplexIfStatementInStub, Path::new("PYI002.py"))]
#[test_case(Rule::ComplexIfStatementInStub, Path::new("PYI002.pyi"))]
#[test_case(Rule::DocstringInStub, Path::new("PYI021.py"))]
#[test_case(Rule::DocstringInStub, Path::new("PYI021.pyi"))]
#[test_case(Rule::DuplicateLiteralMember, Path::new("PYI062.py"))]
#[test_case(Rule::DuplicateLiteralMember, Path::new("PYI062.pyi"))]
#[test_case(Rule::DuplicateUnionMember, Path::new("PYI016.py"))]
#[test_case(Rule::DuplicateUnionMember, Path::new("PYI016.pyi"))]
#[test_case(Rule::EllipsisInNonEmptyClassBody, Path::new("PYI013.py"))]
#[test_case(Rule::EllipsisInNonEmptyClassBody, Path::new("PYI013.pyi"))]
#[test_case(Rule::FutureAnnotationsInStub, Path::new("PYI044.py"))]
#[test_case(Rule::FutureAnnotationsInStub, Path::new("PYI044.pyi"))]
#[test_case(Rule::GeneratorReturnFromIterMethod, Path::new("PYI058.py"))]
#[test_case(Rule::GeneratorReturnFromIterMethod, Path::new("PYI058.pyi"))]
#[test_case(Rule::GenericNotLastBaseClass, Path::new("PYI059.py"))]
#[test_case(Rule::GenericNotLastBaseClass, Path::new("PYI059.pyi"))]
#[test_case(Rule::IterMethodReturnIterable, Path::new("PYI045.py"))]
#[test_case(Rule::IterMethodReturnIterable, Path::new("PYI045.pyi"))]
#[test_case(Rule::NoReturnArgumentAnnotationInStub, Path::new("PYI050.py"))]
#[test_case(Rule::NoReturnArgumentAnnotationInStub, Path::new("PYI050.pyi"))]
#[test_case(Rule::NonEmptyStubBody, Path::new("PYI010.py"))]
#[test_case(Rule::NonEmptyStubBody, Path::new("PYI010.pyi"))]
#[test_case(Rule::NonSelfReturnType, Path::new("PYI034.py"))]
#[test_case(Rule::NonSelfReturnType, Path::new("PYI034.pyi"))]
#[test_case(Rule::NumericLiteralTooLong, Path::new("PYI054.py"))]
#[test_case(Rule::NumericLiteralTooLong, Path::new("PYI054.pyi"))]
#[test_case(Rule::PassInClassBody, Path::new("PYI012.py"))]
#[test_case(Rule::PassInClassBody, Path::new("PYI012.pyi"))]
#[test_case(Rule::PassStatementStubBody, Path::new("PYI009.py"))]
#[test_case(Rule::PassStatementStubBody, Path::new("PYI009.pyi"))]
#[test_case(Rule::PatchVersionComparison, Path::new("PYI004.py"))]
#[test_case(Rule::PatchVersionComparison, Path::new("PYI004.pyi"))]
#[test_case(Rule::QuotedAnnotationInStub, Path::new("PYI020.py"))]
#[test_case(Rule::QuotedAnnotationInStub, Path::new("PYI020.pyi"))]
#[test_case(Rule::Pep484StylePositionalOnlyParameter, Path::new("PYI063.py"))]
#[test_case(Rule::Pep484StylePositionalOnlyParameter, Path::new("PYI063.pyi"))]
#[test_case(Rule::RedundantFinalLiteral, Path::new("PYI064.py"))]
#[test_case(Rule::RedundantFinalLiteral, Path::new("PYI064.pyi"))]
#[test_case(Rule::RedundantLiteralUnion, Path::new("PYI051.py"))]
#[test_case(Rule::RedundantLiteralUnion, Path::new("PYI051.pyi"))]
#[test_case(Rule::RedundantNumericUnion, Path::new("PYI041_1.py"))]
#[test_case(Rule::RedundantNumericUnion, Path::new("PYI041_1.pyi"))]
#[test_case(Rule::RedundantNumericUnion, Path::new("PYI041_2.py"))]
#[test_case(Rule::SnakeCaseTypeAlias, Path::new("PYI042.py"))]
#[test_case(Rule::SnakeCaseTypeAlias, Path::new("PYI042.pyi"))]
#[test_case(Rule::StrOrReprDefinedInStub, Path::new("PYI029.py"))]
#[test_case(Rule::StrOrReprDefinedInStub, Path::new("PYI029.pyi"))]
#[test_case(Rule::StringOrBytesTooLong, Path::new("PYI053.py"))]
#[test_case(Rule::StringOrBytesTooLong, Path::new("PYI053.pyi"))]
#[test_case(Rule::StubBodyMultipleStatements, Path::new("PYI048.py"))]
#[test_case(Rule::StubBodyMultipleStatements, Path::new("PYI048.pyi"))]
#[test_case(Rule::TSuffixedTypeAlias, Path::new("PYI043.py"))]
#[test_case(Rule::TSuffixedTypeAlias, Path::new("PYI043.pyi"))]
#[test_case(Rule::TypeAliasWithoutAnnotation, Path::new("PYI026.py"))]
#[test_case(Rule::TypeAliasWithoutAnnotation, Path::new("PYI026.pyi"))]
#[test_case(Rule::TypeCommentInStub, Path::new("PYI033.py"))]
#[test_case(Rule::TypeCommentInStub, Path::new("PYI033.pyi"))]
#[test_case(Rule::TypedArgumentDefaultInStub, Path::new("PYI011.py"))]
#[test_case(Rule::TypedArgumentDefaultInStub, Path::new("PYI011.pyi"))]
#[test_case(Rule::UnaliasedCollectionsAbcSetImport, Path::new("PYI025_1.py"))]
#[test_case(Rule::UnaliasedCollectionsAbcSetImport, Path::new("PYI025_1.pyi"))]
#[test_case(Rule::UnaliasedCollectionsAbcSetImport, Path::new("PYI025_2.py"))]
#[test_case(Rule::UnaliasedCollectionsAbcSetImport, Path::new("PYI025_2.pyi"))]
#[test_case(Rule::UnaliasedCollectionsAbcSetImport, Path::new("PYI025_3.py"))]
#[test_case(Rule::UnaliasedCollectionsAbcSetImport, Path::new("PYI025_3.pyi"))]
#[test_case(Rule::UnannotatedAssignmentInStub, Path::new("PYI052.py"))]
#[test_case(Rule::UnannotatedAssignmentInStub, Path::new("PYI052.pyi"))]
#[test_case(Rule::UnassignedSpecialVariableInStub, Path::new("PYI035.py"))]
#[test_case(Rule::UnassignedSpecialVariableInStub, Path::new("PYI035.pyi"))]
#[test_case(Rule::UnnecessaryLiteralUnion, Path::new("PYI030.py"))]
#[test_case(Rule::UnnecessaryLiteralUnion, Path::new("PYI030.pyi"))]
#[test_case(Rule::UnnecessaryTypeUnion, Path::new("PYI055.py"))]
#[test_case(Rule::UnnecessaryTypeUnion, Path::new("PYI055.pyi"))]
#[test_case(Rule::UnprefixedTypeParam, Path::new("PYI001.py"))]
#[test_case(Rule::UnprefixedTypeParam, Path::new("PYI001.pyi"))]
#[test_case(Rule::UnrecognizedPlatformCheck, Path::new("PYI007.py"))]
#[test_case(Rule::UnrecognizedPlatformCheck, Path::new("PYI007.pyi"))]
#[test_case(Rule::UnrecognizedPlatformName, Path::new("PYI008.py"))]
#[test_case(Rule::UnrecognizedPlatformName, Path::new("PYI008.pyi"))]
#[test_case(Rule::UnrecognizedVersionInfoCheck, Path::new("PYI003.py"))]
#[test_case(Rule::UnrecognizedVersionInfoCheck, Path::new("PYI003.pyi"))]
#[test_case(Rule::UnsupportedMethodCallOnAll, Path::new("PYI056.py"))]
#[test_case(Rule::UnsupportedMethodCallOnAll, Path::new("PYI056.pyi"))]
#[test_case(Rule::UnusedPrivateProtocol, Path::new("PYI046.py"))]
#[test_case(Rule::UnusedPrivateProtocol, Path::new("PYI046.pyi"))]
#[test_case(Rule::UnusedPrivateTypeAlias, Path::new("PYI047.py"))]
#[test_case(Rule::UnusedPrivateTypeAlias, Path::new("PYI047.pyi"))]
#[test_case(Rule::UnusedPrivateTypeVar, Path::new("PYI018.py"))]
#[test_case(Rule::UnusedPrivateTypeVar, Path::new("PYI018.pyi"))]
#[test_case(Rule::UnusedPrivateTypedDict, Path::new("PYI049.py"))]
#[test_case(Rule::UnusedPrivateTypedDict, Path::new("PYI049.pyi"))]
#[test_case(Rule::WrongTupleLengthVersionComparison, Path::new("PYI005.py"))]
#[test_case(Rule::WrongTupleLengthVersionComparison, Path::new("PYI005.pyi"))]
#[test_case(Rule::RedundantNoneLiteral, Path::new("PYI061.py"))]
#[test_case(Rule::RedundantNoneLiteral, Path::new("PYI061.pyi"))]
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_pyi").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::CustomTypeVarForSelf, Path::new("PYI019_0.py"))]
#[test_case(Rule::CustomTypeVarForSelf, Path::new("PYI019_0.pyi"))]
#[test_case(Rule::CustomTypeVarForSelf, Path::new("PYI019_1.pyi"))]
fn custom_classmethod_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_pyi").join(path).as_path(),
&settings::LinterSettings {
pep8_naming: pep8_naming::settings::Settings {
classmethod_decorators: vec!["foo_classmethod".to_string()],
..pep8_naming::settings::Settings::default()
},
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::TypeAliasWithoutAnnotation, Path::new("PYI026.py"))]
#[test_case(Rule::TypeAliasWithoutAnnotation, Path::new("PYI026.pyi"))]
#[test_case(Rule::RedundantNoneLiteral, Path::new("PYI061.py"))]
#[test_case(Rule::RedundantNoneLiteral, Path::new("PYI061.pyi"))]
fn py38(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("py38_{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("flake8_pyi").join(path).as_path(),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY38.into(),
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::DuplicateUnionMember, Path::new("PYI016.py"))]
#[test_case(Rule::DuplicateUnionMember, Path::new("PYI016.pyi"))]
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_pyi").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("PYI021_1.pyi"))]
fn pyi021_pie790_isolation_check(path: &Path) -> Result<()> {
let diagnostics = test_path(
Path::new("flake8_pyi").join(path).as_path(),
&settings::LinterSettings::for_rules([
Rule::DocstringInStub,
Rule::UnnecessaryPlaceholder,
]),
)?;
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_pyi/rules/unsupported_method_call_on_all.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/unsupported_method_call_on_all.rs | use ruff_python_ast::{self as ast, Expr};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks that `append`, `extend` and `remove` methods are not called on
/// `__all__`.
///
/// ## Why is this bad?
/// Different type checkers have varying levels of support for calling these
/// methods on `__all__`. Instead, use the `+=` operator to add items to
/// `__all__`, which is known to be supported by all major type checkers.
///
/// ## Example
/// ```pyi
/// import sys
///
/// __all__ = ["A", "B"]
///
/// if sys.version_info >= (3, 10):
/// __all__.append("C")
///
/// if sys.version_info >= (3, 11):
/// __all__.remove("B")
/// ```
///
/// Use instead:
/// ```pyi
/// import sys
///
/// __all__ = ["A"]
///
/// if sys.version_info < (3, 11):
/// __all__ += ["B"]
///
/// if sys.version_info >= (3, 10):
/// __all__ += ["C"]
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.281")]
pub(crate) struct UnsupportedMethodCallOnAll {
name: String,
}
impl Violation for UnsupportedMethodCallOnAll {
#[derive_message_formats]
fn message(&self) -> String {
let UnsupportedMethodCallOnAll { name } = self;
format!(
"Calling `.{name}()` on `__all__` may not be supported by all type checkers (use `+=` instead)"
)
}
}
/// PYI056
pub(crate) fn unsupported_method_call_on_all(checker: &Checker, func: &Expr) {
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func else {
return;
};
let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() else {
return;
};
if id.as_str() != "__all__" {
return;
}
if !is_unsupported_method(attr.as_str()) {
return;
}
checker.report_diagnostic(
UnsupportedMethodCallOnAll {
name: attr.to_string(),
},
func.range(),
);
}
fn is_unsupported_method(name: &str) -> bool {
matches!(name, "append" | "extend" | "remove")
}
| 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_pyi/rules/quoted_annotation_in_stub.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/quoted_annotation_in_stub.rs | use ruff_text_size::TextRange;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for quoted type annotations in stub (`.pyi`) files, which should be avoided.
///
/// ## Why is this bad?
/// Stub files natively support forward references in all contexts, as stubs
/// are never executed at runtime. (They should be thought of as "data files"
/// for type checkers and IDEs.) As such, quotes are never required for type
/// annotations in stub files, and should be omitted.
///
/// ## Example
///
/// ```pyi
/// def function() -> "int": ...
/// ```
///
/// Use instead:
///
/// ```pyi
/// def function() -> int: ...
/// ```
///
/// ## References
/// - [Typing documentation - Writing and Maintaining Stub Files](https://typing.python.org/en/latest/guides/writing_stubs.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.265")]
pub(crate) struct QuotedAnnotationInStub;
impl AlwaysFixableViolation for QuotedAnnotationInStub {
#[derive_message_formats]
fn message(&self) -> String {
"Quoted annotations should not be included in stubs".to_string()
}
fn fix_title(&self) -> String {
"Remove quotes".to_string()
}
}
/// PYI020
pub(crate) fn quoted_annotation_in_stub(checker: &Checker, annotation: &str, range: TextRange) {
let mut diagnostic = checker.report_diagnostic(QuotedAnnotationInStub, range);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
annotation.to_string(),
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_pyi/rules/pass_in_class_body.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/pass_in_class_body.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix;
use crate::{AlwaysFixableViolation, Fix};
/// ## What it does
/// Checks for the presence of the `pass` statement in non-empty class bodies
/// in `.pyi` files.
///
/// ## Why is this bad?
/// The `pass` statement is always unnecessary in non-empty class bodies in
/// stubs.
///
/// ## Example
/// ```pyi
/// class MyClass:
/// x: int
/// pass
/// ```
///
/// Use instead:
/// ```pyi
/// class MyClass:
/// x: int
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.260")]
pub(crate) struct PassInClassBody;
impl AlwaysFixableViolation for PassInClassBody {
#[derive_message_formats]
fn message(&self) -> String {
"Class body must not contain `pass`".to_string()
}
fn fix_title(&self) -> String {
"Remove unnecessary `pass`".to_string()
}
}
/// PYI012
pub(crate) fn pass_in_class_body(checker: &Checker, class_def: &ast::StmtClassDef) {
// `pass` is required in these situations (or handled by `pass_statement_stub_body`).
if class_def.body.len() < 2 {
return;
}
for stmt in &class_def.body {
if !stmt.is_pass_stmt() {
continue;
}
let mut diagnostic = checker.report_diagnostic(PassInClassBody, stmt.range());
let edit = fix::edits::delete_stmt(stmt, Some(stmt), checker.locator(), checker.indexer());
diagnostic.set_fix(Fix::safe_edit(edit).isolate(Checker::isolation(
checker.semantic().current_statement_id(),
)));
}
}
| 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_pyi/rules/unaliased_collections_abc_set_import.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/unaliased_collections_abc_set_import.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::Imported;
use ruff_python_semantic::{Binding, BindingKind, Scope};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::renamer::Renamer;
use crate::{Applicability, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `from collections.abc import Set` imports that do not alias
/// `Set` to `AbstractSet`.
///
/// ## Why is this bad?
/// The `Set` type in `collections.abc` is an abstract base class for set-like types.
/// It is easily confused with, and not equivalent to, the `set` builtin.
///
/// To avoid confusion, `Set` should be aliased to `AbstractSet` when imported. This
/// makes it clear that the imported type is an abstract base class, and not the
/// `set` builtin.
///
/// ## Example
/// ```pyi
/// from collections.abc import Set
/// ```
///
/// Use instead:
/// ```pyi
/// from collections.abc import Set as AbstractSet
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe for `Set` imports defined at the
/// top-level of a `.py` module. Top-level symbols are implicitly exported by the
/// module, and so renaming a top-level symbol may break downstream modules
/// that import it.
///
/// The same is not true for `.pyi` files, where imported symbols are only
/// re-exported if they are included in `__all__`, use a "redundant"
/// `import foo as foo` alias, or are imported via a `*` import. As such, the
/// fix is marked as safe in more cases for `.pyi` files.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.271")]
pub(crate) struct UnaliasedCollectionsAbcSetImport;
impl Violation for UnaliasedCollectionsAbcSetImport {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Alias `Set` to `AbstractSet`".to_string())
}
}
/// PYI025
pub(crate) fn unaliased_collections_abc_set_import(checker: &Checker, binding: &Binding) {
let BindingKind::FromImport(import) = &binding.kind else {
return;
};
if !matches!(
import.qualified_name().segments(),
["collections", "abc", "Set"]
) {
return;
}
let name = binding.name(checker.source());
if name == "AbstractSet" {
return;
}
let mut diagnostic =
checker.report_diagnostic(UnaliasedCollectionsAbcSetImport, binding.range());
if checker.semantic().is_available("AbstractSet") {
diagnostic.try_set_fix(|| {
let semantic = checker.semantic();
let scope = &semantic.scopes[binding.scope];
let (edit, rest) =
Renamer::rename(name, "AbstractSet", scope, semantic, checker.stylist())?;
let applicability = determine_applicability(binding, scope, checker);
Ok(Fix::applicable_edits(edit, rest, applicability))
});
}
}
fn determine_applicability(binding: &Binding, scope: &Scope, checker: &Checker) -> Applicability {
// If it's not in a module scope, the import can't be implicitly re-exported,
// so always mark it as safe
if !scope.kind.is_module() {
return Applicability::Safe;
}
// If it's not a stub and it's in the module scope, always mark the fix as unsafe
if !checker.source_type.is_stub() {
return Applicability::Unsafe;
}
// If the import was `from collections.abc import Set as Set`,
// it's being explicitly re-exported: mark the fix as unsafe
if binding.is_explicit_export() {
return Applicability::Unsafe;
}
// If it's included in `__all__`, mark the fix as unsafe
if binding.references().any(|reference| {
checker
.semantic()
.reference(reference)
.in_dunder_all_definition()
}) {
return Applicability::Unsafe;
}
// Anything else in a stub, and it's a safe fix:
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_pyi/rules/collections_named_tuple.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/collections_named_tuple.rs | use ruff_python_ast::Expr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
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 `collections.namedtuple` in stub files.
///
/// ## Why is this bad?
/// `typing.NamedTuple` is the "typed version" of `collections.namedtuple`.
///
/// Inheriting from `typing.NamedTuple` creates a custom `tuple` subclass in
/// the same way as using the `collections.namedtuple` factory function.
/// However, using `typing.NamedTuple` allows you to provide a type annotation
/// for each field in the class. This means that type checkers will have more
/// information to work with, and will be able to analyze your code more
/// precisely.
///
/// ## Example
/// ```pyi
/// from collections import namedtuple
///
/// Person = namedtuple("Person", ["name", "age"])
/// ```
///
/// Use instead:
/// ```pyi
/// from typing import NamedTuple
///
/// class Person(NamedTuple):
/// name: str
/// age: int
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.271")]
pub(crate) struct CollectionsNamedTuple;
impl Violation for CollectionsNamedTuple {
#[derive_message_formats]
fn message(&self) -> String {
"Use `typing.NamedTuple` instead of `collections.namedtuple`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `typing.NamedTuple`".to_string())
}
}
/// PYI024
pub(crate) fn collections_named_tuple(checker: &Checker, expr: &Expr) {
if !checker.semantic().seen_module(Modules::COLLECTIONS) {
return;
}
if checker
.semantic()
.resolve_qualified_name(expr)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["collections", "namedtuple"])
})
{
checker.report_diagnostic(CollectionsNamedTuple, 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/flake8_pyi/rules/type_alias_naming.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/type_alias_naming.rs | use ruff_python_ast::{self as ast, Expr};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for type aliases that do not use the CamelCase naming convention.
///
/// ## Why is this bad?
/// It's conventional to use the CamelCase naming convention for type aliases,
/// to distinguish them from other variables.
///
/// ## Example
/// ```pyi
/// from typing import TypeAlias
///
/// type_alias_name: TypeAlias = int
/// ```
///
/// Use instead:
/// ```pyi
/// from typing import TypeAlias
///
/// TypeAliasName: TypeAlias = int
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.265")]
pub(crate) struct SnakeCaseTypeAlias {
name: String,
}
impl Violation for SnakeCaseTypeAlias {
#[derive_message_formats]
fn message(&self) -> String {
let Self { name } = self;
format!("Type alias `{name}` should be CamelCase")
}
}
/// ## What it does
/// Checks for private type alias definitions suffixed with 'T'.
///
/// ## Why is this bad?
/// It's conventional to use the 'T' suffix for type variables; the use of
/// such a suffix implies that the object is a `TypeVar`.
///
/// Adding the 'T' suffix to a non-`TypeVar`, it can be misleading and should
/// be avoided.
///
/// ## Example
/// ```pyi
/// from typing import TypeAlias
///
/// _MyTypeT: TypeAlias = int
/// ```
///
/// Use instead:
/// ```pyi
/// from typing import TypeAlias
///
/// _MyType: TypeAlias = int
/// ```
///
/// ## References
/// - [PEP 484: Type Aliases](https://peps.python.org/pep-0484/#type-aliases)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.265")]
pub(crate) struct TSuffixedTypeAlias {
name: String,
}
impl Violation for TSuffixedTypeAlias {
#[derive_message_formats]
fn message(&self) -> String {
let Self { name } = self;
format!(
"Private type alias `{name}` should not be suffixed with `T` (the `T` suffix implies that an object is a `TypeVar`)"
)
}
}
/// Return `true` if the given name is a `snake_case` type alias. In this context, we match against
/// any name that begins with an optional underscore, followed by at least one lowercase letter.
fn is_snake_case_type_alias(name: &str) -> bool {
let mut chars = name.chars();
matches!(
(chars.next(), chars.next()),
(Some('_'), Some('0'..='9' | 'a'..='z')) | (Some('0'..='9' | 'a'..='z'), ..)
)
}
/// Return `true` if the given name is a T-suffixed type alias. In this context, we match against
/// any name that begins with an underscore, and ends in a lowercase letter, followed by `T`,
/// followed by an optional digit.
fn is_t_suffixed_type_alias(name: &str) -> bool {
// A T-suffixed, private type alias must begin with an underscore.
if !name.starts_with('_') {
return false;
}
// It must end in a lowercase letter, followed by `T`, and (optionally) a digit.
let mut chars = name.chars().rev();
matches!(
(chars.next(), chars.next(), chars.next()),
(Some('0'..='9'), Some('T'), Some('a'..='z')) | (Some('T'), Some('a'..='z'), _)
)
}
/// PYI042
pub(crate) fn snake_case_type_alias(checker: &Checker, target: &Expr) {
if let Expr::Name(ast::ExprName { id, range, .. }) = target {
if !is_snake_case_type_alias(id) {
return;
}
checker.report_diagnostic(
SnakeCaseTypeAlias {
name: id.to_string(),
},
*range,
);
}
}
/// PYI043
pub(crate) fn t_suffixed_type_alias(checker: &Checker, target: &Expr) {
if let Expr::Name(ast::ExprName { id, range, .. }) = target {
if !is_t_suffixed_type_alias(id) {
return;
}
checker.report_diagnostic(
TSuffixedTypeAlias {
name: id.to_string(),
},
*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_pyi/rules/bad_version_info_comparison.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs | use ruff_python_ast::{self as ast, CmpOp, Expr};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::preview::is_bad_version_info_in_non_stub_enabled;
use crate::registry::Rule;
/// ## What it does
/// Checks for uses of comparators other than `<` and `>=` for
/// `sys.version_info` checks. All other comparators, such
/// as `>`, `<=`, and `==`, are banned.
///
/// ## Why is this bad?
/// Comparing `sys.version_info` with `==` or `<=` has unexpected behavior
/// and can lead to bugs.
///
/// For example, `sys.version_info > (3, 8, 1)` will resolve to `True` if your
/// Python version is 3.8.1; meanwhile, `sys.version_info <= (3, 8)` will _not_
/// resolve to `True` if your Python version is 3.8.10:
///
/// ```python
/// >>> import sys
/// >>> print(sys.version_info)
/// sys.version_info(major=3, minor=8, micro=10, releaselevel='final', serial=0)
/// >>> print(sys.version_info > (3, 8))
/// True
/// >>> print(sys.version_info == (3, 8))
/// False
/// >>> print(sys.version_info <= (3, 8))
/// False
/// >>> print(sys.version_info in (3, 8))
/// False
/// ```
///
/// ## Example
/// ```py
/// import sys
///
/// if sys.version_info > (3, 8): ...
/// ```
///
/// Use instead:
/// ```py
/// import sys
///
/// if sys.version_info >= (3, 9): ...
/// ```
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.254")]
pub(crate) struct BadVersionInfoComparison;
impl Violation for BadVersionInfoComparison {
#[derive_message_formats]
fn message(&self) -> String {
"Use `<` or `>=` for `sys.version_info` comparisons".to_string()
}
}
/// ## What it does
/// Checks for code that branches on `sys.version_info` comparisons where
/// branches corresponding to older Python versions come before branches
/// corresponding to newer Python versions.
///
/// ## Why is this bad?
/// As a convention, branches that correspond to newer Python versions should
/// come first. This makes it easier to understand the desired behavior, which
/// typically corresponds to the latest Python versions.
///
/// This rule enforces the convention by checking for `if` tests that compare
/// `sys.version_info` with `<` rather than `>=`.
///
/// By default, this rule only applies to stub files.
/// In [preview], it will also flag this anti-pattern in non-stub files.
///
/// ## Example
///
/// ```pyi
/// import sys
///
/// if sys.version_info < (3, 10):
/// def read_data(x, *, preserve_order=True): ...
///
/// else:
/// def read_data(x): ...
/// ```
///
/// Use instead:
///
/// ```pyi
/// if sys.version_info >= (3, 10):
/// def read_data(x): ...
///
/// else:
/// def read_data(x, *, preserve_order=True): ...
/// ```
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.8.0")]
pub(crate) struct BadVersionInfoOrder;
impl Violation for BadVersionInfoOrder {
#[derive_message_formats]
fn message(&self) -> String {
"Put branches for newer Python versions first when branching on `sys.version_info` comparisons".to_string()
}
}
/// PYI006, PYI066
pub(crate) fn bad_version_info_comparison(checker: &Checker, test: &Expr, has_else_clause: bool) {
let Expr::Compare(ast::ExprCompare {
left,
ops,
comparators,
..
}) = test
else {
return;
};
let ([op], [_right]) = (&**ops, &**comparators) else {
return;
};
if !checker
.semantic()
.resolve_qualified_name(left)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["sys", "version_info"]))
{
return;
}
if matches!(op, CmpOp::GtE) {
// No issue to be raised, early exit.
return;
}
if matches!(op, CmpOp::Lt) {
if checker.is_rule_enabled(Rule::BadVersionInfoOrder)
// See https://github.com/astral-sh/ruff/issues/15347
&& (checker.source_type.is_stub() || is_bad_version_info_in_non_stub_enabled(checker.settings()))
{
if has_else_clause {
checker.report_diagnostic(BadVersionInfoOrder, test.range());
}
}
} else {
checker.report_diagnostic_if_enabled(BadVersionInfoComparison, test.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_pyi/rules/custom_type_var_for_self.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/custom_type_var_for_self.rs | use anyhow::{Context, bail};
use itertools::Itertools;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::PythonVersion;
use ruff_python_semantic::analyze::class::is_metaclass;
use ruff_python_semantic::analyze::function_type::{self, FunctionType};
use ruff_python_semantic::analyze::visibility::{is_abstract, is_overload};
use ruff_python_semantic::{Binding, ResolvedReference, ScopeId, SemanticModel};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::{Checker, TypingImporter};
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for methods that use custom [`TypeVar`s][typing_TypeVar] in their
/// annotations when they could use [`Self`][Self] instead.
///
/// ## Why is this bad?
/// While the semantics are often identical, using `Self` is more intuitive
/// and succinct (per [PEP 673]) than a custom `TypeVar`. For example, the
/// use of `Self` will typically allow for the omission of type parameters
/// on the `self` and `cls` arguments.
///
/// This check currently applies to instance methods that return `self`,
/// class methods that return an instance of `cls`, class methods that return
/// `cls`, and `__new__` methods.
///
/// ## Example
///
/// ```pyi
/// from typing import TypeVar
///
/// _S = TypeVar("_S", bound="Foo")
///
/// class Foo:
/// def __new__(cls: type[_S], *args: str, **kwargs: int) -> _S: ...
/// def foo(self: _S, arg: bytes) -> _S: ...
/// @classmethod
/// def bar(cls: type[_S], arg: int) -> _S: ...
/// ```
///
/// Use instead:
///
/// ```pyi
/// from typing import Self
///
/// class Foo:
/// def __new__(cls, *args: str, **kwargs: int) -> Self: ...
/// def foo(self, arg: bytes) -> Self: ...
/// @classmethod
/// def bar(cls, arg: int) -> Self: ...
/// ```
///
/// ## Fix behaviour
/// The fix replaces all references to the custom type variable in the method's header and body
/// with references to `Self`. The fix also adds an import of `Self` if neither `Self` nor `typing`
/// is already imported in the module. If your [`target-version`] setting is set to Python 3.11 or
/// newer, the fix imports `Self` from the standard-library `typing` module; otherwise, the fix
/// imports `Self` from the third-party [`typing_extensions`][typing_extensions] backport package.
///
/// If the custom type variable is a [PEP-695]-style `TypeVar`, the fix also removes the `TypeVar`
/// declaration from the method's [type parameter list]. However, if the type variable is an
/// old-style `TypeVar`, the declaration of the type variable will not be removed by this rule's
/// fix, as the type variable could still be used by other functions, methods or classes. See
/// [`unused-private-type-var`][PYI018] for a rule that will clean up unused private type
/// variables.
///
/// ## Fix safety
/// The fix is only marked as unsafe if there is the possibility that it might delete a comment
/// from your code.
///
/// ## Availability
///
/// Because this rule relies on the third-party `typing_extensions` module for Python versions
/// before 3.11, its diagnostic will not be emitted, and no fix will be offered, if
/// `typing_extensions` imports have been disabled by the [`lint.typing-extensions`] linter option.
///
/// ## Options
///
/// - `lint.typing-extensions`
///
/// [PEP 673]: https://peps.python.org/pep-0673/#motivation
/// [PEP-695]: https://peps.python.org/pep-0695/
/// [PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var/
/// [type parameter list]: https://docs.python.org/3/reference/compound_stmts.html#type-params
/// [Self]: https://docs.python.org/3/library/typing.html#typing.Self
/// [typing_TypeVar]: https://docs.python.org/3/library/typing.html#typing.TypeVar
/// [typing_extensions]: https://typing-extensions.readthedocs.io/en/latest/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.283")]
pub(crate) struct CustomTypeVarForSelf {
typevar_name: String,
}
impl Violation for CustomTypeVarForSelf {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Use `Self` instead of custom TypeVar `{}`",
&self.typevar_name
)
}
fn fix_title(&self) -> Option<String> {
Some(format!(
"Replace TypeVar `{}` with `Self`",
&self.typevar_name
))
}
}
/// PYI019
pub(crate) fn custom_type_var_instead_of_self(checker: &Checker, binding: &Binding) {
let semantic = checker.semantic();
let current_scope = &semantic.scopes[binding.scope];
let Some(function_def) = binding
.statement(semantic)
.and_then(|stmt| stmt.as_function_def_stmt())
else {
return;
};
let Some(importer) = checker.typing_importer("Self", PythonVersion::PY311) else {
return;
};
let ast::StmtFunctionDef {
name: function_name,
parameters,
returns,
decorator_list,
type_params,
..
} = function_def;
let type_params = type_params.as_deref();
// Given, e.g., `def foo(self: _S, arg: bytes)`, extract `_S`.
let Some(self_or_cls_parameter) = parameters.posonlyargs.iter().chain(¶meters.args).next()
else {
return;
};
let Some(self_or_cls_annotation_unchecked) = self_or_cls_parameter.annotation() else {
return;
};
let self_or_cls_annotation = match self_or_cls_annotation_unchecked {
ast::Expr::StringLiteral(literal_expr) => {
let Ok(parsed_expr) = checker.parse_type_annotation(literal_expr) else {
return;
};
parsed_expr.expression()
}
_ => self_or_cls_annotation_unchecked,
};
let Some(parent_class) = current_scope.kind.as_class() else {
return;
};
// Skip any abstract/static/overloaded methods,
// and any methods in metaclasses
if is_abstract(decorator_list, semantic)
|| is_overload(decorator_list, semantic)
|| is_metaclass(parent_class, semantic).is_yes()
{
return;
}
let function_kind = function_type::classify(
function_name,
decorator_list,
current_scope,
semantic,
&checker.settings().pep8_naming.classmethod_decorators,
&checker.settings().pep8_naming.staticmethod_decorators,
);
let method = match function_kind {
FunctionType::ClassMethod | FunctionType::NewMethod => Method::Class(ClassMethod {
cls_annotation: self_or_cls_annotation,
type_params,
}),
FunctionType::Method => Method::Instance(InstanceMethod {
self_annotation: self_or_cls_annotation,
type_params,
}),
FunctionType::Function | FunctionType::StaticMethod => return,
};
let Some(custom_typevar) = method.custom_typevar(semantic, binding.scope) else {
return;
};
let function_header_end = returns
.as_deref()
.map(Ranged::end)
.unwrap_or_else(|| parameters.end());
let mut diagnostic = checker.report_diagnostic(
CustomTypeVarForSelf {
typevar_name: custom_typevar.name(checker.source()).to_string(),
},
TextRange::new(function_name.end(), function_header_end),
);
diagnostic.try_set_fix(|| {
replace_custom_typevar_with_self(
checker,
&importer,
function_def,
custom_typevar,
self_or_cls_parameter,
self_or_cls_annotation_unchecked,
)
});
}
#[derive(Debug)]
enum Method<'a> {
Class(ClassMethod<'a>),
Instance(InstanceMethod<'a>),
}
impl Method<'_> {
fn custom_typevar<'a>(
&'a self,
semantic: &'a SemanticModel<'a>,
scope: ScopeId,
) -> Option<TypeVar<'a>> {
match self {
Self::Class(class_method) => class_method.custom_typevar(semantic, scope),
Self::Instance(instance_method) => instance_method.custom_typevar(semantic),
}
}
}
#[derive(Debug)]
struct ClassMethod<'a> {
cls_annotation: &'a ast::Expr,
type_params: Option<&'a ast::TypeParams>,
}
impl ClassMethod<'_> {
/// Returns `Some(typevar)` if the class method is annotated with
/// a custom `TypeVar` for the `cls` parameter
fn custom_typevar<'a>(
&'a self,
semantic: &'a SemanticModel<'a>,
scope: ScopeId,
) -> Option<TypeVar<'a>> {
let ast::ExprSubscript {
value: cls_annotation_value,
slice: cls_annotation_typevar,
..
} = self.cls_annotation.as_subscript_expr()?;
let cls_annotation_typevar = cls_annotation_typevar.as_name_expr()?;
let ast::ExprName { id, .. } = cls_annotation_value.as_name_expr()?;
if id != "type" {
return None;
}
if !semantic.has_builtin_binding_in_scope("type", scope) {
return None;
}
custom_typevar(cls_annotation_typevar, self.type_params, semantic)
}
}
#[derive(Debug)]
struct InstanceMethod<'a> {
self_annotation: &'a ast::Expr,
type_params: Option<&'a ast::TypeParams>,
}
impl InstanceMethod<'_> {
/// Returns `Some(typevar)` if the instance method is annotated with
/// a custom `TypeVar` for the `self` parameter
fn custom_typevar<'a>(&'a self, semantic: &'a SemanticModel<'a>) -> Option<TypeVar<'a>> {
custom_typevar(
self.self_annotation.as_name_expr()?,
self.type_params,
semantic,
)
}
}
/// Returns `Some(TypeVar)` if `typevar_expr` refers to a `TypeVar` binding
fn custom_typevar<'a>(
typevar_expr: &'a ast::ExprName,
type_params: Option<&ast::TypeParams>,
semantic: &'a SemanticModel<'a>,
) -> Option<TypeVar<'a>> {
let binding = semantic
.resolve_name(typevar_expr)
.map(|binding_id| semantic.binding(binding_id))?;
// Example:
// ```py
// class Foo:
// def m[S](self: S) -> S: ...
// ```
if binding.kind.is_type_param() {
return type_params?
.iter()
.filter_map(ast::TypeParam::as_type_var)
.any(|ast::TypeParamTypeVar { name, .. }| name.id == typevar_expr.id)
.then_some(TypeVar(binding));
}
// Example:
// ```py
// from typing import TypeVar
//
// S = TypeVar("S", bound="Foo")
//
// class Foo:
// def m(self: S) -> S: ...
// ```
if !semantic.seen_typing() {
return None;
}
let statement = binding.source.map(|node_id| semantic.statement(node_id))?;
let rhs_function = statement.as_assign_stmt()?.value.as_call_expr()?;
semantic
.match_typing_expr(&rhs_function.func, "TypeVar")
.then_some(TypeVar(binding))
}
/// Add a "Replace with `Self`" fix that does the following:
///
/// * Import `Self` if necessary
/// * Remove the first parameter's annotation
/// * Replace other uses of the original type variable elsewhere in the function with `Self`
/// * If it was a PEP-695 type variable, removes that `TypeVar` from the PEP-695 type-parameter list
fn replace_custom_typevar_with_self(
checker: &Checker,
importer: &TypingImporter,
function_def: &ast::StmtFunctionDef,
custom_typevar: TypeVar,
self_or_cls_parameter: &ast::ParameterWithDefault,
self_or_cls_annotation: &ast::Expr,
) -> anyhow::Result<Fix> {
// (1) Import `Self` (if necessary)
let (import_edit, self_symbol_binding) = importer.import(function_def.start())?;
// (2) Remove the first parameter's annotation
let mut other_edits = vec![Edit::deletion(
self_or_cls_parameter.name().end(),
self_or_cls_annotation.end(),
)];
// (3) If it was a PEP-695 type variable, remove that `TypeVar` from the PEP-695 type-parameter list
if custom_typevar.is_pep695_typevar() {
let type_params = function_def.type_params.as_deref().context(
"Should not be possible to have a type parameter without a type parameter list",
)?;
let deletion_edit = remove_pep695_typevar_declaration(type_params, custom_typevar)
.context("Failed to find a `TypeVar` in the type params that matches the binding")?;
other_edits.push(deletion_edit);
}
// (4) Replace all other references to the original type variable elsewhere in the function with `Self`
let replace_references_range = TextRange::new(self_or_cls_annotation.end(), function_def.end());
replace_typevar_usages_with_self(
custom_typevar,
checker.source(),
self_or_cls_annotation.range(),
&self_symbol_binding,
replace_references_range,
checker.semantic(),
&mut other_edits,
)?;
// (5) Determine the safety of the fixes as a whole
let comment_ranges = checker.comment_ranges();
let applicability = if other_edits
.iter()
.any(|edit| comment_ranges.intersects(edit.range()))
{
Applicability::Unsafe
} else {
Applicability::Safe
};
Ok(Fix::applicable_edits(
import_edit,
other_edits,
applicability,
))
}
/// Returns a series of [`Edit`]s that modify all references to the given `typevar`.
///
/// Only references within `editable_range` will be modified.
/// This ensures that no edit in this series will overlap with other edits.
fn replace_typevar_usages_with_self<'a>(
typevar: TypeVar<'a>,
source: &'a str,
self_or_cls_annotation_range: TextRange,
self_symbol_binding: &'a str,
editable_range: TextRange,
semantic: &'a SemanticModel<'a>,
edits: &mut Vec<Edit>,
) -> anyhow::Result<()> {
let tvar_name = typevar.name(source);
for reference in typevar.references(semantic) {
let reference_range = reference.range();
if &source[reference_range] != tvar_name {
bail!(
"Cannot autofix: reference in the source code (`{}`) is not equal to the typevar name (`{}`)",
&source[reference_range],
tvar_name
);
}
if !editable_range.contains_range(reference_range) {
continue;
}
if self_or_cls_annotation_range.contains_range(reference_range) {
continue;
}
edits.push(Edit::range_replacement(
self_symbol_binding.to_string(),
reference_range,
));
}
Ok(())
}
/// Create an [`Edit`] removing the `TypeVar` binding from the PEP 695 type parameter list.
///
/// Return `None` if we fail to find a `TypeVar` that matches the range of `typevar_binding`.
fn remove_pep695_typevar_declaration(
type_params: &ast::TypeParams,
custom_typevar: TypeVar,
) -> Option<Edit> {
if let [sole_typevar] = &**type_params {
return (sole_typevar.name().range() == custom_typevar.range())
.then(|| Edit::range_deletion(type_params.range));
}
// `custom_typevar.range()` will return the range of the name of the typevar binding.
// We need the full range of the `TypeVar` declaration (including any constraints or bounds)
// to determine the correct deletion range.
let (tvar_index, tvar_declaration) = type_params
.iter()
.find_position(|param| param.name().range() == custom_typevar.range())?;
let last_index = type_params.len() - 1;
let deletion_range = if tvar_index < last_index {
// def f[A, B, C](): ...
// ^^^ Remove this
TextRange::new(
tvar_declaration.start(),
type_params[tvar_index + 1].start(),
)
} else {
// def f[A, B, C](): ...
// ^^^ Remove this
TextRange::new(type_params[tvar_index - 1].end(), tvar_declaration.end())
};
Some(Edit::range_deletion(deletion_range))
}
#[derive(Debug, Copy, Clone)]
struct TypeVar<'a>(&'a Binding<'a>);
impl<'a> TypeVar<'a> {
const fn is_pep695_typevar(self) -> bool {
self.0.kind.is_type_param()
}
fn name(self, source: &'a str) -> &'a str {
self.0.name(source)
}
fn references(
self,
semantic: &'a SemanticModel<'a>,
) -> impl Iterator<Item = &'a ResolvedReference> + 'a {
self.0
.references()
.map(|reference_id| semantic.reference(reference_id))
}
}
impl Ranged for TypeVar<'_> {
fn range(&self) -> TextRange {
self.0.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_pyi/rules/unused_private_type_definition.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/unused_private_type_definition.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::map_subscript;
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_semantic::{Scope, SemanticModel};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix;
use crate::{Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for the presence of unused private `TypeVar`, `ParamSpec` or
/// `TypeVarTuple` declarations.
///
/// ## Why is this bad?
/// A private `TypeVar` that is defined but not used is likely a mistake. It
/// should either be used, made public, or removed to avoid confusion. A type
/// variable is considered "private" if its name starts with an underscore.
///
/// ## Example
/// ```pyi
/// import typing
/// import typing_extensions
///
/// _T = typing.TypeVar("_T")
/// _Ts = typing_extensions.TypeVarTuple("_Ts")
/// ```
///
/// ## Fix safety
/// The fix is always marked as unsafe, as it would break your code if the type
/// variable is imported by another module.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.281")]
pub(crate) struct UnusedPrivateTypeVar {
type_var_like_name: String,
type_var_like_kind: String,
}
impl Violation for UnusedPrivateTypeVar {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let UnusedPrivateTypeVar {
type_var_like_name,
type_var_like_kind,
} = self;
format!("Private {type_var_like_kind} `{type_var_like_name}` is never used")
}
fn fix_title(&self) -> Option<String> {
let UnusedPrivateTypeVar {
type_var_like_name,
type_var_like_kind,
} = self;
Some(format!(
"Remove unused private {type_var_like_kind} `{type_var_like_name}`"
))
}
}
/// ## What it does
/// Checks for the presence of unused private `typing.Protocol` definitions.
///
/// ## Why is this bad?
/// A private `typing.Protocol` that is defined but not used is likely a
/// mistake. It should either be used, made public, or removed to avoid
/// confusion.
///
/// ## Example
///
/// ```pyi
/// import typing
///
/// class _PrivateProtocol(typing.Protocol):
/// foo: int
/// ```
///
/// Use instead:
///
/// ```pyi
/// import typing
///
/// class _PrivateProtocol(typing.Protocol):
/// foo: int
///
/// def func(arg: _PrivateProtocol) -> None: ...
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.281")]
pub(crate) struct UnusedPrivateProtocol {
name: String,
}
impl Violation for UnusedPrivateProtocol {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedPrivateProtocol { name } = self;
format!("Private protocol `{name}` is never used")
}
}
/// ## What it does
/// Checks for the presence of unused private type aliases.
///
/// ## Why is this bad?
/// A private type alias that is defined but not used is likely a
/// mistake. It should either be used, made public, or removed to avoid
/// confusion.
///
/// ## Example
///
/// ```pyi
/// import typing
///
/// _UnusedTypeAlias: typing.TypeAlias = int
/// ```
///
/// Use instead:
///
/// ```pyi
/// import typing
///
/// _UsedTypeAlias: typing.TypeAlias = int
///
/// def func(arg: _UsedTypeAlias) -> _UsedTypeAlias: ...
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.281")]
pub(crate) struct UnusedPrivateTypeAlias {
name: String,
}
impl Violation for UnusedPrivateTypeAlias {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedPrivateTypeAlias { name } = self;
format!("Private TypeAlias `{name}` is never used")
}
}
/// ## What it does
/// Checks for the presence of unused private `typing.TypedDict` definitions.
///
/// ## Why is this bad?
/// A private `typing.TypedDict` that is defined but not used is likely a
/// mistake. It should either be used, made public, or removed to avoid
/// confusion.
///
/// ## Example
///
/// ```pyi
/// import typing
///
/// class _UnusedPrivateTypedDict(typing.TypedDict):
/// foo: list[int]
/// ```
///
/// Use instead:
///
/// ```pyi
/// import typing
///
/// class _UsedPrivateTypedDict(typing.TypedDict):
/// foo: set[str]
///
/// def func(arg: _UsedPrivateTypedDict) -> _UsedPrivateTypedDict: ...
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.281")]
pub(crate) struct UnusedPrivateTypedDict {
name: String,
}
impl Violation for UnusedPrivateTypedDict {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedPrivateTypedDict { name } = self;
format!("Private TypedDict `{name}` is never used")
}
}
/// PYI018
pub(crate) fn unused_private_type_var(checker: &Checker, scope: &Scope) {
for binding in scope
.binding_ids()
.map(|binding_id| checker.semantic().binding(binding_id))
{
if !(binding.kind.is_assignment() && binding.is_private_declaration()) {
continue;
}
if binding.is_used() {
continue;
}
let Some(source) = binding.source else {
continue;
};
let stmt @ Stmt::Assign(ast::StmtAssign { targets, value, .. }) =
checker.semantic().statement(source)
else {
continue;
};
let [Expr::Name(ast::ExprName { id, .. })] = &targets[..] else {
continue;
};
let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() else {
continue;
};
let semantic = checker.semantic();
let Some(type_var_like_kind) =
semantic
.resolve_qualified_name(func)
.and_then(|qualified_name| {
if semantic.match_typing_qualified_name(&qualified_name, "TypeVar") {
Some("TypeVar")
} else if semantic.match_typing_qualified_name(&qualified_name, "ParamSpec") {
Some("ParamSpec")
} else if semantic.match_typing_qualified_name(&qualified_name, "TypeVarTuple")
{
Some("TypeVarTuple")
} else {
None
}
})
else {
continue;
};
checker
.report_diagnostic(
UnusedPrivateTypeVar {
type_var_like_name: id.to_string(),
type_var_like_kind: type_var_like_kind.to_string(),
},
binding.range(),
)
.set_fix(Fix::unsafe_edit(fix::edits::delete_stmt(
stmt,
None,
checker.locator(),
checker.indexer(),
)));
}
}
/// PYI046
pub(crate) fn unused_private_protocol(checker: &Checker, scope: &Scope) {
for binding in scope
.binding_ids()
.map(|binding_id| checker.semantic().binding(binding_id))
{
if !(binding.kind.is_class_definition() && binding.is_private_declaration()) {
continue;
}
if binding.is_used() {
continue;
}
let Some(source) = binding.source else {
continue;
};
let Stmt::ClassDef(class_def) = checker.semantic().statement(source) else {
continue;
};
if !class_def.bases().iter().any(|base| {
checker
.semantic()
.match_typing_expr(map_subscript(base), "Protocol")
}) {
continue;
}
checker.report_diagnostic(
UnusedPrivateProtocol {
name: class_def.name.to_string(),
},
binding.range(),
);
}
}
/// PYI047
pub(crate) fn unused_private_type_alias(checker: &Checker, scope: &Scope) {
let semantic = checker.semantic();
for binding in scope
.binding_ids()
.map(|binding_id| semantic.binding(binding_id))
{
if !(binding.kind.is_assignment() && binding.is_private_declaration()) {
continue;
}
if binding.is_used() {
continue;
}
let Some(source) = binding.source else {
continue;
};
let Some(alias_name) = extract_type_alias_name(semantic.statement(source), semantic) else {
continue;
};
checker.report_diagnostic(
UnusedPrivateTypeAlias {
name: alias_name.to_string(),
},
binding.range(),
);
}
}
fn extract_type_alias_name<'a>(stmt: &'a ast::Stmt, semantic: &SemanticModel) -> Option<&'a str> {
match stmt {
ast::Stmt::AnnAssign(ast::StmtAnnAssign {
target, annotation, ..
}) => {
let ast::ExprName { id, .. } = target.as_name_expr()?;
if semantic.match_typing_expr(annotation, "TypeAlias") {
Some(id)
} else {
None
}
}
ast::Stmt::TypeAlias(ast::StmtTypeAlias { name, .. }) => {
let ast::ExprName { id, .. } = name.as_name_expr()?;
Some(id)
}
_ => None,
}
}
/// PYI049
pub(crate) fn unused_private_typed_dict(checker: &Checker, scope: &Scope) {
let semantic = checker.semantic();
for binding in scope
.binding_ids()
.map(|binding_id| semantic.binding(binding_id))
{
if !binding.is_private_declaration() {
continue;
}
if !(binding.kind.is_class_definition() || binding.kind.is_assignment()) {
continue;
}
if binding.is_used() {
continue;
}
let Some(source) = binding.source else {
continue;
};
let Some(class_name) = extract_typeddict_name(semantic.statement(source), semantic) else {
continue;
};
checker.report_diagnostic(
UnusedPrivateTypedDict {
name: class_name.to_string(),
},
binding.range(),
);
}
}
fn extract_typeddict_name<'a>(stmt: &'a Stmt, semantic: &SemanticModel) -> Option<&'a str> {
let is_typeddict = |expr: &ast::Expr| semantic.match_typing_expr(expr, "TypedDict");
match stmt {
// E.g. return `Some("Foo")` for the first one of these classes,
// and `Some("Bar")` for the second:
//
// ```python
// import typing
// from typing import TypedDict
//
// class Foo(TypedDict):
// x: int
//
// T = typing.TypeVar("T")
//
// class Bar(typing.TypedDict, typing.Generic[T]):
// y: T
// ```
Stmt::ClassDef(class_def @ ast::StmtClassDef { name, .. }) => {
if class_def.bases().iter().any(is_typeddict) {
Some(name)
} else {
None
}
}
// E.g. return `Some("Baz")` for this assignment,
// which is an accepted alternative way of creating a TypedDict type:
//
// ```python
// import typing
// Baz = typing.TypedDict("Baz", {"z": bytes})
// ```
Stmt::Assign(ast::StmtAssign { targets, value, .. }) => {
let [target] = targets.as_slice() else {
return None;
};
let ast::ExprName { id, .. } = target.as_name_expr()?;
let ast::ExprCall { func, .. } = value.as_call_expr()?;
if is_typeddict(func) { Some(id) } else { None }
}
_ => 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_pyi/rules/any_eq_ne_annotation.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/any_eq_ne_annotation.rs | use ruff_python_ast::Parameters;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for `__eq__` and `__ne__` implementations that use `typing.Any` as
/// the type annotation for their second parameter.
///
/// ## Why is this bad?
/// The Python documentation recommends the use of `object` to "indicate that a
/// value could be any type in a typesafe manner". `Any`, on the other hand,
/// should be seen as an "escape hatch when you need to mix dynamically and
/// statically typed code". Since using `Any` allows you to write highly unsafe
/// code, you should generally only use `Any` when the semantics of your code
/// would otherwise be inexpressible to the type checker.
///
/// The expectation in Python is that a comparison of two arbitrary objects
/// using `==` or `!=` should never raise an exception. This contract can be
/// fully expressed in the type system and does not involve requesting unsound
/// behaviour from a type checker. As such, `object` is a more appropriate
/// annotation than `Any` for the second parameter of the methods implementing
/// these comparison operators -- `__eq__` and `__ne__`.
///
/// ## Example
///
/// ```pyi
/// from typing import Any
///
/// class Foo:
/// def __eq__(self, obj: Any) -> bool: ...
/// ```
///
/// Use instead:
///
/// ```pyi
/// class Foo:
/// def __eq__(self, obj: object) -> bool: ...
/// ```
/// ## References
/// - [Python documentation: The `Any` type](https://docs.python.org/3/library/typing.html#the-any-type)
/// - [Mypy documentation: Any vs. object](https://mypy.readthedocs.io/en/latest/dynamic_typing.html#any-vs-object)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.271")]
pub(crate) struct AnyEqNeAnnotation {
method_name: String,
}
impl AlwaysFixableViolation for AnyEqNeAnnotation {
#[derive_message_formats]
fn message(&self) -> String {
let AnyEqNeAnnotation { method_name } = self;
format!("Prefer `object` to `Any` for the second parameter to `{method_name}`")
}
fn fix_title(&self) -> String {
"Replace with `object`".to_string()
}
}
/// PYI032
pub(crate) fn any_eq_ne_annotation(checker: &Checker, name: &str, parameters: &Parameters) {
if !matches!(name, "__eq__" | "__ne__") {
return;
}
if parameters.args.len() != 2 {
return;
}
let Some(annotation) = ¶meters.args[1].annotation() else {
return;
};
let semantic = checker.semantic();
if !semantic.current_scope().kind.is_class() {
return;
}
if !checker.match_maybe_stringized_annotation(annotation, |expr| {
semantic.match_typing_expr(expr, "Any")
}) {
return;
}
let mut diagnostic = checker.report_diagnostic(
AnyEqNeAnnotation {
method_name: name.to_string(),
},
annotation.range(),
);
// Ex) `def __eq__(self, obj: Any): ...`
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol(
"object",
annotation.start(),
semantic,
)?;
let binding_edit = Edit::range_replacement(binding, annotation.range());
Ok(Fix::safe_edits(binding_edit, import_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_pyi/rules/prefix_type_params.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/prefix_type_params.rs | use std::fmt;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub(crate) enum VarKind {
TypeVar,
ParamSpec,
TypeVarTuple,
}
impl fmt::Display for VarKind {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
VarKind::TypeVar => fmt.write_str("TypeVar"),
VarKind::ParamSpec => fmt.write_str("ParamSpec"),
VarKind::TypeVarTuple => fmt.write_str("TypeVarTuple"),
}
}
}
/// ## What it does
/// Checks that type `TypeVar`s, `ParamSpec`s, and `TypeVarTuple`s in stubs
/// have names prefixed with `_`.
///
/// ## Why is this bad?
/// Prefixing type parameters with `_` avoids accidentally exposing names
/// internal to the stub.
///
/// ## Example
/// ```pyi
/// from typing import TypeVar
///
/// T = TypeVar("T")
/// ```
///
/// Use instead:
/// ```pyi
/// from typing import TypeVar
///
/// _T = TypeVar("_T")
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.245")]
pub(crate) struct UnprefixedTypeParam {
kind: VarKind,
}
impl Violation for UnprefixedTypeParam {
#[derive_message_formats]
fn message(&self) -> String {
let UnprefixedTypeParam { kind } = self;
format!("Name of private `{kind}` must start with `_`")
}
}
/// PYI001
pub(crate) fn prefix_type_params(checker: &Checker, value: &Expr, targets: &[Expr]) {
// If the typing modules were never imported, we'll never match below.
if !checker.semantic().seen_typing() {
return;
}
let [target] = targets else {
return;
};
if let Expr::Name(ast::ExprName { id, .. }) = target {
if id.starts_with('_') {
return;
}
}
let Expr::Call(ast::ExprCall { func, .. }) = value else {
return;
};
let Some(kind) = checker
.semantic()
.resolve_qualified_name(func)
.and_then(|qualified_name| {
if checker
.semantic()
.match_typing_qualified_name(&qualified_name, "ParamSpec")
{
Some(VarKind::ParamSpec)
} else if checker
.semantic()
.match_typing_qualified_name(&qualified_name, "TypeVar")
{
Some(VarKind::TypeVar)
} else if checker
.semantic()
.match_typing_qualified_name(&qualified_name, "TypeVarTuple")
{
Some(VarKind::TypeVarTuple)
} else {
None
}
})
else {
return;
};
checker.report_diagnostic(UnprefixedTypeParam { kind }, value.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_pyi/rules/docstring_in_stubs.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/docstring_in_stubs.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{ExprStringLiteral, Stmt};
use ruff_text_size::Ranged;
use crate::checkers::ast::{Checker, DocstringState, ExpectedDocstringKind};
use crate::docstrings::extraction::docstring_from;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for the presence of docstrings in stub files.
///
/// ## Why is this bad?
/// Stub files should omit docstrings, as they're intended to provide type
/// hints, rather than documentation.
///
/// ## Example
///
/// ```pyi
/// def func(param: int) -> str:
/// """This is a docstring."""
/// ...
/// ```
///
/// Use instead:
///
/// ```pyi
/// def func(param: int) -> str: ...
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.253")]
pub(crate) struct DocstringInStub;
impl AlwaysFixableViolation for DocstringInStub {
#[derive_message_formats]
fn message(&self) -> String {
"Docstrings should not be included in stubs".to_string()
}
fn fix_title(&self) -> String {
"Remove docstring".to_string()
}
}
/// PYI021
pub(crate) fn docstring_in_stubs(checker: &Checker, body: &[Stmt]) {
if !matches!(
checker.docstring_state(),
DocstringState::Expected(
ExpectedDocstringKind::Module
| ExpectedDocstringKind::Class
| ExpectedDocstringKind::Function
)
) {
return;
}
let docstring = docstring_from(body);
let Some(docstring_range) = docstring.map(ExprStringLiteral::range) else {
return;
};
let edit = if body.len() == 1 {
Edit::range_replacement("...".to_string(), docstring_range)
} else {
Edit::range_deletion(docstring_range)
};
let isolation_level = Checker::isolation(checker.semantic().current_statement_id());
let fix = Fix::unsafe_edit(edit).isolate(isolation_level);
checker
.report_diagnostic(DocstringInStub, docstring_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_pyi/rules/simple_defaults.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/simple_defaults.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::PythonVersion;
use ruff_python_ast::name::QualifiedName;
use ruff_python_ast::{self as ast, Expr, Operator, Parameters, Stmt, UnaryOp};
use ruff_python_semantic::{ScopeKind, SemanticModel, analyze::class::is_enumeration};
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::rules::flake8_pyi::rules::TypingModule;
use crate::{AlwaysFixableViolation, Edit, Fix, Violation};
/// ## What it does
/// Checks for typed function arguments in stubs with complex default values.
///
/// ## Why is this bad?
/// Stub (`.pyi`) files exist as "data files" for static analysis tools, and
/// are not evaluated at runtime. While simple default values may be useful for
/// some tools that consume stubs, such as IDEs, they are ignored by type
/// checkers.
///
/// Instead of including and reproducing a complex value, use `...` to indicate
/// that the assignment has a default value, but that the value is "complex" or
/// varies according to the current platform or Python version. For the
/// purposes of this rule, any default value counts as "complex" unless it is
/// a literal `int`, `float`, `complex`, `bytes`, `str`, `bool`, `None`, `...`,
/// or a simple container literal.
///
/// ## Example
///
/// ```pyi
/// def foo(arg: list[int] = list(range(10_000))) -> None: ...
/// ```
///
/// Use instead:
///
/// ```pyi
/// def foo(arg: list[int] = ...) -> None: ...
/// ```
///
/// ## References
/// - [`flake8-pyi`](https://github.com/PyCQA/flake8-pyi/blob/main/ERRORCODES.md)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.253")]
pub(crate) struct TypedArgumentDefaultInStub;
impl AlwaysFixableViolation for TypedArgumentDefaultInStub {
#[derive_message_formats]
fn message(&self) -> String {
"Only simple default values allowed for typed arguments".to_string()
}
fn fix_title(&self) -> String {
"Replace default value with `...`".to_string()
}
}
/// ## What it does
/// Checks for untyped function arguments in stubs with default values that
/// are not "simple" /// (i.e., `int`, `float`, `complex`, `bytes`, `str`,
/// `bool`, `None`, `...`, or simple container literals).
///
/// ## Why is this bad?
/// Stub (`.pyi`) files exist to define type hints, and are not evaluated at
/// runtime. As such, function arguments in stub files should not have default
/// values, as they are ignored by type checkers.
///
/// However, the use of default values may be useful for IDEs and other
/// consumers of stub files, and so "simple" values may be worth including and
/// are permitted by this rule.
///
/// Instead of including and reproducing a complex value, use `...` to indicate
/// that the assignment has a default value, but that the value is non-simple
/// or varies according to the current platform or Python version.
///
/// ## Example
///
/// ```pyi
/// def foo(arg=bar()) -> None: ...
/// ```
///
/// Use instead:
///
/// ```pyi
/// def foo(arg=...) -> None: ...
/// ```
///
/// ## References
/// - [`flake8-pyi`](https://github.com/PyCQA/flake8-pyi/blob/main/ERRORCODES.md)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.253")]
pub(crate) struct ArgumentDefaultInStub;
impl AlwaysFixableViolation for ArgumentDefaultInStub {
#[derive_message_formats]
fn message(&self) -> String {
"Only simple default values allowed for arguments".to_string()
}
fn fix_title(&self) -> String {
"Replace default value with `...`".to_string()
}
}
/// ## What it does
/// Checks for assignments in stubs with default values that are not "simple"
/// (i.e., `int`, `float`, `complex`, `bytes`, `str`, `bool`, `None`, `...`, or
/// simple container literals).
///
/// ## Why is this bad?
/// Stub (`.pyi`) files exist to define type hints, and are not evaluated at
/// runtime. As such, assignments in stub files should not include values,
/// as they are ignored by type checkers.
///
/// However, the use of such values may be useful for IDEs and other consumers
/// of stub files, and so "simple" values may be worth including and are
/// permitted by this rule.
///
/// Instead of including and reproducing a complex value, use `...` to indicate
/// that the assignment has a default value, but that the value is non-simple
/// or varies according to the current platform or Python version.
///
/// ## Example
/// ```pyi
/// foo: str = bar()
/// ```
///
/// Use instead:
/// ```pyi
/// foo: str = ...
/// ```
///
/// ## References
/// - [`flake8-pyi`](https://github.com/PyCQA/flake8-pyi/blob/main/ERRORCODES.md)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.260")]
pub(crate) struct AssignmentDefaultInStub;
impl AlwaysFixableViolation for AssignmentDefaultInStub {
#[derive_message_formats]
fn message(&self) -> String {
"Only simple default values allowed for assignments".to_string()
}
fn fix_title(&self) -> String {
"Replace default value with `...`".to_string()
}
}
/// ## What it does
/// Checks for unannotated assignments in stub (`.pyi`) files.
///
/// ## Why is this bad?
/// Stub files exist to provide type hints, and are never executed. As such,
/// all assignments in stub files should be annotated with a type.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.269")]
pub(crate) struct UnannotatedAssignmentInStub {
name: String,
}
impl Violation for UnannotatedAssignmentInStub {
#[derive_message_formats]
fn message(&self) -> String {
let UnannotatedAssignmentInStub { name } = self;
format!("Need type annotation for `{name}`")
}
}
/// ## What it does
/// Checks that `__all__`, `__match_args__`, and `__slots__` variables are
/// assigned to values when defined in stub files.
///
/// ## Why is this bad?
/// Special variables like `__all__` have the same semantics in stub files
/// as they do in Python modules, and so should be consistent with their
/// runtime counterparts.
///
/// ## Example
/// ```pyi
/// __all__: list[str]
/// ```
///
/// Use instead:
/// ```pyi
/// __all__: list[str] = ["foo", "bar"]
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.271")]
pub(crate) struct UnassignedSpecialVariableInStub {
name: String,
}
impl Violation for UnassignedSpecialVariableInStub {
#[derive_message_formats]
fn message(&self) -> String {
let UnassignedSpecialVariableInStub { name } = self;
format!(
"`{name}` in a stub file must have a value, as it has the same semantics as `{name}` at runtime"
)
}
}
/// ## What it does
/// Checks for type alias definitions that are not annotated with
/// `typing.TypeAlias`.
///
/// ## Why is this bad?
/// In Python, a type alias is defined by assigning a type to a variable (e.g.,
/// `Vector = list[float]`).
///
/// It's best to annotate type aliases with the `typing.TypeAlias` type to
/// make it clear that the statement is a type alias declaration, as opposed
/// to a normal variable assignment.
///
/// ## Example
/// ```pyi
/// Vector = list[float]
/// ```
///
/// Use instead:
/// ```pyi
/// from typing import TypeAlias
///
/// Vector: TypeAlias = list[float]
/// ```
///
/// ## Availability
///
/// Because this rule relies on the third-party `typing_extensions` module for Python versions
/// before 3.10, its diagnostic will not be emitted, and no fix will be offered, if
/// `typing_extensions` imports have been disabled by the [`lint.typing-extensions`] linter option.
///
/// ## Options
///
/// - `lint.typing-extensions`
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.279")]
pub(crate) struct TypeAliasWithoutAnnotation {
module: TypingModule,
name: String,
value: String,
}
impl AlwaysFixableViolation for TypeAliasWithoutAnnotation {
#[derive_message_formats]
fn message(&self) -> String {
let TypeAliasWithoutAnnotation {
module,
name,
value,
} = self;
format!("Use `{module}.TypeAlias` for type alias, e.g., `{name}: TypeAlias = {value}`")
}
fn fix_title(&self) -> String {
"Add `TypeAlias` annotation".to_string()
}
}
fn is_allowed_negated_math_attribute(qualified_name: &QualifiedName) -> bool {
matches!(
qualified_name.segments(),
["math", "inf" | "e" | "pi" | "tau"]
)
}
fn is_allowed_math_attribute(qualified_name: &QualifiedName) -> bool {
matches!(
qualified_name.segments(),
["math", "inf" | "nan" | "e" | "pi" | "tau"]
| [
"sys",
"stdin"
| "stdout"
| "stderr"
| "version"
| "version_info"
| "platform"
| "executable"
| "prefix"
| "exec_prefix"
| "base_prefix"
| "byteorder"
| "maxsize"
| "hexversion"
| "winver"
]
)
}
fn is_valid_default_value_with_annotation(
default: &Expr,
allow_container: bool,
locator: &Locator,
semantic: &SemanticModel,
) -> bool {
match default {
Expr::StringLiteral(_)
| Expr::BytesLiteral(_)
| Expr::NumberLiteral(_)
| Expr::BooleanLiteral(_)
| Expr::NoneLiteral(_)
| Expr::EllipsisLiteral(_) => {
return true;
}
Expr::List(ast::ExprList { elts, .. })
| Expr::Tuple(ast::ExprTuple { elts, .. })
| Expr::Set(ast::ExprSet {
elts,
range: _,
node_index: _,
}) => {
return allow_container
&& elts.len() <= 10
&& elts
.iter()
.all(|e| is_valid_default_value_with_annotation(e, false, locator, semantic));
}
Expr::Dict(dict) => {
return allow_container
&& dict.len() <= 10
&& dict.iter().all(|ast::DictItem { key, value }| {
key.as_ref().is_some_and(|key| {
is_valid_default_value_with_annotation(key, false, locator, semantic)
}) && is_valid_default_value_with_annotation(value, false, locator, semantic)
});
}
Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::USub,
operand,
range: _,
node_index: _,
}) => {
match operand.as_ref() {
// Ex) `-1`, `-3.14`, `2j`
Expr::NumberLiteral(_) => return true,
// Ex) `-math.inf`, `-math.pi`, etc.
Expr::Attribute(_) => {
if semantic
.resolve_qualified_name(operand)
.as_ref()
.is_some_and(is_allowed_negated_math_attribute)
{
return true;
}
}
_ => {}
}
}
Expr::BinOp(ast::ExprBinOp {
left,
op: Operator::Add | Operator::Sub,
right,
range: _,
node_index: _,
}) => {
// Ex) `1 + 2j`, `1 - 2j`, `-1 - 2j`, `-1 + 2j`
if let Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Complex { .. },
..
}) = right.as_ref()
{
// Ex) `1 + 2j`, `1 - 2j`
if let Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(..) | ast::Number::Float(..),
..
}) = left.as_ref()
{
return locator.slice(left.as_ref()).len() <= 10;
} else if let Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::USub,
operand,
range: _,
node_index: _,
}) = left.as_ref()
{
// Ex) `-1 + 2j`, `-1 - 2j`
if let Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(..) | ast::Number::Float(..),
..
}) = operand.as_ref()
{
return locator.slice(operand.as_ref()).len() <= 10;
}
}
}
}
// Ex) `math.inf`, `sys.stdin`, etc.
Expr::Attribute(_) => {
if semantic
.resolve_qualified_name(default)
.as_ref()
.is_some_and(is_allowed_math_attribute)
{
return true;
}
}
_ => {}
}
false
}
/// Returns `true` if an [`Expr`] appears to be a valid PEP 604 union. (e.g. `int | None`)
fn is_valid_pep_604_union(annotation: &Expr) -> bool {
/// Returns `true` if an [`Expr`] appears to be a valid PEP 604 union member.
fn is_valid_pep_604_union_member(value: &Expr) -> bool {
match value {
Expr::BinOp(ast::ExprBinOp {
left,
op: Operator::BitOr,
right,
range: _,
node_index: _,
}) => is_valid_pep_604_union_member(left) && is_valid_pep_604_union_member(right),
Expr::Name(_) | Expr::Subscript(_) | Expr::Attribute(_) | Expr::NoneLiteral(_) => true,
_ => false,
}
}
// The top-level expression must be a bit-or operation.
let Expr::BinOp(ast::ExprBinOp {
left,
op: Operator::BitOr,
right,
range: _,
node_index: _,
}) = annotation
else {
return false;
};
// The left and right operands must be valid union members.
is_valid_pep_604_union_member(left) && is_valid_pep_604_union_member(right)
}
/// Returns `true` if an [`Expr`] appears to be a valid default value without an annotation.
fn is_valid_default_value_without_annotation(default: &Expr) -> bool {
matches!(
default,
Expr::Call(_)
| Expr::Name(_)
| Expr::Attribute(_)
| Expr::Subscript(_)
| Expr::EllipsisLiteral(_)
| Expr::NoneLiteral(_)
) || is_valid_pep_604_union(default)
}
/// Returns `true` if an [`Expr`] appears to be `TypeVar`, `TypeVarTuple`, `NewType`, or `ParamSpec`
/// call.
///
/// See also [`ruff_python_semantic::analyze::typing::TypeVarLikeChecker::is_type_var_like_call`].
fn is_type_var_like_call(expr: &Expr, semantic: &SemanticModel) -> bool {
let Expr::Call(ast::ExprCall { func, .. }) = expr else {
return false;
};
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
[
"typing" | "typing_extensions",
"TypeVar" | "TypeVarTuple" | "NewType" | "ParamSpec"
]
)
})
}
/// Returns `true` if this is a "special" assignment which must have a value (e.g., an assignment to
/// `__all__`).
fn is_special_assignment(target: &Expr, semantic: &SemanticModel) -> bool {
if let Expr::Name(ast::ExprName { id, .. }) = target {
match id.as_str() {
"__all__" => semantic.current_scope().kind.is_module(),
"__match_args__" | "__slots__" => semantic.current_scope().kind.is_class(),
_ => false,
}
} else {
false
}
}
/// Returns `true` if this is an assignment to a simple `Final`-annotated variable.
fn is_final_assignment(annotation: &Expr, value: &Expr, semantic: &SemanticModel) -> bool {
if matches!(value, Expr::Name(_) | Expr::Attribute(_)) {
if semantic.match_typing_expr(annotation, "Final") {
return true;
}
}
false
}
/// Returns `true` if an [`Expr`] is a value that should be annotated with `typing.TypeAlias`.
///
/// This is relatively conservative, as it's hard to reliably detect whether a right-hand side is a
/// valid type alias. In particular, this function checks for uses of `typing.Any`, `None`,
/// parameterized generics, and PEP 604-style unions.
fn is_annotatable_type_alias(value: &Expr, semantic: &SemanticModel) -> bool {
if value.is_none_literal_expr() {
if let ScopeKind::Class(class_def) = semantic.current_scope().kind {
!is_enumeration(class_def, semantic)
} else {
true
}
} else {
value.is_subscript_expr()
|| is_valid_pep_604_union(value)
|| semantic.match_typing_expr(value, "Any")
}
}
/// PYI011
pub(crate) fn typed_argument_simple_defaults(checker: &Checker, parameters: &Parameters) {
for parameter in parameters.iter_non_variadic_params() {
let Some(default) = parameter.default() else {
continue;
};
if parameter.annotation().is_some() {
if !is_valid_default_value_with_annotation(
default,
true,
checker.locator(),
checker.semantic(),
) {
let mut diagnostic =
checker.report_diagnostic(TypedArgumentDefaultInStub, default.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
"...".to_string(),
default.range(),
)));
}
}
}
}
/// PYI014
pub(crate) fn argument_simple_defaults(checker: &Checker, parameters: &Parameters) {
for parameter in parameters.iter_non_variadic_params() {
let Some(default) = parameter.default() else {
continue;
};
if parameter.annotation().is_none() {
if !is_valid_default_value_with_annotation(
default,
true,
checker.locator(),
checker.semantic(),
) {
let mut diagnostic =
checker.report_diagnostic(ArgumentDefaultInStub, default.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
"...".to_string(),
default.range(),
)));
}
}
}
}
/// PYI015
pub(crate) fn assignment_default_in_stub(checker: &Checker, targets: &[Expr], value: &Expr) {
let [target] = targets else {
return;
};
if !target.is_name_expr() {
return;
}
if is_special_assignment(target, checker.semantic()) {
return;
}
if is_type_var_like_call(value, checker.semantic()) {
return;
}
if is_valid_default_value_without_annotation(value) {
return;
}
if is_valid_default_value_with_annotation(value, true, checker.locator(), checker.semantic()) {
return;
}
let mut diagnostic = checker.report_diagnostic(AssignmentDefaultInStub, value.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
"...".to_string(),
value.range(),
)));
}
/// PYI015
pub(crate) fn annotated_assignment_default_in_stub(
checker: &Checker,
target: &Expr,
value: &Expr,
annotation: &Expr,
) {
if checker
.semantic()
.match_typing_expr(annotation, "TypeAlias")
{
return;
}
if is_special_assignment(target, checker.semantic()) {
return;
}
if is_type_var_like_call(value, checker.semantic()) {
return;
}
if is_final_assignment(annotation, value, checker.semantic()) {
return;
}
if is_valid_default_value_with_annotation(value, true, checker.locator(), checker.semantic()) {
return;
}
let mut diagnostic = checker.report_diagnostic(AssignmentDefaultInStub, value.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
"...".to_string(),
value.range(),
)));
}
/// PYI052
pub(crate) fn unannotated_assignment_in_stub(checker: &Checker, targets: &[Expr], value: &Expr) {
let [target] = targets else {
return;
};
let Expr::Name(ast::ExprName { id, .. }) = target else {
return;
};
let semantic = checker.semantic();
if is_special_assignment(target, semantic) {
return;
}
if is_type_var_like_call(value, semantic) {
return;
}
if is_valid_default_value_without_annotation(value) {
return;
}
if !is_valid_default_value_with_annotation(value, true, checker.locator(), semantic) {
return;
}
if let ScopeKind::Class(class_def) = semantic.current_scope().kind {
if is_enumeration(class_def, semantic) {
return;
}
}
checker.report_diagnostic(
UnannotatedAssignmentInStub {
name: id.to_string(),
},
value.range(),
);
}
/// PYI035
pub(crate) fn unassigned_special_variable_in_stub(checker: &Checker, target: &Expr, stmt: &Stmt) {
let Expr::Name(ast::ExprName { id, .. }) = target else {
return;
};
if !is_special_assignment(target, checker.semantic()) {
return;
}
checker.report_diagnostic(
UnassignedSpecialVariableInStub {
name: id.to_string(),
},
stmt.range(),
);
}
/// PYI026
pub(crate) fn type_alias_without_annotation(checker: &Checker, value: &Expr, targets: &[Expr]) {
let [target] = targets else {
return;
};
let Expr::Name(ast::ExprName { id, .. }) = target else {
return;
};
if !is_annotatable_type_alias(value, checker.semantic()) {
return;
}
let module = if checker.target_version() >= PythonVersion::PY310 {
TypingModule::Typing
} else {
TypingModule::TypingExtensions
};
let Some(importer) = checker.typing_importer("TypeAlias", PythonVersion::PY310) else {
return;
};
let mut diagnostic = checker.report_diagnostic(
TypeAliasWithoutAnnotation {
module,
name: id.to_string(),
value: checker.generator().expr(value),
},
target.range(),
);
diagnostic.try_set_fix(|| {
let (import_edit, binding) = importer.import(target.start())?;
Ok(Fix::safe_edits(
Edit::range_replacement(format!("{id}: {binding}"), target.range()),
[import_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_pyi/rules/string_or_bytes_too_long.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/string_or_bytes_too_long.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_docstring_stmt;
use ruff_python_ast::{self as ast, StringLike};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for the use of string and bytes literals longer than 50 characters
/// in stub (`.pyi`) files.
///
/// ## Why is this bad?
/// If a function or variable has a default value where the string or bytes
/// representation is greater than 50 characters long, it is likely to be an
/// implementation detail or a constant that varies depending on the system
/// you're running on.
///
/// Although IDEs may find them useful, default values are ignored by type
/// checkers, the primary consumers of stub files. Replace very long constants
/// with ellipses (`...`) to simplify the stub.
///
/// ## Example
///
/// ```pyi
/// def foo(arg: str = "51 character stringgggggggggggggggggggggggggggggggg") -> None: ...
/// ```
///
/// Use instead:
///
/// ```pyi
/// def foo(arg: str = ...) -> None: ...
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.271")]
pub(crate) struct StringOrBytesTooLong;
impl AlwaysFixableViolation for StringOrBytesTooLong {
#[derive_message_formats]
fn message(&self) -> String {
"String and bytes literals longer than 50 characters are not permitted".to_string()
}
fn fix_title(&self) -> String {
"Replace with `...`".to_string()
}
}
/// PYI053
pub(crate) fn string_or_bytes_too_long(checker: &Checker, string: StringLike) {
let semantic = checker.semantic();
// Ignore docstrings.
if is_docstring_stmt(semantic.current_statement()) {
return;
}
if is_warnings_dot_deprecated(semantic.current_expression_parent(), semantic) {
return;
}
if semantic.in_type_definition() | semantic.in_deferred_type_definition() {
return;
}
let length = match string {
StringLike::String(ast::ExprStringLiteral { value, .. }) => value.chars().count(),
StringLike::Bytes(ast::ExprBytesLiteral { value, .. }) => value.len(),
StringLike::FString(node) => count_f_string_chars(node),
// TODO(dylan): decide how to count chars, especially
// if interpolations are of different type than `str`
StringLike::TString(_) => {
return;
}
};
if length <= 50 {
return;
}
let mut diagnostic = checker.report_diagnostic(StringOrBytesTooLong, string.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
"...".to_string(),
string.range(),
)));
}
/// Count the number of visible characters in an f-string. This accounts for
/// implicitly concatenated f-strings as well.
fn count_f_string_chars(f_string: &ast::ExprFString) -> usize {
f_string
.value
.iter()
.map(|part| match part {
ast::FStringPart::Literal(string) => string.chars().count(),
ast::FStringPart::FString(f_string) => f_string
.elements
.iter()
.map(|element| match element {
ast::InterpolatedStringElement::Literal(string) => string.chars().count(),
ast::InterpolatedStringElement::Interpolation(expr) => {
expr.range().len().to_usize()
}
})
.sum(),
})
.sum()
}
fn is_warnings_dot_deprecated(expr: Option<&ast::Expr>, semantic: &SemanticModel) -> bool {
// Does `expr` represent a call to `warnings.deprecated` or `typing_extensions.deprecated`?
let Some(expr) = expr else {
return false;
};
let Some(call) = expr.as_call_expr() else {
return false;
};
semantic
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["warnings" | "typing_extensions", "deprecated"]
)
})
}
| 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_pyi/rules/redundant_literal_union.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_literal_union.rs | use std::fmt;
use rustc_hash::FxHashSet;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, LiteralExpressionRef};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::typing::traverse_union;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
/// ## What it does
/// Checks for redundant unions between a `Literal` and a builtin supertype of
/// that `Literal`.
///
/// ## Why is this bad?
/// Using a `Literal` type in a union with its builtin supertype is redundant,
/// as the supertype will be strictly more general than the `Literal` type.
/// For example, `Literal["A"] | str` is equivalent to `str`, and
/// `Literal[1] | int` is equivalent to `int`, as `str` and `int` are the
/// supertypes of `"A"` and `1` respectively.
///
/// ## Example
/// ```pyi
/// from typing import Literal
///
/// x: Literal["A", b"B"] | str
/// ```
///
/// Use instead:
/// ```pyi
/// from typing import Literal
///
/// x: Literal[b"B"] | str
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.283")]
pub(crate) struct RedundantLiteralUnion {
literal: SourceCodeSnippet,
builtin_type: ExprType,
}
impl Violation for RedundantLiteralUnion {
#[derive_message_formats]
fn message(&self) -> String {
let RedundantLiteralUnion {
literal,
builtin_type,
} = self;
if let Some(literal) = literal.full_display() {
format!("`Literal[{literal}]` is redundant in a union with `{builtin_type}`")
} else {
format!("`Literal` is redundant in a union with `{builtin_type}`")
}
}
}
/// PYI051
pub(crate) fn redundant_literal_union<'a>(checker: &Checker, union: &'a Expr) {
let mut typing_literal_exprs = Vec::new();
let mut builtin_types_in_union = FxHashSet::default();
// Adds a member to `literal_exprs` for each value in a `Literal`, and any builtin types
// to `builtin_types_in_union`.
let mut func = |expr: &'a Expr, _parent: &'a Expr| {
if let Expr::Subscript(ast::ExprSubscript { value, slice, .. }) = expr {
if checker.semantic().match_typing_expr(value, "Literal") {
if let Expr::Tuple(tuple) = &**slice {
typing_literal_exprs.extend(tuple);
} else {
typing_literal_exprs.push(slice);
}
}
return;
}
let Some(builtin_type) = match_builtin_type(expr, checker.semantic()) else {
return;
};
builtin_types_in_union.insert(builtin_type);
};
traverse_union(&mut func, checker.semantic(), union);
for typing_literal_expr in typing_literal_exprs {
let Some(literal_type) = match_literal_type(typing_literal_expr) else {
continue;
};
if builtin_types_in_union.contains(&literal_type) {
checker.report_diagnostic(
RedundantLiteralUnion {
literal: SourceCodeSnippet::from_str(
checker.locator().slice(typing_literal_expr),
),
builtin_type: literal_type,
},
typing_literal_expr.range(),
);
}
}
}
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
enum ExprType {
Int,
Str,
Bool,
Float,
Bytes,
Complex,
}
impl fmt::Display for ExprType {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Int => fmt.write_str("int"),
Self::Str => fmt.write_str("str"),
Self::Bool => fmt.write_str("bool"),
Self::Float => fmt.write_str("float"),
Self::Bytes => fmt.write_str("bytes"),
Self::Complex => fmt.write_str("complex"),
}
}
}
/// Return the [`ExprType`] of an [`Expr]` if it is a builtin type (e.g. `int`, `bool`, `float`,
/// `str`, `bytes`, or `complex`).
fn match_builtin_type(expr: &Expr, semantic: &SemanticModel) -> Option<ExprType> {
let result = match semantic.resolve_builtin_symbol(expr)? {
"int" => ExprType::Int,
"bool" => ExprType::Bool,
"str" => ExprType::Str,
"float" => ExprType::Float,
"bytes" => ExprType::Bytes,
"complex" => ExprType::Complex,
_ => return None,
};
Some(result)
}
/// Return the [`ExprType`] of an [`Expr`] if it is a literal (e.g., an `int`, like `1`, or a
/// `bool`, like `True`).
fn match_literal_type(expr: &Expr) -> Option<ExprType> {
Some(match expr.as_literal_expr()? {
LiteralExpressionRef::BooleanLiteral(_) => ExprType::Bool,
LiteralExpressionRef::StringLiteral(_) => ExprType::Str,
LiteralExpressionRef::BytesLiteral(_) => ExprType::Bytes,
LiteralExpressionRef::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => match value {
ast::Number::Int(_) => ExprType::Int,
ast::Number::Float(_) => ExprType::Float,
ast::Number::Complex { .. } => ExprType::Complex,
},
LiteralExpressionRef::NoneLiteral(_) | LiteralExpressionRef::EllipsisLiteral(_) => {
return 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_pyi/rules/unnecessary_literal_union.rs | crates/ruff_linter/src/rules/flake8_pyi/rules/unnecessary_literal_union.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::pep_604_union;
use ruff_python_ast::{self as ast, Expr, ExprContext};
use ruff_python_semantic::analyze::typing::traverse_union;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for the presence of multiple literal types in a union.
///
/// ## Why is this bad?
/// `Literal["foo", 42]` has identical semantics to
/// `Literal["foo"] | Literal[42]`, but is clearer and more concise.
///
/// ## Example
/// ```pyi
/// from typing import Literal
///
/// field: Literal[1] | Literal[2] | str
/// ```
///
/// Use instead:
/// ```pyi
/// from typing import Literal
///
/// field: Literal[1, 2] | str
/// ```
///
/// ## Fix safety
/// This fix is marked unsafe if it would delete any comments within the replacement range.
///
/// An example to illustrate where comments are preserved and where they are not:
///
/// ```pyi
/// from typing import Literal
///
/// field: (
/// # deleted comment
/// Literal["a", "b"] # deleted comment
/// # deleted comment
/// | Literal["c", "d"] # preserved comment
/// )
/// ```
///
/// ## References
/// - [Python documentation: `typing.Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.278")]
pub(crate) struct UnnecessaryLiteralUnion {
members: Vec<String>,
}
impl Violation for UnnecessaryLiteralUnion {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Multiple literal members in a union. Use a single literal, e.g. `Literal[{}]`",
self.members.join(", ")
)
}
fn fix_title(&self) -> Option<String> {
Some("Replace with a single `Literal`".to_string())
}
}
/// PYI030
pub(crate) fn unnecessary_literal_union<'a>(checker: &Checker, expr: &'a Expr) {
let mut literal_exprs = Vec::new();
let mut other_exprs = Vec::new();
// For the sake of consistency, use the first `Literal` subscript to construct the fix.
let mut literal_subscript = None;
let mut total_literals = 0;
// Split members into `literal_exprs` if they are a `Literal` annotation and `other_exprs` otherwise
let mut collect_literal_expr = |expr: &'a Expr, _parent: &'a Expr| {
if let Expr::Subscript(ast::ExprSubscript { value, slice, .. }) = expr {
if checker.semantic().match_typing_expr(value, "Literal") {
total_literals += 1;
if literal_subscript.is_none() {
literal_subscript = Some(value.as_ref());
}
let slice = &**slice;
// flatten already-unioned literals to later union again
if let Expr::Tuple(tuple) = slice {
for item in tuple {
literal_exprs.push(item);
}
} else {
literal_exprs.push(slice);
}
} else {
other_exprs.push(expr);
}
} else {
other_exprs.push(expr);
}
};
// Traverse the union, collect all members, split out the literals from the rest.
traverse_union(&mut collect_literal_expr, checker.semantic(), expr);
let union_subscript = expr.as_subscript_expr();
if union_subscript.is_some_and(|subscript| {
!checker
.semantic()
.match_typing_expr(&subscript.value, "Union")
}) {
return;
}
// If there are no literal members, we don't need to do anything.
let Some(literal_subscript) = literal_subscript else {
return;
};
if total_literals == 0 || total_literals == 1 {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryLiteralUnion {
members: literal_exprs
.iter()
.map(|expr| checker.locator().slice(expr).to_string())
.collect(),
},
expr.range(),
);
diagnostic.set_fix({
let literal = Expr::Subscript(ast::ExprSubscript {
value: Box::new(literal_subscript.clone()),
slice: Box::new(Expr::Tuple(ast::ExprTuple {
elts: literal_exprs.into_iter().cloned().collect(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
ctx: ExprContext::Load,
parenthesized: true,
})),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
ctx: ExprContext::Load,
});
let edit = if other_exprs.is_empty() {
Edit::range_replacement(checker.generator().expr(&literal), expr.range())
} else {
let elts: Vec<Expr> = std::iter::once(literal)
.chain(other_exprs.into_iter().cloned())
.collect();
let content = if let Some(union) = union_subscript {
checker
.generator()
.expr(&Expr::Subscript(ast::ExprSubscript {
value: union.value.clone(),
slice: Box::new(Expr::Tuple(ast::ExprTuple {
elts,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
ctx: ExprContext::Load,
parenthesized: true,
})),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
ctx: ExprContext::Load,
}))
} else {
checker.generator().expr(&pep_604_union(&elts))
};
Edit::range_replacement(content, expr.range())
};
if checker.comment_ranges().intersects(expr.range()) {
Fix::unsafe_edit(edit)
} else {
Fix::safe_edit(edit)
}
});
}
| 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.