from types import ModuleType class MyModule(ModuleType): def __metamodule_init__(self): self._metamodule_init_called = True class_attr = "foo" import metamodule metamodule.install(__name__, MyModule) del metamodule other_attr = "bar"
import metamodule metamodule.install(__name__) del metamodule __warn_on_access__["a"] = ( 1, FutureWarning("'a' attribute will become 2 in next release"))
# Setup the metamodule. import metamodule metamodule.install(__name__) del metamodule # Automatically execute "import .submodule" the first time that someone tries # to access it: __auto_import__.add("submodule") # Issue a warning whenever "a" is accessed. # We use a FutureWarning so that it's easier to see from the REPL that the # warning is issued. __warn_on_access__["a"] = ( 1, FutureWarning("'a' attribute will become 2 in next release")) # Regular globals are still exposed and accessible with no speed penalty: b = 2 def f(x): return b * x
from types import ModuleType class MyModule(ModuleType): # Make sure that having no __metamodule_init__ is legal, and does not get # routed through __getattr__. def __getattr__(self, attr): if attr == "class_attr": return "foo" raise AttributeError import metamodule metamodule.install(__name__, MyModule) del metamodule other_attr = "bar"