gh-107369: optimize textwrap.indent() (#107374)

This commit is contained in:
Inada Naoki 2023-07-29 15:37:23 +09:00 committed by GitHub
parent f2d07d3289
commit 37551c9cef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 7 deletions

View File

@ -150,7 +150,8 @@ typing
Optimizations
=============
* :func:`textwrap.indent` is now ~30% faster than before for large input.
(Contributed by Inada Naoki in :gh:`107369`.)
Deprecated

View File

@ -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():
prefixed_lines = []
for line in text.splitlines(True):
yield (prefix + line if predicate(line) else line)
return ''.join(prefixed_lines())
if predicate(line):
prefixed_lines.append(prefix)
prefixed_lines.append(line)
return ''.join(prefixed_lines)
if __name__ == "__main__":

View File

@ -0,0 +1,2 @@
Optimize :func:`textwrap.indent`. It is ~30% faster for large input. Patch
by Inada Naoki.