mirror of https://github.com/python/cpython
gh-107369: optimize textwrap.indent() (#107374)
This commit is contained in:
parent
f2d07d3289
commit
37551c9cef
|
@ -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
|
||||
|
|
|
@ -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__":
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
Optimize :func:`textwrap.indent`. It is ~30% faster for large input. Patch
|
||||
by Inada Naoki.
|
Loading…
Reference in New Issue