Does Python offer modules the ability to respond to missing (module-level) attributes?
What I would like to be able to do is something like
# my_module\__init__.py
import importlib
available_modules = ["foo", "bar"]
def __missing__(this_module, key):
if key in available_modules:
setattr(this_module, key, importlib.load_module(key))
return getattr(this_module, key)
# my_module\foo.py
somevar = "A"
# my_module\bar.py
somevar = "B"
# downstream script
import my_module # foo, and bar not imported yet
assert my_module.foo.somevar == "A" # lazy imports foo
assert my_module.bar.somevar == "B" # lazy imports bar
my_module.foobar # raises attribute error