Skip to content

Commit 7400aff

Browse files
committed
Add support for nested lambda expression in brackets
1 parent 86a51c5 commit 7400aff

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

pycodestyle.py

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -434,24 +434,37 @@ def extraneous_whitespace(logical_line):
434434
E203: if x == 4 : print x, y; x, y = y, x
435435
"""
436436

437-
def is_a_slice(line, colon_position):
438-
"""Check colon acts as a slice
437+
def is_a_slice(line, space_pos):
438+
"""Check if the colon after an extra space acts as a slice
439439
440440
Return True if the colon is directly contained within
441441
square brackets.
442442
"""
443+
# list of found '[({' as tuples "(char, position)"
443444
parentheses_brackets_braces = list()
444-
for i in range(colon_position):
445+
for i in range(space_pos):
445446
c = line[i]
446447
if c in '[({':
447-
parentheses_brackets_braces += c
448+
# add it to the stack
449+
parentheses_brackets_braces.append((c, i))
448450
elif c in '])}':
449-
last_opened = parentheses_brackets_braces.pop()
451+
# unstack last item and check consistency
452+
last_opened = parentheses_brackets_braces.pop()[0]
450453
expected_close = {'{': '}', '(': ')', '[': ']'}[last_opened]
451454
if c != expected_close: # invalid Python code
452455
return False
453-
return (len(parentheses_brackets_braces) > 0 and
454-
parentheses_brackets_braces.pop() == '[')
456+
is_within_brackets = (len(parentheses_brackets_braces) > 0 and
457+
parentheses_brackets_braces[-1][0] == '[')
458+
459+
is_lambda_expr = False
460+
if is_within_brackets:
461+
# check for a lambda expression nested in brackets
462+
if space_pos > 6:
463+
last_opened = parentheses_brackets_braces[-1]
464+
between_bracket_colon = line[last_opened[1] + 1 : space_pos]
465+
is_lambda_expr = 'lambda' in between_bracket_colon
466+
467+
return (is_within_brackets and not is_lambda_expr)
455468

456469
line = logical_line
457470
for match in EXTRANEOUS_WHITESPACE_REGEX.finditer(line):

testsuite/E20.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,10 @@
4848
x, y = y , x
4949
#: E203:1:37
5050
foo[idxs[2 : 6] : spam(ham[1], {eggs : a[2 : 4]})]
51+
#: E203:1:8
52+
[lambda : foo]
53+
#: E203:1:13
54+
ham[lambda x : foo]
5155
#: Okay
5256
if x == 4:
5357
print x, y
@@ -58,4 +62,6 @@
5862
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
5963
ham[lower + offset : upper + offset]
6064
foo[idxs[2 : 6] : spam(ham[1], {eggs: a[2 : 4]})]
65+
[lambda: foo]
66+
ham[lambda x: foo]
6167
#:

0 commit comments

Comments
 (0)