Skip to content

Commit d69f819

Browse files
Treat generator and comprehension more gracefully
1 parent c0e0be5 commit d69f819

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

pylint/checkers/refactoring/len_checker.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from typing import List, Optional
66

77
import astroid
8-
from astroid import Uninferable
8+
from astroid import DictComp, GeneratorExp, ListComp, SetComp, Uninferable
99

1010
from pylint import checkers, interfaces
1111
from pylint.checkers import utils
@@ -89,13 +89,13 @@ def visit_call(self, node):
8989
# we're finally out of any nested boolean operations so check if
9090
# this len() call is part of a test condition
9191
if _is_test_condition(node, parent):
92-
try:
93-
instance = next(node.args[0].infer())
94-
except astroid.InferenceError:
95-
# Inference error happens for list comprehension, dict comprehension,
96-
# set comprehension and generators (like range)
92+
len_arg = node.args[0]
93+
generator_or_comprehension = (ListComp, SetComp, DictComp, GeneratorExp)
94+
if isinstance(len_arg, generator_or_comprehension):
95+
# The node is a generator or comprehension as in len([x for x in ...])
9796
self.add_message("len-as-condition", node=node)
9897
return
98+
instance = next(len_arg.infer())
9999
mother_classes = self.base_classes_of_node(instance)
100100
affected_by_pep8 = any(
101101
t in mother_classes for t in ["str", "tuple", "list", "set"]

0 commit comments

Comments
 (0)