diff --git a/CHANGELOG.md b/CHANGELOG.md
index b3af780..40f87cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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.
diff --git a/ERRORCODES.md b/ERRORCODES.md
index 0c8f984..2a6e694 100644
--- a/ERRORCODES.md
+++ b/ERRORCODES.md
@@ -75,7 +75,7 @@ The following warnings are currently emitted by default:
| Y059 | `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
| Y060 | Redundant inheritance from `Generic[]`. For example, `class Foo(Iterable[_T], Generic[_T]): ...` can be written more simply as `class Foo(Iterable[_T]): ...`.
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
| Y061 | 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
-| Y062 | `Literal[]` slices shouldn't contain duplicates, e.g. `Literal[True, True]` is not allowed. | Redundant code
+| Y062 | `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
| Y063 | 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
| Y064 | Use simpler syntax to define final literal types. For example, use `x: Final = 42` instead of `x: Final[Literal[42]]`. | Style
| Y065 | 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
diff --git a/flake8_pyi/visitor.py b/flake8_pyi/visitor.py
index 4bb8d53..1bde69d 100644
--- a/flake8_pyi/visitor.py
+++ b/flake8_pyi/visitor.py
@@ -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."""
@@ -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:
@@ -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
@@ -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})"
@@ -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:
@@ -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":
diff --git a/tests/literals.pyi b/tests/literals.pyi
index ea9f904..213a3c3 100644
--- a/tests/literals.pyi
+++ b/tests/literals.pyi
@@ -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"
@@ -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]]"