Skip to content

Commit 394a061

Browse files
committed
Identify binary operators used as unary operators
Previously we handled the case where binary operators were being used as unary operators except in the case where they followed another binary operator, e.g., foo = (1 + -10 * 2 / -5) This change updates the check for W503 to track the previous non-whitespace token type and token text to check if it is in fact also a binary operator (because you should never have two binary operators in a row). This does not handle invalid syntax, e.g., foo = (bar / /baz) But the false-positive generated for other cases was more harmful than not catching what will instead be caught by the interpreter. Closes gh-484
1 parent 4fb305e commit 394a061

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

pep8.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1018,6 +1018,8 @@ def break_around_binary_operator(logical_line, tokens):
10181018
Okay: foo(x,\n -y)
10191019
Okay: foo(x, # comment\n -y)
10201020
Okay: var = (1 &\n ~2)
1021+
Okay: var = (1 /\n -2)
1022+
Okay: var = (1 +\n -1 +\n -2)
10211023
"""
10221024
def is_binary_operator(token_type, text):
10231025
# The % character is strictly speaking a binary operator, but the
@@ -1028,17 +1030,24 @@ def is_binary_operator(token_type, text):
10281030

10291031
line_break = False
10301032
unary_context = True
1033+
# Previous non-newline token types and text
1034+
previous_token_type = None
1035+
previous_text = None
10311036
for token_type, text, start, end, line in tokens:
10321037
if token_type == tokenize.COMMENT:
10331038
continue
10341039
if ('\n' in text or '\r' in text) and token_type != tokenize.STRING:
10351040
line_break = True
10361041
else:
10371042
if (is_binary_operator(token_type, text) and line_break and
1038-
not unary_context):
1043+
not unary_context and
1044+
not is_binary_operator(previous_token_type,
1045+
previous_text)):
10391046
yield start, "W503 line break before binary operator"
10401047
unary_context = text in '([{,;'
10411048
line_break = False
1049+
previous_token_type = token_type
1050+
previous_text = text
10421051

10431052

10441053
def comparison_to_singleton(logical_line, noqa):

0 commit comments

Comments
 (0)