Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Optional["ForwardRef"] rewriting #750

Merged
merged 1 commit into from Nov 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 11 additions & 10 deletions pyupgrade/_plugins/typing_pep604.py
Expand Up @@ -144,16 +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
# don't rewrite forward annotations (unless we know they will be dequoted)
if 'annotations' not in state.from_imports['__future__']:
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,
Expand Down
11 changes: 11 additions & 0 deletions tests/features/typing_pep604_test.py
Expand Up @@ -185,6 +185,17 @@ def f(x: int | str) -> None: ...

id='Optional rewrite multi-line',
),
pytest.param(
'from __future__ import annotations\n'
'from typing import Optional\n'
'x: Optional["str"]\n',

'from __future__ import annotations\n'
'from typing import Optional\n'
'x: str | None\n',

id='Optional rewrite with forward reference',
),
pytest.param(
'from typing import Union, Sequence\n'
'def f(x: Union[Union[A, B], Sequence[Union[C, D]]]): pass\n',
Expand Down