Skip to content

Commit

Permalink
prevent rewriting union types with forward annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
asottile committed Nov 16, 2021
1 parent f5b16fc commit 886c3f0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
20 changes: 20 additions & 0 deletions pyupgrade/_plugins/typing_pep604.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,15 @@ def _supported_version(state: State) -> bool:
)


def _any_arg_is_str(node_slice: ast.expr) -> bool:
return (
isinstance(node_slice, ast.Str) or (
isinstance(node_slice, ast.Tuple) and
any(isinstance(elt, ast.Str) for elt in node_slice.elts)
)
)


@register(ast.Subscript)
def visit_Subscript(
state: State,
Expand All @@ -135,6 +144,17 @@ def visit_Subscript(
if not _supported_version(state):
return

# prevent rewriting forward annotations
if (
(sys.version_info >= (3, 9) and _any_arg_is_str(node.slice)) or
(
sys.version_info < (3, 9) and
isinstance(node.slice, ast.Index) and
_any_arg_is_str(node.slice.value)
)
):
return

if is_name_attr(node.value, state.from_imports, 'typing', ('Optional',)):
yield ast_to_offset(node), _fix_optional
elif is_name_attr(node.value, state.from_imports, 'typing', ('Union',)):
Expand Down
13 changes: 13 additions & 0 deletions tests/features/typing_pep604_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@
(3, 10),
id='3.10+ empty Union',
),
# https://github.com/asottile/pyupgrade/issues/567
pytest.param(
'from typing import Optional\n'
'def f() -> Optional["str"]: ...\n',
(3, 10),
id='3.10+ Optional of forward reference',
),
pytest.param(
'from typing import Union\n'
'def f() -> Union[int, "str"]: ...\n',
(3, 10),
id='3.10+ Union of forward reference',
),
),
)
def test_fix_pep604_types_noop(s, version):
Expand Down

0 comments on commit 886c3f0

Please sign in to comment.