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

idea: Add rule for flattening nested Literals #7881

Open
diceroll123 opened this issue Oct 10, 2023 · 5 comments
Open

idea: Add rule for flattening nested Literals #7881

diceroll123 opened this issue Oct 10, 2023 · 5 comments
Labels
needs-decision Awaiting a decision from a maintainer rule Implementing or modifying a lint rule

Comments

@diceroll123
Copy link
Contributor

From PEP 586, Literal[Literal[Literal[1, 2, 3], "foo"], 5, None] is equivalent to Literal[1, 2, 3, "foo", 5, None]

Currently there's no rule I know of that would unfurl/flatten a literal structure like this. Would be neat!

I came across this while fiddling with #7880.

@T-256
Copy link
Contributor

T-256 commented Oct 10, 2023

++ Union and Annotated.

@charliermarsh
Copy link
Member

Could this not be part of PYI030 itself (https://docs.astral.sh/ruff/rules/unnecessary-literal-union/)?

@charliermarsh charliermarsh added rule Implementing or modifying a lint rule needs-decision Awaiting a decision from a maintainer labels Oct 13, 2023
@T-256
Copy link
Contributor

T-256 commented Oct 13, 2023

Could this not be part of PYI030 itself (https://docs.astral.sh/ruff/rules/unnecessary-literal-union/)?

As its name says that is Unnecessery union but here I think we need Unnecessery nested.
For Unnecessery union, types get joined:

field: Literal[1] | Literal[2]  # FIX: Literal[1, 2] 

For Unnecessery nested, types get unpacked:

field: Literal[1, Literal[2]]  # FIX: Literal[1, 2]

@diceroll123
Copy link
Contributor Author

Could this not be part of PYI030 itself (docs.astral.sh/ruff/rules/unnecessary-literal-union)?

I've implemented this in as part of #7934, but of course this is strictly for literals.

@Avasam
Copy link
Contributor

Avasam commented Nov 22, 2023

Could this not be part of PYI030 itself (https://docs.astral.sh/ruff/rules/unnecessary-literal-union/)?

It could. But can also be a new code. It was not implemented in flake8-pyi for the sole reason it was not deemed worth the effort for typeshed. PyCQA/flake8-pyi#425

Also note the existence of Y061 PyCQA/flake8-pyi#435
Which prefers Literal[0] | None over Literal[0, None] and is an opinionated and purely aesthetic rule (flake8-pyi doesn't need to support enforcing the second form because they are their own users at typeshed)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-decision Awaiting a decision from a maintainer rule Implementing or modifying a lint rule
Projects
None yet
Development

No branches or pull requests

4 participants