Skip to content

gh-154675: Improve import time of unittest and unittest.mock by around 4 times - #162871

Open
hugovk wants to merge 5 commits into
python:mainfrom
hugovk:3.16-lazy-unittest
Open

hugovk wants to merge 5 commits into
python:mainfrom
hugovk:3.16-lazy-unittest

Conversation

@hugovk

@hugovk hugovk commented Nov 30, 2026 •

Copy link
Copy Markdown
Member
module before after
unittest
14 ms image 3 ms image
unittest.mock
14 ms image 4 ms image

Also:

@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #36265126 | 📁 Comparing ae088eb against main (352cc06)

  🔍 Preview build  

2 files changed
± whatsnew/3.16.html
± whatsnew/changelog.html

Comment thread Lib/unittest/loader.py
# we would need to avoid loading the same tests multiple times
# from '.py', *and* '.pyc'
VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE)
def __getattr__(name):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I find these kind of constructions quite ugly, especially if you put them at the top of the module where anyone following the unittest loader would find it. Is it necessary to make re import faster here? (I think it's 11% only right?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I agree, in this case I don't think it is worth it, unittest isn't particularly performance sensitive. Also, how many of these does a simple test suite trigger anyway?

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

Labels

awaiting core review type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants