Skip to content

chore: avoid importing TYPE_CHECKING#1195

Closed
mayeut wants to merge 1 commit into
pypa:mainfrom
mayeut:type-checking
Closed

chore: avoid importing TYPE_CHECKING#1195
mayeut wants to merge 1 commit into
pypa:mainfrom
mayeut:type-checking

Conversation

@mayeut

@mayeut mayeut commented May 24, 2026

Copy link
Copy Markdown
Member

Using TYPE_CHECKING=False rather than importing it allows not to import typing altogether which can help with import time.
This PR forbids the use of typing.TYPE_CHECKING to ensure typing will not be imported if unneeded.

Comment on lines +10 to 15
from typing import NamedTuple

from ._elffile import EIClass, EIData, ELFFile, EMachine

TYPE_CHECKING = False
if TYPE_CHECKING:

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.

This is pointless code churn

@notatallshaw

Copy link
Copy Markdown
Member

Provide a real world use case that uses packaging and markedly improves due to saving type importing.

I am -1 on this without a real world benefit, while this works in practice isn't not part of the typing standard and adds a lot of churn across the code base.

@mayeut

mayeut commented May 24, 2026

Copy link
Copy Markdown
Member Author

you're right in the end it always typing always ends up being loaded. Let's wait for PEP781 to properly land in a few years. sorry for the noise.

@mayeut mayeut closed this May 24, 2026
@henryiii

Copy link
Copy Markdown
Contributor

For context, this is probably inspired by pypa/cibuildwheel#2866, which itself was inspired by henryiii/cibuildwheel#17 (from @hugovk). For cibuildwheel, when combined with lazy imports, it saves about 30% more time, and simplifies the lazy imports a bit (you can't lazy import TYPE_CHECKING and then use it, it reifies immediately). Not sure it's as effective here, though.

@mayeut

mayeut commented May 25, 2026

Copy link
Copy Markdown
Member Author

Not sure it's as effective here, though.

It's only effective for the errors & direct_url modules which is likely useless on its own . I should have checked that before hand.
There's a bunch of types exposed publicly in other modules and it would probably be deemed a regression to only expose them under the guard in order for this to be potentially effective in real-world applications.
typing import is roughly 1-2 ms (when all its deps are already imported) on Apple M1 / Python 3.15.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants