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

PYI061 fixes Literal[None,] | Literal[None,] to None | None #16177

Open
dscorbett opened this issue Feb 15, 2025 · 2 comments
Open

PYI061 fixes Literal[None,] | Literal[None,] to None | None #16177

dscorbett opened this issue Feb 15, 2025 · 2 comments
Labels
bug Something isn't working fixes Related to suggested fixes for violations help wanted Contributions especially welcome

Comments

@dscorbett
Copy link

Description

The fix for redundant-none-literal (PYI061) converts Literal[None,] | Literal[None,] to None | None, which can raise an exception.

$ cat >pyi061.py <<'# EOF'
from typing import Literal
x: Literal[None,] | Literal[None,]
# EOF

$ python pyi061.py

$ ruff --isolated check --preview --select PYI061 pyi061.py --fix
Found 2 errors (2 fixed, 0 remaining).

$ python pyi061.py                               
Traceback (most recent call last):
  File "pyi061.py", line 2, in <module>
    x: None | None
       ~~~~~^~~~~~
TypeError: unsupported operand type(s) for |: 'NoneType' and 'NoneType'
@AlexWaygood AlexWaygood added bug Something isn't working fixes Related to suggested fixes for violations help wanted Contributions especially welcome labels Feb 15, 2025
@VascoSch92
Copy link
Contributor

I think I can fix that. Should be not so difficult.

Another question: I tried to fix the example giving in the doc, and I had another result that the one presented, i.e.,

from typing import Literal
y: Literal[1, 2, 3, "foo", 5, None]

was fixed as

from typing import Literal, Optional
y: Optional[Literal[1, 2, 3, "foo", 5]]

after command ruff --isolated check --preview --select PYI061 scratch.py --fix, but in the docs the fix is given by
Literal[1, 2, 3, "foo", 5] | None.

Which one is the correct/expected fix? Is the fix wrong or the doc :-) ?

FYI: I'm using Python 3.10.14 and Ruff 0.9.6

@InSyncWithFoo
Copy link
Contributor

@VascoSch92 The fix changes depending on what target-version is. For 3.9 (default) and lower, it uses Optional[...]; for 3.10 and higher, it uses ... | None.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working fixes Related to suggested fixes for violations help wanted Contributions especially welcome
Projects
None yet
Development

No branches or pull requests

4 participants