Skip to content

Commit 36389f0

Browse files
committed
E711 / E712 checks test for None != arg and False == arg
(Fixes #307)
1 parent 4c5bf00 commit 36389f0

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

pep8.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,10 @@
101101
DOCSTRING_REGEX = re.compile(r'u?r?["\']')
102102
EXTRANEOUS_WHITESPACE_REGEX = re.compile(r'[[({] | []}),;:]')
103103
WHITESPACE_AFTER_COMMA_REGEX = re.compile(r'[,;:]\s*(?: |\t)')
104-
COMPARE_SINGLETON_REGEX = re.compile(r'([=!]=)\s*(None|False|True)')
104+
COMPARE_SINGLETON_REGEX = re.compile(r'(?P<op>[=!]=)\s*'
105+
r'(?P<singleton>None|False|True)')
106+
COMPARE_SINGLETON_REVERSE_REGEX = re.compile(r'(?P<singleton>None|False|True)'
107+
r'\s*(?P<op>[=!]=)')
105108
COMPARE_NEGATIVE_REGEX = re.compile(r'\b(not)\s+[^[({ ]+\s+(in|is)\s')
106109
COMPARE_TYPE_REGEX = re.compile(r'(?:[=!]=|is(?:\s+not)?)\s*type(?:s.\w+Type'
107110
r'|\s*\(\s*([^)]*[^ )])\s*\))')
@@ -930,17 +933,22 @@ def comparison_to_singleton(logical_line, noqa):
930933
931934
Okay: if arg is not None:
932935
E711: if arg != None:
936+
E711: if None == arg:
933937
E712: if arg == True:
938+
E712: if False == arg:
934939
935940
Also, beware of writing if x when you really mean if x is not None --
936941
e.g. when testing whether a variable or argument that defaults to None was
937942
set to some other value. The other value might have a type (such as a
938943
container) that could be false in a boolean context!
939944
"""
940-
match = not noqa and COMPARE_SINGLETON_REGEX.search(logical_line)
945+
946+
match = not noqa and (COMPARE_SINGLETON_REGEX.search(logical_line) or
947+
COMPARE_SINGLETON_REVERSE_REGEX.search(logical_line))
941948
if match:
942-
same = (match.group(1) == '==')
943-
singleton = match.group(2)
949+
singleton = match.group('singleton')
950+
same = match.group('op')
951+
944952
msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton)
945953
if singleton in ('None',):
946954
code = 'E711'

testsuite/E71.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,29 @@
11
#: E711
22
if res == None:
33
pass
4+
#: E711
5+
if res != None:
6+
pass
7+
#: E711
8+
if None == res:
9+
pass
10+
#: E711
11+
if None != res:
12+
pass
13+
14+
#
415
#: E712
516
if res == True:
617
pass
718
#: E712
819
if res != False:
920
pass
21+
#: E712
22+
if True != res:
23+
pass
24+
#: E712
25+
if False == res:
26+
pass
1027

1128
#
1229
#: E713

0 commit comments

Comments
 (0)