Using Python's LazyLoader to import class import top level module

Viewed 258

If I do import os lazily I can use the method below:

os = lazy('os')

And it load the library lazily, but if I do:

path = lazy('os.path')

The LazyLoader is loading the os module, then Lazy Loading path submodule. How can I prevent that from happening?

Additionally I do not know if this is supported, but I would like to know if you can do something like this:

from os.path import isdir

But have the method be returned in a lazy fashion?

def lazy(fullname):
  if fullname in sys.modules:
    return sys.modules[fullname]
  else:
    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
0 Answers
Related