Warn on PEP 604 syntax not in an annotation, but don't autofix (#4170)

This commit is contained in:
wookie184 2023-05-02 07:49:20 +01:00 committed by GitHub
parent 8cb76f85eb
commit ac600bb3da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 8 deletions

View File

@ -2281,8 +2281,7 @@ where
match &expr.node { match &expr.node {
ExprKind::Subscript { value, slice, .. } => { ExprKind::Subscript { value, slice, .. } => {
// Ex) Optional[...], Union[...] // Ex) Optional[...], Union[...]
if self.ctx.in_type_definition if !self.settings.pyupgrade.keep_runtime_typing
&& !self.settings.pyupgrade.keep_runtime_typing
&& self.settings.rules.enabled(Rule::NonPEP604Annotation) && self.settings.rules.enabled(Rule::NonPEP604Annotation)
&& (self.settings.target_version >= PythonVersion::Py310 && (self.settings.target_version >= PythonVersion::Py310
|| (self.settings.target_version >= PythonVersion::Py37 || (self.settings.target_version >= PythonVersion::Py37

View File

@ -100,12 +100,13 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
return; return;
}; };
// Avoid fixing forward references. // Avoid fixing forward references, or types not in an annotation.
let fixable = checker let fixable = checker.ctx.in_type_definition
.ctx && checker
.in_deferred_string_type_definition .ctx
.as_ref() .in_deferred_string_type_definition
.map_or(true, AnnotationKind::is_simple); .as_ref()
.map_or(true, AnnotationKind::is_simple);
match typing_member { match typing_member {
TypingMember::Optional => { TypingMember::Optional => {

View File

@ -200,6 +200,26 @@ UP007.py:47:8: UP007 [*] Use `X | Y` for type annotations
49 49 | 49 49 |
50 50 | x = Union[str, int] 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 UP007.py:52:8: UP007 [*] Use `X | Y` for type annotations
| |
52 | x = Union[str, int] 52 | x = Union[str, int]