Skip to content

gh-137855: Improve import time of textwrap by lazy importing re modules#150156

Closed
XiaoWan-zi wants to merge 1 commit into
python:mainfrom
XiaoWan-zi:gh-137855-textwrap-import-time
Closed

gh-137855: Improve import time of textwrap by lazy importing re modules#150156
XiaoWan-zi wants to merge 1 commit into
python:mainfrom
XiaoWan-zi:gh-137855-textwrap-import-time

Conversation

@XiaoWan-zi
Copy link
Copy Markdown
Contributor

Summary

  • Improve textwrap import time by lazy-importing re (PEP 810) instead of loading it at module import.
  • Defer compilation of TextWrapper word-separator regexes from class body to _compile_wordseps(), called on first TextWrapper() instantiation. Compiled patterns remain class attributes, shared across instances (same semantics as before).
  • Add LazyImportTest.test_lazy_import using ensure_lazy_imports() to guard against regressions.
    Part of the ongoing stdlib import-time work tracked in Improve import time of various stdlib modules #137855.

Motivation

textwrap is imported eagerly by many modules (e.g. tests, traceback, optparse paths) often only for dedent() / indent(), which do not need re. Previously, import re at module level and re.compile() in the TextWrapper class body caused re to load on every import textwrap.

Before

db7456bb-64c0-4ff9-92c7-528726129fdb

After

c4648acf-c2dc-4307-ad57-cddaa0feee9c

Copy link
Copy Markdown
Member

@picnixz picnixz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a nontrivial change that may break subclasses so closing, sorry.

@bedevere-app
Copy link
Copy Markdown

bedevere-app Bot commented May 20, 2026

A Python core developer has requested some changes be made to your pull request before we can consider merging it. If you could please address their requests along with any other requests in other reviews from core developers that would be appreciated.

Once you have made the requested changes, please leave a comment on this pull request containing the phrase I have made the requested changes; please review again. I will then notify any core developers who have left a review that you're ready for them to take another look at this pull request.

@picnixz picnixz closed this May 20, 2026
@XiaoWan-zi XiaoWan-zi deleted the gh-137855-textwrap-import-time branch May 20, 2026 23:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants