Following up on Async imports to reduce startup times.
This would be a very different approach, and I’m not sure how much sense it’d make, but I think we could possibly add the following:
- A way to explicitly state that deferred execution is supported by the module
- A delayed execution flag in bytecode
- A special function that is always explicitly called at import time (eg.
__run__
), even if the the module supports delayed execution
Since delaying execution is mainly an optimization thing, not doing it shouldn’t be a big deal for modules, but doing it without the module explicitly supporting it can be problematic, as the module might rely on code executing on import. For this reason, we opt out by default and only use it when we know it’s supported.
When a module is imported in delayed execution mode, all its attributes become delayed references — the code that defines them is only executed on access. Code that needs to be executed at import time goes into __run__
, which can include triggering the execution of certain attributes.
As far as adoption goes, having to flag every single module as supporting delayed execution would be pretty annoying, and that’s where the bytecode flag comes in. Most code is shipped as a package, so we could add some metadata to flag delayed execution support for its whole pure-Python code, which installers could check, and generate the bytecode accordingly. We can also have the backends or installers directly adding the flag themselves, depending on which execat mechanism we choose for that.
This provides a pretty easy path for projects to adopt the feature, leaving only unpackaged code needing to use the manual flag. On top of it, it is backwards compatible, and doesn’t require any syntax changes.
The main drawback AFAICT is that delayed execution might not be guaranteed to module authors, but I think that’s okay, as I don’t see a big need for that, and it cal already be accomplished in other ways (eg. module __getattr__
).
Any thoughts? Is there any technical detail I am missing regarding the viability of this?