Skip to content

Commit 91235d0

Browse files
AA-Turnerpicnixz
authored andcommitted
pythongh-107369: Optimise textwrap.indent() (python#131923)
Co-authored-by: Bénédikt Tran <[email protected]>
1 parent c014325 commit 91235d0

File tree

2 files changed

+15
-12
lines changed

2 files changed

+15
-12
lines changed

Lib/textwrap.py

+13-12
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

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)