diff options
author | Inada Naoki <songofacandy@gmail.com> | 2023-07-29 06:37:23 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-07-29 06:37:23 (GMT) |
commit | 37551c9cef307ca3172c60b28c7de9db921808ad (patch) | |
tree | 4b149180dbb2102af8d7e7c07239df38f2f0b27e | |
parent | f2d07d3289947d10b065b2bb7670c8fb6b6582f2 (diff) | |
download | cpython-37551c9cef307ca3172c60b28c7de9db921808ad.zip cpython-37551c9cef307ca3172c60b28c7de9db921808ad.tar.gz cpython-37551c9cef307ca3172c60b28c7de9db921808ad.tar.bz2 |
gh-107369: optimize textwrap.indent() (#107374)
-rw-r--r-- | Doc/whatsnew/3.13.rst | 3 | ||||
-rw-r--r-- | Lib/textwrap.py | 20 | ||||
-rw-r--r-- | Misc/NEWS.d/next/Library/2023-07-28-14-56-35.gh-issue-107369.bvTq8F.rst | 2 |
3 files changed, 17 insertions, 8 deletions
diff --git a/Doc/whatsnew/3.13.rst b/Doc/whatsnew/3.13.rst index 7cad5d1..e20832a 100644 --- a/Doc/whatsnew/3.13.rst +++ b/Doc/whatsnew/3.13.rst @@ -150,7 +150,8 @@ typing Optimizations ============= - +* :func:`textwrap.indent` is now ~30% faster than before for large input. + (Contributed by Inada Naoki in :gh:`107369`.) Deprecated 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__": diff --git a/Misc/NEWS.d/next/Library/2023-07-28-14-56-35.gh-issue-107369.bvTq8F.rst b/Misc/NEWS.d/next/Library/2023-07-28-14-56-35.gh-issue-107369.bvTq8F.rst new file mode 100644 index 0000000..76aeab6 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-07-28-14-56-35.gh-issue-107369.bvTq8F.rst @@ -0,0 +1,2 @@ +Optimize :func:`textwrap.indent`. It is ~30% faster for large input. Patch +by Inada Naoki. |