From 3439066c1943794beacb05011fd661fa35833bed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?B=C3=A9n=C3=A9dikt=20Tran?= <10796600+picnixz@users.noreply.github.com> Date: Sat, 29 Jul 2023 16:09:52 +0200 Subject: [PATCH] optimize textwrap.indent() (#107424) --- Lib/textwrap.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/Lib/textwrap.py b/Lib/textwrap.py index 7ca393d1c371aa..6c1a2112931659 100644 --- a/Lib/textwrap.py +++ b/Lib/textwrap.py @@ -475,18 +475,22 @@ 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. """ + prefixed_lines = [] + 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) + # So we can use just `not line.isspace()` here. + 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)