summaryrefslogtreecommitdiffstats
path: root/Lib/textwrap.py
diff options
context:
space:
mode:
authorInada Naoki <songofacandy@gmail.com>2023-07-29 06:37:23 (GMT)
committerGitHub <noreply@github.com>2023-07-29 06:37:23 (GMT)
commit37551c9cef307ca3172c60b28c7de9db921808ad (patch)
tree4b149180dbb2102af8d7e7c07239df38f2f0b27e /Lib/textwrap.py
parentf2d07d3289947d10b065b2bb7670c8fb6b6582f2 (diff)
downloadcpython-37551c9cef307ca3172c60b28c7de9db921808ad.zip
cpython-37551c9cef307ca3172c60b28c7de9db921808ad.tar.gz
cpython-37551c9cef307ca3172c60b28c7de9db921808ad.tar.bz2
gh-107369: optimize textwrap.indent() (#107374)
Diffstat (limited to 'Lib/textwrap.py')
-rw-r--r--Lib/textwrap.py20
1 files changed, 13 insertions, 7 deletions
diff --git a/Lib/textwrap.py b/Lib/textwrap.py
index 98bedd2..7ca393d 100644
--- a/Lib/textwrap.py
+++ b/Lib/textwrap.py
@@ -476,13 +476,19 @@ def indent(text, prefix, predicate=None):
consist solely of whitespace characters.
"""
if predicate is None:
- def predicate(line):
- return line.strip()
-
- def prefixed_lines():
- for line in text.splitlines(True):
- yield (prefix + line if predicate(line) else line)
- return ''.join(prefixed_lines())
+ # 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)
+
+ return ''.join(prefixed_lines)
if __name__ == "__main__":