@@ -413,6 +413,12 @@ def extraneous_whitespace(logical_line):
413
413
- Immediately inside parentheses, brackets or braces.
414
414
- Immediately before a comma, semicolon, or colon.
415
415
416
+ Exceptions:
417
+ - When the colon acts as a slice, the rule of binary operators
418
+ applies and we should have the same amount of space on either side
419
+ - When the colon acts as a slice but a parameter is omitted, then
420
+ the space is omitted
421
+
416
422
Okay: spam(ham[1], {eggs: 2})
417
423
E201: spam( ham[1], {eggs: 2})
418
424
E201: spam(ham[ 1], {eggs: 2})
@@ -421,10 +427,32 @@ def extraneous_whitespace(logical_line):
421
427
E202: spam(ham[1 ], {eggs: 2})
422
428
E202: spam(ham[1], {eggs: 2 })
423
429
430
+ Okay: ham[8 : 2]
431
+ Okay: ham[: 2]
424
432
E203: if x == 4: print x, y; x, y = y , x
425
433
E203: if x == 4: print x, y ; x, y = y, x
426
434
E203: if x == 4 : print x, y; x, y = y, x
427
435
"""
436
+
437
+ def is_a_slice (line , colon_position ):
438
+ """Check colon acts as a slice
439
+
440
+ Return True if the colon is directly contained within
441
+ square brackets.
442
+ """
443
+ parentheses_brackets_braces = list ()
444
+ for i in range (colon_position ):
445
+ c = line [i ]
446
+ if c in '[({' :
447
+ parentheses_brackets_braces += c
448
+ elif c in '])}' :
449
+ last_opened = parentheses_brackets_braces .pop ()
450
+ expected_close = {'{' : '}' , '(' : ')' , '[' : ']' }[last_opened ]
451
+ if c != expected_close : # invalid Python code
452
+ return False
453
+ return (len (parentheses_brackets_braces ) > 0 and
454
+ parentheses_brackets_braces .pop () == '[' )
455
+
428
456
line = logical_line
429
457
for match in EXTRANEOUS_WHITESPACE_REGEX .finditer (line ):
430
458
text = match .group ()
@@ -433,7 +461,8 @@ def extraneous_whitespace(logical_line):
433
461
if text == char + ' ' :
434
462
# assert char in '([{'
435
463
yield found + 1 , "E201 whitespace after '%s'" % char
436
- elif line [found - 1 ] != ',' :
464
+ elif (line [found - 1 ] != ',' and
465
+ not (char == ':' and is_a_slice (line , found ))):
437
466
code = ('E202' if char in '}])' else 'E203' ) # if char in ',;:'
438
467
yield found , "%s whitespace before '%s'" % (code , char )
439
468
0 commit comments