Skip to content

Commit 523a2fb

Browse files
authored
Merge pull request #445 from hhatto/fix-w503
Fix w503
2 parents 3b3d5ff + 0fd9c35 commit 523a2fb

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

autopep8.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1217,16 +1217,24 @@ def fix_w503(self, result):
12171217
return
12181218
# find comment
12191219
comment_index = 0
1220+
found_not_comment_only_line = False
12201221
comment_only_linenum = 0
12211222
for i in range(5):
12221223
# NOTE: try to parse code in 5 times
12231224
if (line_index - i) < 0:
12241225
break
12251226
from_index = line_index - i - 1
1227+
if from_index < 0 or len(self.source) <= from_index:
1228+
break
12261229
to_index = line_index + 1
1227-
if self.source[from_index].lstrip()[0] == '#':
1230+
strip_line = self.source[from_index].lstrip()
1231+
if (
1232+
not found_not_comment_only_line and
1233+
strip_line and strip_line[0] == '#'
1234+
):
12281235
comment_only_linenum += 1
12291236
continue
1237+
found_not_comment_only_line = True
12301238
try:
12311239
ts = generate_tokens("".join(self.source[from_index:to_index]))
12321240
except (SyntaxError, tokenize.TokenError):

test/test_autopep8.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4352,6 +4352,26 @@ def test_w503_with_line_comment(self):
43524352
with autopep8_context(line, options=['--select=W503', '--ignore=E']) as result:
43534353
self.assertEqual(fixed, result)
43544354

4355+
def test_w503_with_empty_line(self):
4356+
line = """\
4357+
4358+
# this is comment
4359+
a = 2
4360+
b = (1 +
4361+
2 +
4362+
3) / 2.0
4363+
"""
4364+
fixed = """\
4365+
4366+
# this is comment
4367+
a = 2
4368+
b = (1 +
4369+
2 +
4370+
3) / 2.0
4371+
"""
4372+
with autopep8_context(line, options=['--ignore=E721']) as result:
4373+
self.assertEqual(fixed, result)
4374+
43554375
def test_w503_with_line_comments(self):
43564376
line = '(width == 0\n # this is comment\n # comment2\n + height == 0)\n'
43574377
fixed = '(width == 0 +\n # this is comment\n # comment2\n height == 0)\n'

0 commit comments

Comments
 (0)