Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow typing_extensions.TypeVar assignments in .pyi files #3951

Merged
merged 1 commit into from
Apr 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use rustpython_parser::ast::{Arguments, Constant, Expr, ExprKind, Operator, Unar
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::types::Range;
use ruff_python_semantic::context::Context;

use crate::checkers::ast::Checker;
use crate::registry::AsRule;
Expand Down Expand Up @@ -221,21 +222,21 @@ fn is_valid_default_value_with_annotation(
false
}

pub fn is_type_var_call(checker: &Checker, expr: &Expr) -> bool {
/// Returns `true` if an [`Expr`] appears to be `TypeVar`, `TypeVarTuple`, `NewType`, or `ParamSpec`
/// call.
fn is_type_var_like_call(context: &Context, expr: &Expr) -> bool {
let ExprKind::Call {func, ..} = &expr.node else {
return false;
};
checker
.ctx
.resolve_call_path(func)
.map_or(false, |call_path| {
call_path.as_slice() == ["typing", "TypeVar"]
|| call_path.as_slice() == ["typing", "TypeVarTuple"]
|| call_path.as_slice() == ["typing_extensions", "TypeVarTuple"]
|| call_path.as_slice() == ["typing", "NewType"]
|| call_path.as_slice() == ["typing", "ParamSpec"]
|| call_path.as_slice() == ["typing_extensions", "ParamSpec"]
})
context.resolve_call_path(func).map_or(false, |call_path| {
matches!(
call_path.as_slice(),
[
"typing" | "typing_extensions",
"TypeVar" | "TypeVarTuple" | "NewType" | "ParamSpec"
]
)
})
}

/// PYI011
Expand Down Expand Up @@ -359,7 +360,7 @@ pub fn assignment_default_in_stub(checker: &mut Checker, value: &Expr, annotatio
}) {
return;
}
if is_type_var_call(checker, value) {
if is_type_var_like_call(&checker.ctx, value) {
return;
}
if !is_valid_default_value_with_annotation(value, checker, true) {
Expand Down