Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use importlib.LazyLoader?

Tags:

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.

like image 489
gerrit Avatar asked Mar 09 '17 19:03

gerrit


People also ask

How does Python Importlib work?

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.

What does Importlib Import_module do?

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.

How do I import a file into Python?

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.

How do you import tools in Python?

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.


1 Answers

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).

like image 157
Petter Avatar answered Oct 27 '22 19:10

Petter