Skip to content

Commit 37551c9

Browse files
authored
gh-107369: optimize textwrap.indent() (#107374)
1 parent f2d07d3 commit 37551c9

File tree

3 files changed

+17
-8
lines changed

3 files changed

+17
-8
lines changed

Doc/whatsnew/3.13.rst

+2-1
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,8 @@ typing
150150
Optimizations
151151
=============
152152

153-
153+
* :func:`textwrap.indent` is now ~30% faster than before for large input.
154+
(Contributed by Inada Naoki in :gh:`107369`.)
154155

155156

156157
Deprecated

Lib/textwrap.py

+13-7
Original file line numberDiff line numberDiff line change
@@ -476,13 +476,19 @@ def indent(text, prefix, predicate=None):
476476
consist solely of whitespace characters.
477477
"""
478478
if predicate is None:
479-
def predicate(line):
480-
return line.strip()
481-
482-
def prefixed_lines():
483-
for line in text.splitlines(True):
484-
yield (prefix + line if predicate(line) else line)
485-
return ''.join(prefixed_lines())
479+
# str.splitlines(True) doesn't produce empty string.
480+
# ''.splitlines(True) => []
481+
# 'foo\n'.splitlines(True) => ['foo\n']
482+
# So we can use just `not s.isspace()` here.
483+
predicate = lambda s: not s.isspace()
484+
485+
prefixed_lines = []
486+
for line in text.splitlines(True):
487+
if predicate(line):
488+
prefixed_lines.append(prefix)
489+
prefixed_lines.append(line)
490+
491+
return ''.join(prefixed_lines)
486492

487493

488494
if __name__ == "__main__":
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Optimize :func:`textwrap.indent`. It is ~30% faster for large input. Patch
2+
by Inada Naoki.

0 commit comments

Comments
 (0)