Skip to content

Commit

Permalink
gh-107369: optimize textwrap.indent() (#107374)
Browse files Browse the repository at this point in the history
  • Loading branch information
methane authored Jul 29, 2023
1 parent f2d07d3 commit 37551c9
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 8 deletions.
3 changes: 2 additions & 1 deletion Doc/whatsnew/3.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 13 additions & 7 deletions Lib/textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if predicate(line) else line)
return ''.join(prefixed_lines())
# 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()

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__":
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Optimize :func:`textwrap.indent`. It is ~30% faster for large input. Patch
by Inada Naoki.

0 comments on commit 37551c9

Please sign in to comment.