Skip to content

Instantly share code, notes, and snippets.

@pharmpy-dev-123
Forked from ttt-fifo/__init__.py
Created June 10, 2022 13:51
Show Gist options
  • Save pharmpy-dev-123/6cd2d7d21a8f34e74947c12c0d67fb53 to your computer and use it in GitHub Desktop.
Save pharmpy-dev-123/6cd2d7d21a8f34e74947c12c0d67fb53 to your computer and use it in GitHub Desktop.
Python >= 3.7 Dynamic Load Recipe
"""
Python Dynamic Load Recipe
for Python >= 3.7
See https://github.com/ttt-fifo/python-dynamicload for details
"""
import importlib.resources
# Change your dynamic imports here --------------------------------------------
# - As you would normally import your modules, functions, classes, etc.
# - But you should end every import with '... as somename'
IMPORTS = """
from . import examplemodule01 as examplemodule
from .examplemodule01 import myfunction01 as examplefunction
from .examplemodule02 import MyClassTwo as exampleclass
"""
# End dynamic imports ---------------------------------------------------------
# Parse the import registry
REGISTRY = {}
for i in IMPORTS.split('\n'):
if i == '':
continue
REGISTRY[i.split(' ')[-1]] = i
del IMPORTS
del i
# Needed for 'from mypackage import *'
__all__ = list(REGISTRY.keys())
def __getattr__(name):
"""
Executed whenever attribute is not found
Attempts to dynamically load attribute and return it
"""
if REGISTRY.get(name):
# Attempts to load dynamically from REGISTRY
try:
exec(REGISTRY[name], globals(), globals())
REGISTRY[name] = eval(name)
return REGISTRY[name]
except Exception:
print(f'ERROR while attempting to dynamically load {name}:')
raise
elif importlib.resources.is_resource(__name__, name):
# This is a module into the package directory, attempt to load it
exec(f'import {__name__}.{name}', globals(), globals())
return eval(f'{__name__}.{name}')
else:
# No such attribute, raise the proper exception
raise AttributeError(f'module {__name__} has no attribute {name}')
def __dir__():
"""
Give a hint to the end user what they could import, even the attributes
which are still not loaded in memory.
"""
return list(__all__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment