Skip to content

Commit

Permalink
Improve check for logical continuation in comprehension.
Browse files Browse the repository at this point in the history
Excludes
```
sorted(obj for obj in iterator
       if some_long_cond()
          and some_other_cond())
```
from E127.

It is true that this also lets through some "bad" indents e.g.
```
(1 if a and 2 else
      b)
```
but at the tokenization level it is quite difficult to distinguish
between the "if" in `a for b in c if d` and the "if" in `a if b else c`,
which play quite different roles.
  • Loading branch information
anntzer committed Mar 1, 2020
1 parent 68cc24f commit ace7b01
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 5 additions & 1 deletion pycodestyle.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ def continued_indentation(logical_line, tokens, indent_level, hang_closing,
if verbose >= 3:
print(">>> " + tokens[0][4].rstrip())

for token_type, text, start, end, line in tokens:
for idx, (token_type, text, start, end, line) in enumerate(tokens):

newline = row < start[0] - first_row
if newline:
Expand Down Expand Up @@ -695,6 +695,10 @@ def continued_indentation(logical_line, tokens, indent_level, hang_closing,
elif (token_type in (tokenize.STRING, tokenize.COMMENT) or
text in ('u', 'ur', 'b', 'br')):
indent_chances[start[1]] = str
# hanging indents in comprehensions
elif (token_type == tokenize.NAME and text == "if" and
tokens[idx + 1][0] != tokenize.LPAR): # [0] == .type
indent_chances[tokens[idx + 1][2][1]] = True # [2] == .start
# special case for the "if" statement because len("if (") == 4
elif not indent_chances and not row and not depth and text == 'if':
indent_chances[end[1] + 1] = True
Expand Down
4 changes: 4 additions & 0 deletions testsuite/E12not.py
Original file line number Diff line number Diff line change
Expand Up @@ -639,3 +639,7 @@ def other_example():
# more stuff
)
)
#: W503
sorted(obj for obj in []
if True
and False)

0 comments on commit ace7b01

Please sign in to comment.