Skip to content

Reject direct union expressions in Literal#21540

Open
97littleleaf11 wants to merge 2 commits into
python:masterfrom
97littleleaf11:fix-17260
Open

Reject direct union expressions in Literal#21540
97littleleaf11 wants to merge 2 commits into
python:masterfrom
97littleleaf11:fix-17260

Conversation

@97littleleaf11
Copy link
Copy Markdown
Collaborator

Fixes #17260

A union expression inside Literal[...] should not be valid, e.g. Literal[1 | None] or Literal[Union[Literal[1], None]].

Remaining issues to discuss, cc @JukkaL :

Alias1 = Literal[1, None]
x: Literal[Alias1]        # currently valid in mypy with a special check. is a nested Literal valid?

Alias2 = Literal[1] | None
y: Literal[Alias2]        # valid, or should this also be rejected?

@github-actions
Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

xarray (https://github.com/pydata/xarray)
+ xarray/core/groupby.py: note: In member "_first_or_last" of class "GroupBy":
+ xarray/core/groupby.py:1461: error: Parameter 1 of Literal[...] cannot be a union expression  [valid-type]
+ xarray/core/groupby.py: note: At top level:

from typing import Literal as L, Optional as O, Union as U

a: Literal[1 | None] # E: Parameter 1 of Literal[...] cannot be a union expression
b: Literal[1 | 2] # E: Parameter 1 of Literal[...] cannot be a union expression
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

bad case of error msg here. 1 | 2 should be recongized as bitwise operation?

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.

False negative: typing.Literal[<Union expression>]

1 participant