Skip to content

Commit a5bbfbb

Browse files
authored
Simplify Y051 logic (#409)
This comes out to about the same number of lines, but I find it much more readable. It uses `set`s rather than `defaultdict`s, and does the work in a single loop instead of two consecutive loops.
1 parent dc1eb0c commit a5bbfbb

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

pyi.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -1260,23 +1260,23 @@ def _check_union_members(
12601260

12611261
def _check_for_Y051_violations(self, analysis: UnionAnalysis) -> None:
12621262
"""Search for redundant unions such as `str | Literal["foo"]`, etc."""
1263-
literal_classes_present: defaultdict[str, list[_SliceContents]]
1264-
literal_classes_present = defaultdict(list)
1263+
seen_builtins: set[type] = set()
12651264
for literal in analysis.combined_literal_members:
1266-
interesting_builtins = {str, bytes, int, bool}
1265+
if not isinstance(literal, ast.Constant):
1266+
continue
1267+
typ = type(literal.value)
1268+
typename = typ.__name__
12671269
if (
1268-
isinstance(literal, ast.Constant)
1269-
and type(literal.value) in interesting_builtins
1270+
typ in {str, bytes, int, bool}
1271+
and typename in analysis.builtins_classes_in_union
1272+
and typ not in seen_builtins
12701273
):
1271-
literal_classes_present[type(literal.value).__name__].append(literal)
1272-
for cls, literals in literal_classes_present.items():
1273-
if cls in analysis.builtins_classes_in_union:
1274-
first_literal_present = literals[0]
1274+
seen_builtins.add(typ)
12751275
self.error(
1276-
first_literal_present,
1276+
literal,
12771277
Y051.format(
1278-
literal_subtype=f"Literal[{unparse(first_literal_present)}]",
1279-
builtin_supertype=cls,
1278+
literal_subtype=f"Literal[{unparse(literal)}]",
1279+
builtin_supertype=typename,
12801280
),
12811281
)
12821282

0 commit comments

Comments
 (0)