Skip to content

Commit 016cbe4

Browse files
committed
Make maybe_check_physical() easier to understand (based on code review)
- reorder so common case comes first - rewrite docstring - expand/clarify comments
1 parent 8b734d9 commit 016cbe4

1 file changed

Lines changed: 21 additions & 8 deletions

File tree

pep8.py

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1356,13 +1356,28 @@ def generate_tokens(self):
13561356

13571357
def maybe_check_physical(self, token):
13581358
"""
1359-
If token calls for it, check current physical line(s).
1359+
If appropriate (based on token), check current physical line(s).
13601360
"""
1361-
if token[0] == tokenize.STRING and token[1].count('\n'):
1362-
# Check the physical lines that make up a multiline string. Do
1363-
# *not* check the last line: its newline is outside of the
1364-
# multiline string, so we consider it a regular physical line
1365-
# (it will be checked when we see the newline token).
1361+
# This is called after every token, but we only want to take action
1362+
# after a token that ends a line.
1363+
if token[0] in (tokenize.NEWLINE, tokenize.NL):
1364+
# Obviously, a newline token ends a single physical line.
1365+
self.check_physical(token[4])
1366+
elif token[0] == tokenize.STRING and token[1].count('\n'):
1367+
# Less obviously, a string that contains newlines is a
1368+
# multiline string, either triple-quoted or with internal
1369+
# newlines backslash-escaped. Check every physical line in the
1370+
# string *except* for the last one: its newline is outside of
1371+
# the multiline string, so we consider it a regular physical
1372+
# line, and will check it like any other physical line.
1373+
#
1374+
# Subtleties:
1375+
# - we don't *completely* ignore the last line; if it contains
1376+
# the magical "# noqa" comment, we disable all physical
1377+
# checks for the entire multiline string
1378+
# - have to wind self.line_number back because initially it
1379+
# points to the last line of the string, and we want
1380+
# check_physical() to give accurate feedback
13661381
if noqa(token[4]):
13671382
return
13681383
self.multiline = True
@@ -1371,8 +1386,6 @@ def maybe_check_physical(self, token):
13711386
self.check_physical(line + '\n')
13721387
self.line_number += 1
13731388
self.multiline = False
1374-
elif token[0] in (tokenize.NEWLINE, tokenize.NL):
1375-
self.check_physical(token[4])
13761389

13771390
def check_all(self, expected=None, line_offset=0):
13781391
"""

0 commit comments

Comments
 (0)