Skip to content

Optimize textwrap.indent() #107369

Closed
Closed

Description

@methane

Current code:

def indent(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.
    """
    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())
  • predicate = str.strip is faster than def predicate(line)
  • ''.join(x) converts input iterable to sequence. Using generator just makes overhead.
  • creating temporary prefix + line is avoidable.

Linked PRs

Activity

  1. added
    type-featureA feature request or enhancement
    performancePerformance or resource usage
    stdlibStandard Library Python modules in the Lib/ directory
    and removed
    type-featureA feature request or enhancement
    on Jul 28, 2023
  2. methane commented on Jul 28, 2023

    @methane
    MemberAuthor
    import timeit
    import textwrap
    
    with open("Objects/unicodeobject.c") as f:
        text = f.read()
    
    it = timeit.Timer(lambda: textwrap.indent(text, " "*4))
    result = it.repeat(number=1000)
    result.sort()
    print(f"indent {len(text.splitlines())} lines.")
    print(f"{result[0]:.4f}msec")

    before: 2.8msec
    after: 2.1msec (-25%)

  3. added a commit that references this issue on Jul 29, 2023
  4. added a commit that references this issue on Mar 31, 2025
  5. hroncok commented on Apr 14, 2025

    @hroncok
  6. methane commented on Apr 15, 2025

    @methane
    MemberAuthor

    @hroncok This issue is about indent, not dedent.

    See #131919 instead.

  7. hroncok commented on Apr 15, 2025

    @hroncok
  8. hroncok commented on Apr 15, 2025

    @hroncok
    Contributor
  9. methane commented on Apr 15, 2025

    @methane
    MemberAuthor

    #131919 references this issue.

    It references #130167, not this issue.

    #131923 references this issue because it makes textwrap.indent faster again. It is unrelated to textwrap.dedent.

  10. hroncok commented on Apr 15, 2025

    @hroncok
    Contributor

    Sorry for my confusion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directory

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions