Skip to content

⚡ perf: avoid importing typing at runtime - #714

Merged
gaborbernat merged 4 commits into
tox-dev:mainfrom
hugovk:defer-typing-import
Nov 17, 2026
Merged

gaborbernat merged 4 commits into
tox-dev:mainfrom
hugovk:defer-typing-import

Conversation

@hugovk

@hugovk hugovk commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Rather than importing typing at runtime when it's not needed:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from pathlib import Path
    from typing import Literal

We can avoid the import entirely with this common pattern:

TYPE_CHECKING = False
if TYPE_CHECKING:
    from pathlib import Path
    from typing import Literal

Import times measured and visualised with https://pypi.org/project/tuna/:

python3 -X importtime -c "import platformdirs" 2> import.log
tuna import.log

Before: 11ms

image

After: 8ms

image

A test now checks in a fresh interpreter that import platformdirs leaves typing out of sys.modules, so a later import that pulls it back in fails CI.

@gaborbernat gaborbernat added the enhancement New feature or request label Nov 17, 2026
@gaborbernat gaborbernat changed the title Avoid typing import at runtime ⚡ perf: avoid importing typing at runtime Nov 17, 2026
@gaborbernat
gaborbernat merged commit d67c5d5 into tox-dev:main Nov 17, 2026
40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants