[Python-Dev] Investigating time for import requests (original) (raw)

Koos Zevenhoven k7hoven at gmail.com
Tue Oct 3 05:58:05 EDT 2017


I've probably missed a lot of this discussion, but this lazy import discussion confuses me. We already have both eager import (import at the top of the file), and lazy import (import right before use).

The former is good when you know you need the module, and the latter is good when you having the overhead at first use is preferable over having the overhead at startup. But like Raymond was saying, this is of course especially relevant when that import is likely never used.

Maybe the fact that the latter is not recommended gives people the feeling that we don't have lazy imports, although we do.

What we don't have, however, is partially lazy imports and partially executed code, something like:

on demand: class Foo: # a lot of stuff here

def foo_function(my_foo, bar):
    # more stuff here

When executed, the on demand block would only keep track of which names are being bound to (here, "Foo" and "foo_function"), and on the lookup of those names in the namespace, the code would actually be run.

Then you could also do

on demand: import sometimes_needed_module

Or

on demand: from . import all, submodules, of, this, package

This would of course drift away from "namespaces are simply dicts". But who cares, if they still provide the dict interface. See e.g. this example with automatic lazy imports:

https://gist.github.com/k7hoven/21c5532ce19b306b08bb4e82cfe5a609

Another thing we don't have is unimporting. What if I know that I'm only going to need some particular module in this one initialization function. Why should I keep it in memory for the whole lifetime of the program?

––Koos

--



More information about the Python-Dev mailing list