2
2
3
3
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
4
4
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
5
- from typing import Optional
6
-
7
5
import astroid
8
6
9
7
from pylint import checkers , interfaces
10
8
from pylint .checkers import utils
11
9
12
10
13
- def _is_call_of_name (node : astroid .node_classes .NodeNG , name : str ) -> bool :
14
- """Checks if node is a function call with the given name"""
15
- return (
16
- isinstance (node , astroid .Call )
17
- and isinstance (node .func , astroid .Name )
18
- and node .func .name == name
19
- )
20
-
21
-
22
- def _is_test_condition (
23
- node : astroid .node_classes .NodeNG ,
24
- parent : Optional [astroid .node_classes .NodeNG ] = None ,
25
- ) -> bool :
26
- """Returns true if the given node is being tested for truthiness"""
27
- parent = parent or node .parent
28
- if isinstance (parent , (astroid .While , astroid .If , astroid .IfExp , astroid .Assert )):
29
- return node is parent .test or parent .test .parent_of (node )
30
- if isinstance (parent , astroid .Comprehension ):
31
- return node in parent .ifs
32
- return _is_call_of_name (parent , "bool" ) and parent .parent_of (node )
33
-
34
-
35
11
class LenChecker (checkers .BaseChecker ):
36
12
"""Checks for incorrect usage of len() inside conditions.
37
13
Pep8 states:
@@ -79,7 +55,7 @@ def visit_call(self, node):
79
55
# a len(S) call is used inside a test condition
80
56
# could be if, while, assert or if expression statement
81
57
# e.g. `if len(S):`
82
- if _is_call_of_name (node , "len" ):
58
+ if utils . is_call_of_name (node , "len" ):
83
59
# the len() call could also be nested together with other
84
60
# boolean operations, e.g. `if z or len(x):`
85
61
parent = node .parent
@@ -88,7 +64,7 @@ def visit_call(self, node):
88
64
89
65
# we're finally out of any nested boolean operations so check if
90
66
# this len() call is part of a test condition
91
- if _is_test_condition (node , parent ):
67
+ if utils . is_test_condition (node , parent ):
92
68
self .add_message ("len-as-condition" , node = node )
93
69
94
70
@utils .check_messages ("len-as-condition" )
@@ -99,6 +75,6 @@ def visit_unaryop(self, node):
99
75
if (
100
76
isinstance (node , astroid .UnaryOp )
101
77
and node .op == "not"
102
- and _is_call_of_name (node .operand , "len" )
78
+ and utils . is_call_of_name (node .operand , "len" )
103
79
):
104
80
self .add_message ("len-as-condition" , node = node )
0 commit comments