From ac600bb3da05b7259a8b646c36e1dfe21ef8c450 Mon Sep 17 00:00:00 2001 From: wookie184 Date: Tue, 2 May 2023 07:49:20 +0100 Subject: [PATCH] Warn on PEP 604 syntax not in an annotation, but don't autofix (#4170) --- crates/ruff/src/checkers/ast/mod.rs | 3 +-- .../pyupgrade/rules/use_pep604_annotation.rs | 13 ++++++------ ...ff__rules__pyupgrade__tests__UP007.py.snap | 20 +++++++++++++++++++ 3 files changed, 28 insertions(+), 8 deletions(-) diff --git a/crates/ruff/src/checkers/ast/mod.rs b/crates/ruff/src/checkers/ast/mod.rs index 7b348e1488..a414077466 100644 --- a/crates/ruff/src/checkers/ast/mod.rs +++ b/crates/ruff/src/checkers/ast/mod.rs @@ -2281,8 +2281,7 @@ where match &expr.node { ExprKind::Subscript { value, slice, .. } => { // Ex) Optional[...], Union[...] - if self.ctx.in_type_definition - && !self.settings.pyupgrade.keep_runtime_typing + if !self.settings.pyupgrade.keep_runtime_typing && self.settings.rules.enabled(Rule::NonPEP604Annotation) && (self.settings.target_version >= PythonVersion::Py310 || (self.settings.target_version >= PythonVersion::Py37 diff --git a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs index 2c51cb2d32..e6e1500d37 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs @@ -100,12 +100,13 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s return; }; - // Avoid fixing forward references. - let fixable = checker - .ctx - .in_deferred_string_type_definition - .as_ref() - .map_or(true, AnnotationKind::is_simple); + // Avoid fixing forward references, or types not in an annotation. + let fixable = checker.ctx.in_type_definition + && checker + .ctx + .in_deferred_string_type_definition + .as_ref() + .map_or(true, AnnotationKind::is_simple); match typing_member { TypingMember::Optional => { diff --git a/crates/ruff/src/rules/pyupgrade/snapshots/ruff__rules__pyupgrade__tests__UP007.py.snap b/crates/ruff/src/rules/pyupgrade/snapshots/ruff__rules__pyupgrade__tests__UP007.py.snap index 079806c6bf..b844f6a84b 100644 --- a/crates/ruff/src/rules/pyupgrade/snapshots/ruff__rules__pyupgrade__tests__UP007.py.snap +++ b/crates/ruff/src/rules/pyupgrade/snapshots/ruff__rules__pyupgrade__tests__UP007.py.snap @@ -200,6 +200,26 @@ UP007.py:47:8: UP007 [*] Use `X | Y` for type annotations 49 49 | 50 50 | x = Union[str, int] +UP007.py:48:9: UP007 Use `X | Y` for type annotations + | +48 | def f() -> None: +49 | x: Optional[str] +50 | x = Optional[str] + | ^^^^^^^^^^^^^ UP007 +51 | +52 | x = Union[str, int] + | + +UP007.py:50:9: UP007 Use `X | Y` for type annotations + | +50 | x = Optional[str] +51 | +52 | x = Union[str, int] + | ^^^^^^^^^^^^^^^ UP007 +53 | x = Union["str", "int"] +54 | x: Union[str, int] + | + UP007.py:52:8: UP007 [*] Use `X | Y` for type annotations | 52 | x = Union[str, int]