mirror of
https://github.com/python/cpython.git
synced 2025-08-04 08:59:19 +00:00
gh-107369: optimize textwrap.indent() (#107374)
This commit is contained in:
parent
f2d07d3289
commit
37551c9cef
3 changed files with 16 additions and 7 deletions
|
@ -476,13 +476,19 @@ def indent(text, prefix, predicate=None):
|
|||
consist solely of whitespace characters.
|
||||
"""
|
||||
if predicate is None:
|
||||
def predicate(line):
|
||||
return line.strip()
|
||||
# str.splitlines(True) doesn't produce empty string.
|
||||
# ''.splitlines(True) => []
|
||||
# 'foo\n'.splitlines(True) => ['foo\n']
|
||||
# So we can use just `not s.isspace()` here.
|
||||
predicate = lambda s: not s.isspace()
|
||||
|
||||
def prefixed_lines():
|
||||
for line in text.splitlines(True):
|
||||
yield (prefix + line if predicate(line) else line)
|
||||
return ''.join(prefixed_lines())
|
||||
prefixed_lines = []
|
||||
for line in text.splitlines(True):
|
||||
if predicate(line):
|
||||
prefixed_lines.append(prefix)
|
||||
prefixed_lines.append(line)
|
||||
|
||||
return ''.join(prefixed_lines)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue