Specify `TYPE_CHECKING = False` without typing import

A quick search on GitHub for TYPE_CHECKING = True (excluding Sphinx’s autodoc) shows c. 16 results:

To be clear, this is extremely minimal use given the corpus of all code on GitHub (unless something is wrong with my search query!).

A

3 Likes

There is a limited implementation of typing for MicroPython but it’s not part of the standard builds.

It would be good to have a standard solution for cases where every byte counts.

Regarding import times, currently (read, 3.13) typing has a module-level __getattr__ to generate some aliases on-the-fly.

Wouldn’t moving the special forms implementations to an “internal” module, something like _typing.py or _typing_internals.py, and using typing’s __getattr__ to get them from that module help reduce load times? Or would module resolution merge everything anyway?

I think that would make sense if there is one thing (or a few things) in typing.py that are both slow to create and rarely used. But I’m not sure that’s true; it’s slow mostly because there’s a lot of stuff in there, not because any particular thing is slow. However, maybe detailed profiling will show that I’m wrong there, so I’d love for someone to take a detailed look and try to find ways to make typing.py faster to execute.

1 Like

probably not. The moment someone has a module level import of from typing import SomeAlias the __getattr__ will be invoked. For this to have any benefit, you’d need import typing as t and then use of t.SomeAlias only in places where evaluation of the attribute access is deferred, such as type alias statements or annotations (3.13 and earlier with a future import, 3.14 forward with 649)

This could still be done, but it would require adoption across “foundational libraries” to make it likely that users dont end up eagerly importing anyhow. It also rules out use of typing decorators.
You can see this post for details on the current limitations of runtime deferral of typing.

Something that would improve performance here is to remove all the metaprogramming tricks going on in that file and expand it in source code instead. This reduces the amount of things that need executing at import time, but that’s not free either, it has costs on development in some form or other, and would probably make a codegen script appealing (even if it’s run manually and results checked in).

5 Likes