Skip to content
Open
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ flake8-pyi uses Calendar Versioning (CalVer).

## Unreleased

### Changed Error Codes

* Y062: Duplicate values inside nested `Literal` slices are now detected.
For example, `Literal[1, Literal[2, 1]]`.

### Other changes

* Support Python 3.15.
Expand Down
2 changes: 1 addition & 1 deletion ERRORCODES.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ The following warnings are currently emitted by default:
| <a id="Y059" href="#Y059">Y059</a> | `Generic[]` should always be the last base class, if it is present in a class's bases tuple. At runtime, if `Generic[]` is not the final class in a the bases tuple, this [can cause the class creation to fail](https://github.com/python/cpython/issues/106102). In a stub file, however, this rule is enforced purely for stylistic consistency. | Style
| <a id="Y060" href="#Y060">Y060</a> | Redundant inheritance from `Generic[]`. For example, `class Foo(Iterable[_T], Generic[_T]): ...` can be written more simply as `class Foo(Iterable[_T]): ...`.<br><br>To avoid false-positive errors, and to avoid complexity in the implementation, this check is deliberately conservative: it only flags classes where all subscripted bases have identical code inside their subscript slices. | Style
| <a id="Y061" href="#Y061">Y061</a> | Do not use `None` inside a `Literal[]` slice. For example, use `Literal["foo"] \| None` instead of `Literal["foo", None]`. While both are legal according to [PEP 586](https://peps.python.org/pep-0586/), the former is preferred for stylistic consistency. Note that this warning is not emitted if Y062 is emitted for the same `Literal[]` slice. For example, `Literal[None, None, True, True]` only causes Y062 to be emitted. | Style
| <a id="Y062" href="#Y062">Y062</a> | `Literal[]` slices shouldn't contain duplicates, e.g. `Literal[True, True]` is not allowed. | Redundant code
| <a id="Y062" href="#Y062">Y062</a> | `Literal[]` slices shouldn't contain duplicates, e.g. `Literal[True, True]` is not allowed. Nested `Literal` slices are flattened first, so `Literal[1, Literal[2, 1]]` is checked as `Literal[1, 2, 1]`. | Redundant code

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's keep this text user-focused. Maybe just "Literal[] slices shouldn't contain duplicates, e.g. Literal[True, True] or Literal[True, Literal[True]] is not allowed."

| <a id="Y063" href="#Y063">Y063</a> | Use [PEP 570 syntax](https://peps.python.org/pep-0570/) (e.g. `def foo(x: int, /) -> None: ...`) to denote positional-only arguments, rather than [the older Python 3.7-compatible syntax described in PEP 484](https://peps.python.org/pep-0484/#positional-only-arguments) (`def foo(__x: int) -> None: ...`, etc.). | Style
| <a id="Y064" href="#Y064">Y064</a> | Use simpler syntax to define final literal types. For example, use `x: Final = 42` instead of `x: Final[Literal[42]]`. | Style
| <a id="Y065" href="#Y065">Y065</a> | Don't use bare `Incomplete` in argument and return annotations. Instead, leave them unannotated. Omitting an annotation entirely from a function will cause some type checkers to view the parameter or return type as "untyped"; this may result in stricter type-checking on code that makes use of the stubbed function. | Style
Expand Down
43 changes: 35 additions & 8 deletions flake8_pyi/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,21 @@ class TypingLiteralAnalysis(NamedTuple):
contains_only_none: bool


def _literal_leaf_members(member: ast.expr) -> list[ast.expr]:
"""Return values inside `member`, unwrapping nested Literals.

PEP 586 treats ``Literal[1, Literal[2, 1]]`` as the same values as
``Literal[1, 2, 1]``.
"""
if not (isinstance(member, ast.Subscript) and _is_Literal(member.value)):
return [member]
inner = member.slice.elts if isinstance(member.slice, ast.Tuple) else [member.slice]
leaves: list[ast.expr] = []
for item in inner:
leaves.extend(_literal_leaf_members(item))
return leaves


def _analyse_typing_Literal(node: ast.Subscript) -> TypingLiteralAnalysis:
"""Return a tuple providing analysis of a `typing.Literal` slice."""

Expand All @@ -556,7 +571,8 @@ def _analyse_typing_Literal(node: ast.Subscript) -> TypingLiteralAnalysis:
members = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]

for member in members:
members_by_dump[ast.dump(member)].append(member)
for leaf in _literal_leaf_members(member):
members_by_dump[ast.dump(leaf)].append(leaf)
if _is_None(member):
none_members.append(member)
else:
Expand Down Expand Up @@ -876,6 +892,7 @@ class PyiVisitor(ast.NodeVisitor):
in_function: NestingCounter
visiting_arg: NestingCounter
Y061_suppressed: NestingCounter
Y062_suppressed: NestingCounter

# This is only relevant for visiting classes
enclosing_class_ctx: EnclosingClassContext | None = None
Expand All @@ -894,6 +911,7 @@ def __init__(self, filename: str) -> None:
self.in_function = NestingCounter()
self.visiting_arg = NestingCounter()
self.Y061_suppressed = NestingCounter()
self.Y062_suppressed = NestingCounter()

def __repr__(self) -> str:
return f"{self.__class__.__name__}(filename={self.filename!r})"
Expand Down Expand Up @@ -1385,12 +1403,13 @@ def _visit_typing_Literal(self, node: ast.Subscript) -> None:
analysis = _analyse_typing_Literal(node)

Y062_encountered = False
for member_list in analysis.members_by_dump.values():
if len(member_list) > 1 and not _is_None(member_list[0]):
Y062_encountered = True
self.error(
member_list[1], errors.Y062.format(ast.unparse(member_list[1]))
)
if not self.Y062_suppressed.active:
for member_list in analysis.members_by_dump.values():
if len(member_list) > 1 and not _is_None(member_list[0]):
Y062_encountered = True
self.error(
member_list[1], errors.Y062.format(ast.unparse(member_list[1]))
)

if not Y062_encountered and not self.Y061_suppressed.active:
if analysis.contains_only_none:
Expand All @@ -1407,7 +1426,15 @@ def _visit_typing_Literal(self, node: ast.Subscript) -> None:
)

with self.long_strings_allowed.enabled():
self.visit(node.slice)
elements = (
node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
)
for element in elements:
if isinstance(element, ast.Subscript) and _is_Literal(element.value):
with self.Y062_suppressed.enabled():
self.visit(element)
else:
self.visit(element)

def _visit_slice_tuple(self, node: ast.Tuple, parent: str | None) -> None:
if parent == "Union":
Expand Down
13 changes: 12 additions & 1 deletion tests/literals.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Final, Literal
import typing
from typing import Annotated, Final, Literal

Literal[None] # Y061 None inside "Literal[]" expression. Replace with "None"
Literal[True, None] # Y061 None inside "Literal[]" expression. Replace with "Literal[True] | None"
Expand All @@ -22,6 +23,16 @@ Literal[1, None, "foo", None] # Y061 None inside "Literal[]" expression. Replac
# only emit Y062:
Literal[None, True, None, True] # Y062 Duplicate "Literal[]" member "True"

# Nested Literal values are the same values as a flat slice.
Literal[1, Literal[2, 1]] # Y062 Duplicate "Literal[]" member "1"
Literal[1, Literal[2, 3]]
Literal[Literal[1], Literal[1]] # Y062 Duplicate "Literal[]" member "1"
Literal[1, Literal[1, 1]] # Y062 Duplicate "Literal[]" member "1"
Literal["a", Literal["b", "a"]] # Y062 Duplicate "Literal[]" member "'a'"
Literal[0, typing.Literal[0]] # Y062 Duplicate "Literal[]" member "0"
Literal[Annotated[Literal[1, 1], "m"]] # Y062 Duplicate "Literal[]" member "1"
Literal[True, Literal[False, True], False] # Y062 Duplicate "Literal[]" member "True" # Y062 Duplicate "Literal[]" member "False"

x: Final[Literal[True]] # Y064 Use "x: Final = True" instead of "x: Final[Literal[True]]"
# If Y061 and Y064 both apply, only emit Y064
y: Final[Literal[None]] # Y064 Use "y: Final = None" instead of "y: Final[Literal[None]]"
Expand Down
Loading