8000 gh-107369: Optimise ``textwrap.indent()`` by AA-Turner · Pull Request #131923 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
25 changes: 13 additions & 12 deletions Lib/textwrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,19 +451,20 @@ def indent(text, prefix, predicate=None):
it will default to adding 'prefix' to all non-empty lines that do not
consist solely of whitespace characters.
"""
if predicate is None:
# 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)

if predicate is None:
# str.splitlines(keepends=True) doesn't produce the empty string,
# so we need to use `str.isspace()` rather than a truth test.
# Inlining the predicate leads to a ~30% performance improvement.
for line in text.splitlines(True):
if not line.isspace():
prefixed_lines.append(prefix)
prefixed_lines.append(line)
else:
for line in text.splitlines(True):
if predicate(line):
prefixed_lines.append(prefix)
prefixed_lines.append(line)
return ''.join(prefixed_lines)


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improved performance of :func:`textwrap.dedent` by an average of ~1.3x.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/dedent/indent/

Patch by Adam Turner.
Loading
0