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

Ruff rewrites Union[tuple_of_types] in potentially breaking ways #3215

Closed
rouge8 opened this issue Feb 24, 2023 · 4 comments · Fixed by #3217
Closed

Ruff rewrites Union[tuple_of_types] in potentially breaking ways #3215

rouge8 opened this issue Feb 24, 2023 · 4 comments · Fixed by #3217
Assignees
Labels
bug Something isn't working

Comments

@rouge8
Copy link
Contributor

rouge8 commented Feb 24, 2023

After Ruff rewrites this file, Python starts throwing an error.

t.py

from typing import Union, cast


def _make_optional(cls: type) -> type:
    """Convert a type to an Optional type."""
    return cast(type, cls | None)


new_types = (int, float)

_make_optional(cast(type, Union[new_types]))

output

❯ ruff --isolated --fix --target-version py311 --select UP t.py
Found 1 error (1 fixed, 0 remaining).

rewritten

from typing import Union, cast


def _make_optional(cls: type) -> type:
    """Convert a type to an Optional type."""
    return cast(type, cls | None)


new_types = (int, float)

_make_optional(cast(type, new_types))

Unfortunately, t.py now errors out:

Traceback (most recent call last):
  File "/Users/andyfreeland/t.py", line 11, in <module>
    _make_optional(cast(type, new_types))
  File "/Users/andyfreeland/t.py", line 6, in _make_optional
    return cast(type, cls | None)
                      ~~~~^~~~~~
TypeError: unsupported operand type(s) for |: 'tuple' and 'NoneType'

version

ruff 0.0.252
@rouge8
Copy link
Contributor Author

rouge8 commented Feb 24, 2023

FWIW, pyupgrade --py311-plus t.py does not make any changes to the original t.py.

@charliermarsh
Copy link
Member

Yeah pyupgrade never applies PEP 604 transformations to runtime types. Maybe we shouldn't either. It's come up before.

@charliermarsh charliermarsh added the bug Something isn't working label Feb 24, 2023
@charliermarsh
Copy link
Member

This was another recent case: #2981.

@charliermarsh
Copy link
Member

(So let's just change it.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants