First, the idiomatic Python ("pythonic") style is to use the 20 lines of explicit import statements. Static analysis tools tend to function better if you don't try to circumvent the normal import mechanisms. Some IDEs like PyCharm can keep them sorted for you.
Dynamic imports like that are much harder to understand without actually running the code.
That said, some libraries do use runtime imports like this. Sometimes what you need to import depends on runtime conditions, so and it's worth learning how dynamic imports work.
Second, the __import__
builtin is not generally recommended because it doesn't handle the .
for you when modules are nested. Use importlib.import_module
instead. But in the case of Flask
, it's not a module, but a class, so use import_module('flask').Flask
.
Third, modules are not callable. You can't simply import something and call it, like you suggest.
import importLibs
importLibs()
instead it should be something like
from my_imports import importLibs
It is possible to place arbitrary objects into the import cache by mutating sys.modules
, so you could make a direct import callable that way. Modules have been known to replace themselves with other things on import like that. Please use responsibly, as this is again harder to reason about without actually running the code.
Fourth, the globals()
function refers to the globals of the defining module. Not the module it was called in. So you can't just from my_imports import importLibs
and then expect it to import things into the current module. They'll go inside the my_imports
module instead. There are at least two ways to deal with this.
One is to add some kind of globals_dict
parameter to the function and set the globals on that instead of globals()
. Then you'd call it like importLibs(globals())
. This way it will use the globals dict from the calling module instead of the defining (my_imports
) module.
The other way is to use the inspect
module to go up a stack frame and find the caller's module to get its globals. This way you won't have to pass it in explicitly and can just use importLibs()
. But this kind of automagic is more brittle and can break if you somehow call it indirectly inside a different module.
Another option is to import everything into your third module my_imports
, provide an __all__
there and then use
from my_imports import *
And if you manage your global namespace carefully, you don't even need the __all__
. Star imports are discouraged, because explicit imports are easier to reason about statically, but some libraries do work this way.
And finally, you could make a module with a short name, import everything there and then just access things via .
from that everywhere, like
import my
my.Flask
Again, some libraries work this way, like tk.