diff --git a/crates/ruff/resources/test/fixtures/pyupgrade/UP007.py b/crates/ruff/resources/test/fixtures/pyupgrade/UP007.py index 3523fff908a29..1b628aabdfc12 100644 --- a/crates/ruff/resources/test/fixtures/pyupgrade/UP007.py +++ b/crates/ruff/resources/test/fixtures/pyupgrade/UP007.py @@ -41,3 +41,8 @@ def f(x: Union["str", int]) -> None: def f(x: Union[("str", "int"), float]) -> None: ... + + +def f() -> None: + x: Optional[str] + x = Optional[str] diff --git a/crates/ruff/src/checkers/ast.rs b/crates/ruff/src/checkers/ast.rs index 4df49b76e80a8..6ef66bb48f8b2 100644 --- a/crates/ruff/src/checkers/ast.rs +++ b/crates/ruff/src/checkers/ast.rs @@ -2172,8 +2172,9 @@ where // Pre-visit. match &expr.node { ExprKind::Subscript { value, slice, .. } => { - // Ex) Optional[...] - if !self.in_deferred_string_type_definition + // Ex) Optional[...], Union[...] + if self.in_type_definition + && !self.in_deferred_string_type_definition && !self.settings.pyupgrade.keep_runtime_typing && self.settings.rules.enabled(&Rule::TypingUnion) && (self.settings.target_version >= PythonVersion::Py310 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 c4f8211e3dd02..8583dc305791a 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 @@ -121,4 +121,21 @@ expression: diagnostics row: 26 column: 40 parent: ~ +- kind: + TypingUnion: ~ + location: + row: 47 + column: 7 + end_location: + row: 47 + column: 20 + fix: + content: str | None + location: + row: 47 + column: 7 + end_location: + row: 47 + column: 20 + parent: ~