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

Conversation

mhils
Copy link
Contributor

@mhils mhils commented Nov 9, 2022

Optional["ForwardRef"] currently requires two pyupgrade calls to be fully rewritten. Here's a minimal example:

$ echo "from __future__ import annotations; from typing import Optional; x: Optional['str']" > repro.py

$ pyupgrade --py39-plus repro.py; cat repro.py
Rewriting repro.py
from __future__ import annotations; from typing import Optional; x: Optional[str]

$ pyupgrade --py39-plus repro.py; cat repro.py
Rewriting repro.py
from __future__ import annotations; from typing import Optional; x: str | None

The problem here is that typing_pep604.py bails if it encounters a forward annotation (#567). This PR adjusts the check to guess ahead if annotations will be dequoted by typing_pep563.py.

I guess there's an argument to be made that forward refs and from __future__ import annotations in the same file aren't best practice to begin with, but I've encountered that in real-world code and figured I'd send a fix. No hard feelings if you consider this a wontfix. :)

mhils added a commit to mhils/r8 that referenced this pull request Nov 9, 2022
Comment on lines 157 to 158
has_forward_annotation and
'annotations' not in state.from_imports['__future__']
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while it probably doesn't actually matter in practice -- the 'annotations' in check is very cheap and should probably come before the computation for forward annotations

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, fixed. I've kept the has_forward_annotation variable for readability, but that is subjective. Let me know if you want me to make it a single big if statement. :)

Copy link
Owner

@asottile asottile left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@asottile asottile merged commit bba6fec into asottile:main Nov 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants