Skip to content

gh-137855: Improve import time of dataclasses by lazy importing re and copy modules#148379

Open
danielhollas wants to merge 7 commits intopython:mainfrom
danielhollas:dataclass-lazy-re
Open

gh-137855: Improve import time of dataclasses by lazy importing re and copy modules#148379
danielhollas wants to merge 7 commits intopython:mainfrom
danielhollas:dataclass-lazy-re

Conversation

@danielhollas
Copy link
Copy Markdown
Contributor

@danielhollas danielhollas commented Apr 11, 2026

Split from #144387 as requested by @hugovk (tagging for review :-) This is a relatively minor win, the bigger win will come from lazy importing inspect in #144387

See below for tuna-visualized outputs from ./python -X importtime -c "import dataclasses"
(the absolute import numbers are not representative as I was running a debug python build)

Before

image

After

image

Comment on lines 809 to 813
global _MODULE_IDENTIFIER_RE
if _MODULE_IDENTIFIER_RE is None:
_MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)')

match = _MODULE_IDENTIFIER_RE.match(annotation)
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.

Oh look, the regex starts with a ^ anchor, but then uses match, which is now better expressed with its prefixmatch alias:

https://docs.python.org/3.15/library/re.html#prefixmatch-vs-match

Let's either use search with ^, or prefixmatch without ^.


And a micro-optimisation for below, match[x] (introduced in 3.6) is a bit faster than match.group(x).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Cool! I went with prefixmatch

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.

There's also a match.group(2) on line 826.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ah, good catch, sorry about that

danielhollas and others added 4 commits April 11, 2026 17:19
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
@danielhollas
Copy link
Copy Markdown
Contributor Author

The failing Ubuntu build is a transient issue during dependency installation that will hopefully go away when the job is restarted.

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