Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Doc/whatsnew/3.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,8 @@ typing
Optimizations
=============


* :func:`textwrap.indent` is now ~25% 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 ~25% faster for large input. Patch
by Inada Naoki.