Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

gh-107369: optimize textwrap.indent()#107374

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
methane merged 8 commits intopython:mainfrommethane:opt-textwrap-indent
Jul 29, 2023
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletionDoc/whatsnew/3.13.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -144,7 +144,8 @@ typing
Optimizations
=============


* :func:`textwrap.indent` is now ~30% faster than before for large input.
(Contributed by Inada Naoki in :gh:`107369`.)


Deprecated
Expand Down
20 changes: 13 additions & 7 deletionsLib/textwrap.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -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__":
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
Optimize :func:`textwrap.indent`. It is ~30% faster for large input. Patch
by Inada Naoki.

[8]ページ先頭

©2009-2025 Movatter.jp