8000 gh-107369: Optimise ``textwrap.indent()`` (#131923) · python/cpython@51e0f2b · GitHub
[go: up one dir, main page]

Skip to content

Commit 51e0f2b

Browse files
AA-Turnerpicnixz
andauthored
gh-107369: Optimise textwrap.indent() (#131923)
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
1 parent 511d344 commit 51e0f2b

File tree

2 files changed

+15
-12
lines changed

2 files changed

+15
-12
lines changed

Lib/textwrap.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -451,19 +451,20 @@ def indent(text, prefix, predicate=None):
451451
it will default to adding 'prefix' to all non-empty lines that do not
452452
consist solely of whitespace characters.
453453
"""
454-
if predicate is None:
455-
# str.splitlines(True) doesn't produce empty string.
456-
# ''.splitlines(True) => []
457-
# 'foo\n'.splitlines(True) => ['foo\n']
458-
# So we can use just `not s.isspace()` here.
459-
predicate = lambda s: not s.isspace()
460-
461454
prefixed_lines = []
462-
for line in text.splitlines(True):
463-
if predicate(line):
464-
prefixed_lines.append(prefix)
465-
prefixed_lines.append(line)
466-
455+
if predicate is None:
456+
# str.splitlines(keepends=True) doesn't produce the empty string,
457+
# so we need to use `str.isspace()` rather than a truth test.
458+
# Inlining the predicate leads to a ~30% performance improvement.
459+
for line in text.splitlines(True):
460+
if not line.isspace():
461+
prefixed_lines.append(prefix)
462+
prefixed_lines.append(line)
463+
else:
464+
for line in text.splitlines(True):
465+
if predicate(line):
466+
prefixed_lines.append(prefix)
467+
prefixed_lines.append(line)
467468
return ''.join(prefixed_lines)
468469

469470

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improved performance of :func:`textwrap.dedent` by an average of ~1.3x.
2+
Patch by Adam Turner.

0 commit comments

Comments
 (0)
0