Async imports to reduce startup times

I think the distinction being made is in the underlying mechanism (CPython internals), not in the syntax.

I would just wait until the proposal is made to see the details.

1 Like

I don’t think moving the problem to user land would solve it. Currently, if a user wants a lazy import, they can simply import the library where it’s needed, e.g., inside a function. Alternatively, with asyncio, they can wait for the library to be imported, import it again, and use it. Explicit lazy importing is already straightforward.

Concurrent imports could be naturally supported in a free-threading environment, where multiple threads can operate independently, without the need for explicitly deferring imports. This would be an implementation detail handled by the interpreter.

1 Like

This may be “simple” but it doesn’t really work if - for instance - you want a deferred import to use with PEP-649 annotations. If you use an if TYPE_CHECKING block to make a “fake” import then the annotations wouldn’t be available at runtime if something did want to analyse them (also you’d have to import typing, which is not free and may in fact be the module you were hoping to defer).

It also gets in the way of actual logic if you need to put an extra import statement everywhere you might use a module as I mentioned earlier.

One other use for lazy imports is importing parts of your own library to provide a better interface for users, or to maintain an interface that it turned out was the main cause of slow startups. The background for Scientific Python’s SPEC 1 probably explains this better. The upshot is that you have to declare your imports twice, once dynamically for the actual import mechanism and once again under a ‘TYPE_CHECKING’ block for static analysis[1].

I think finding ways to improve import time are good, but I don’t think they remove the need for a better way to defer imports and hopefully make things easier to maintain for people already using them.


  1. Or use some tool to analyse the ‘fake’ type_checking or stub imports and make them lazy at runtime. ↩︎