In my module, I have a couple of functions that depend on an external module with a long startup time. How do I use LazyLoader
? If I have
import veggies
or
import veggies.brussels.sprouts
or
from veggies.brussels import sprouts
how would I replace those statements to use LazyLoader
such that the execution of the contents of the module are postponed until needed?
It is not immediately obvious from the documentation how to use it. There is no example, and nullege code search only comes up with the unit test included with Python itself.
The purpose of the importlib package is three-fold. One is to provide the implementation of the import statement (and thus, by extension, the __import__() function) in Python source code. This provides an implementation of import which is portable to any Python interpreter.
import_module(): This function imports a module programmatically. Name of module is first parameter to the function. Optional second parameter specifies package name if any.
If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.
Importing Modules To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.
The original issue has some code that seems to to a full import lazily:
The following files imports two modules lazily:
import sys
import importlib.util
def lazy(fullname):
try:
return sys.modules[fullname]
except KeyError:
spec = importlib.util.find_spec(fullname)
module = importlib.util.module_from_spec(spec)
loader = importlib.util.LazyLoader(spec.loader)
# Make module with proper locking and get it inserted into sys.modules.
loader.exec_module(module)
return module
os = lazy("os")
myown = lazy("myown")
print(os.name)
myown.test()
To test, I used the following in myown.py
.
print("Executed myown.")
def test():
print("OK")
That worked nicely (Python 3.8a0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With