Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ flake8-pyi uses Calendar Versioning (CalVer).
* Y002 no longer flags nested `and`/`or` combinations of `sys.version_info` and
`sys.platform` checks, e.g.
`if sys.version_info >= (3, 15) and (sys.platform == "win32" or sys.platform == "linux")`.
* Y051 now also flags negative integer literals that are redundant in a union
with `int`, e.g. `int | Literal[-1]`.

### Other changes

Expand Down
11 changes: 8 additions & 3 deletions flake8_pyi/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1258,9 +1258,14 @@ def _check_for_Y051_violations(self, analysis: UnionAnalysis) -> None:
"""Search for redundant unions such as `str | Literal["foo"]`, etc."""
seen_builtins: set[type[object]] = set()
for literal in analysis.combined_literal_members:
if not isinstance(literal, ast.Constant):
continue
typ = type(literal.value)
match literal:
case ast.Constant(value):
typ = type(value)
# Negative integers such as `-1` are parsed as unary operations
case ast.UnaryOp(op=ast.USub(), operand=ast.Constant(value=int())):
typ = int
case _:
continue
typename = typ.__name__
if (
typ in {str, bytes, int, bool}
Expand Down
5 changes: 5 additions & 0 deletions tests/union_duplicates.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,11 @@ def three(arg: Literal["foo", 5] | builtins.int | Literal[9, "bar"]) -> None: ..
class Four:
var: builtins.bool | Literal[True] # Y051 "Literal[True]" is redundant in a union with "bool"

def five(arg: int | Literal[-1]) -> None: ... # Y051 "Literal[-1]" is redundant in a union with "int"
Six: TypeAlias = Union[Literal[-5], builtins.int] # Y051 "Literal[-5]" is redundant in a union with "int"
Seven: TypeAlias = int | Literal[-1, 5] # Y051 "Literal[-1]" is redundant in a union with "int"
Eight: TypeAlias = str | Literal[-1]

DupesHereSoNoY051: TypeAlias = int | int | Literal[42] # Y016 Duplicate union member "int"
NightmareAlias1 = int | float | Literal[4, b"bar"] | Literal["foo"] # Y026 Use typing.TypeAlias for type aliases, e.g. "NightmareAlias1: TypeAlias = int | float | Literal[4, b'bar'] | Literal['foo']" # Y030 Multiple Literal members in a union. Combine them into one, e.g. "Literal[4, b'bar', 'foo']". # Y051 "Literal[4]" is redundant in a union with "int"
nightmare_alias2: TypeAlias = int | float | Literal[True, 4] | Literal["foo"] # Y042 Type aliases should use the CamelCase naming convention # Y030 Multiple Literal members in a union. Combine them into one, e.g. "Literal[True, 4, 'foo']". # Y051 "Literal[4]" is redundant in a union with "int"
Expand Down
Loading