Skip to content

Commit 056c130

Browse files
committed
[pyupgrade] Fix false positive for TypeVar with default on Python<3.13 (UP046,UP047)
Type default for Type parameter was added in Python 3.13 (PEP 696). `typing_extensions.TypeVar` backports the default argument to earlier versions. `UP046` & `UP047` were getting triggered when typing_extensions.TypeVar with `default` argument was used on python version < 3.13 It shouldn't be triggered for python version < 3.13 This commit fixes the bug by adding a python version check before triggering them. Fixes #20929. Signed-off-by: Prakhar Pratyush <prakhar1144@gmail.com>
1 parent 7198e53 commit 056c130

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

  • crates/ruff_linter/src/rules/pyupgrade/rules/pep695

crates/ruff_linter/src/rules/pyupgrade/rules/pep695/mod.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ use std::fmt::Display;
66

77
use itertools::Itertools;
88
use ruff_python_ast::{
9-
self as ast, Arguments, Expr, ExprCall, ExprName, ExprSubscript, Identifier, Stmt, StmtAssign,
10-
TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple,
9+
self as ast, Arguments, Expr, ExprCall, ExprName, ExprSubscript, Identifier, PythonVersion,
10+
Stmt, StmtAssign, TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple,
1111
name::Name,
1212
visitor::{self, Visitor},
1313
};
@@ -369,15 +369,19 @@ fn in_nested_context(checker: &Checker) -> bool {
369369
}
370370

371371
/// Deduplicate `vars`, returning `None` if `vars` is empty or any duplicates are found.
372-
/// Also returns `None` if any `TypeVar` has a default value and preview mode is not enabled.
372+
/// Also returns `None` if any `TypeVar` has a default value and the target Python version
373+
/// is below 3.13 or preview mode is not enabled. Note that `typing_extensions` backports
374+
/// the default argument, but the rule should be skipped in that case.
373375
fn check_type_vars<'a>(vars: Vec<TypeVar<'a>>, checker: &Checker) -> Option<Vec<TypeVar<'a>>> {
374376
if vars.is_empty() {
375377
return None;
376378
}
377379

378-
// If any type variables have defaults and preview mode is not enabled, skip the rule
380+
// If any type variables have defaults, skip the rule unless
381+
// running with preview mode enabled and targeting Python 3.13+.
379382
if vars.iter().any(|tv| tv.default.is_some())
380-
&& !is_type_var_default_enabled(checker.settings())
383+
&& (checker.target_version() < PythonVersion::PY313
384+
|| !is_type_var_default_enabled(checker.settings()))
381385
{
382386
return None;
383387
}

0 commit comments

Comments
 (0)