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

Optimize textwrap.indent() #107369

Closed
Closed
Labels
performancePerformance or resource usagestdlibPython modules in the Lib dir
@methane

Description

@methane

Current code:

defindent(text,prefix,predicate=None):"""Adds 'prefix' to the beginning of selected lines in 'text'.    If 'predicate' is provided, 'prefix' will only be added to the lines    where 'predicate(line)' is True. If 'predicate' is not provided,    it will default to adding 'prefix' to all non-empty lines that do not    consist solely of whitespace characters.    """ifpredicateisNone:defpredicate(line):returnline.strip()defprefixed_lines():forlineintext.splitlines(True):yield (prefix+lineifpredicate(line)elseline)return''.join(prefixed_lines())
  • predicate = str.strip is faster thandef predicate(line)
  • ''.join(x) converts input iterable to sequence. Using generator just makes overhead.
  • creating temporaryprefix + line is avoidable.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usagestdlibPython modules in the Lib dir

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp