Skip to content

Commit

Permalink
Allow Final assignments in stubs (#5490)
Browse files Browse the repository at this point in the history
## Summary

This fixes one incompatibility with `flake8-pyi`, and gives us a clean
pass on `typeshed`.
  • Loading branch information
charliermarsh authored Jul 3, 2023
1 parent ed1dd09 commit 8de5a3d
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions crates/ruff/resources/test/fixtures/flake8_pyi/PYI015.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,4 @@ class Class1:
field28 = builtins.str
field29 = str
field30 = str | bytes | None
field31: typing.Final = field30
1 change: 1 addition & 0 deletions crates/ruff/resources/test/fixtures/flake8_pyi/PYI015.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,4 @@ field27 = list[str]
field28 = builtins.str
field29 = str
field30 = str | bytes | None
field31: typing.Final = field30
13 changes: 13 additions & 0 deletions crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,16 @@ fn is_special_assignment(target: &Expr, semantic: &SemanticModel) -> bool {
}
}

/// 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 the a class is an enum, based on its base classes.
fn is_enum(bases: &[Expr], semantic: &SemanticModel) -> bool {
return bases.iter().any(|expr| {
Expand Down Expand Up @@ -438,6 +448,9 @@ pub(crate) fn annotated_assignment_default_in_stub(
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;
}
Expand Down

0 comments on commit 8de5a3d

Please sign in to comment.