0

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
FirefoxMetzger
  • 1,760
  • 10
  • 24
  • The question is indeed answered by the duplicate. I doubt I would have come up with those keywords though. Hopefully others (with similar keywords in mind) can use this question as a reference to find what they are looking for :) – FirefoxMetzger Nov 20 '21 at 14:31

0 Answers0