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

Skip to content

gh-107369: Optimise textwrap.indent() 8000 #131923

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 31, 2025
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