Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-118761: Lazily import annotationlib in typing #132060

Merged
merged 3 commits into from
Apr 4, 2025

Conversation

JelleZijlstra
Copy link
Member

@JelleZijlstra JelleZijlstra commented Apr 4, 2025

annotationlib is used quite a few times in typing.py, but I think the
usages are just rare enough that this makes sense.

The import would get triggered by:

  • Using get_type_hints(), evaluate_forward_ref(), and similar introspection
    functions
  • Using a string annotation anywhere that goes through _type_convert (e.g.,
    "Final['x']" will trigger an annotationlib import in order to access the
    ForwardRef class).
  • Creating a TypedDict or NamedTuple (unless it's empty or PEP 563 is on).

Lots of programs will want to use typing without any of these, so the tradeoff
seems worth it.

annotationlib is used quite a few times in typing.py, but I think the
usages are just rare enough that this makes sense.

The import would get triggered by:
- Using get_type_hints(), evaluate_forward_ref(), and similar introspection
  functions
- Using a string annotation anywhere that goes through _type_convert (e.g.,
  "Final['x']" will trigger an annotationlib import in order to access the
  ForwardRef class).
- Creating a TypedDict or NamedTuple (unless it's empty or PEP 563 is on).

Lots of programs will want to use typing without any of these, so the tradeoff
seems worth it.
Copy link
Member

@AlexWaygood AlexWaygood left a comment

Choose a reason for hiding this comment

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

I agree with the concept, but I think there's some opportunities to make this simpler and faster

Copy link
Member

@AlexWaygood AlexWaygood left a comment

Choose a reason for hiding this comment

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

the code doesn't look so pretty anymore, but I'm fine with this if it significantly speeds up the import time! (Do you have any numbers there?)

@JelleZijlstra
Copy link
Member Author

On this branch with -X importtime:

import time:      2162 |       4424 | typing

On main:

import time:      2017 |       7641 | typing

@JelleZijlstra JelleZijlstra merged commit 305be5f into python:main Apr 4, 2025
42 checks passed
@AlexWaygood
Copy link
Member

Nice work, thank you!!

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