Created
August 16, 2022 12:33
-
-
Save lorenzodifuccia/c9c96040d33072eecdd7470e734d71f8 to your computer and use it in GitHub Desktop.
Dynamically load submodules (subclass of BaseModule)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pkgutil | |
from importlib import import_module | |
# Dynamically load submodules (subclass of BaseModule). | |
# Ref: https://www.bnmetrics.com/blog/dynamic-import-in-python3 | |
for _, name, _ in pkgutil.iter_modules([MODULES_PATH, PERSONAL_MODULES_PATH]): | |
try: | |
imported_module = import_module("." + name, package=__name__) | |
except ImportError: # ModuleNotFoundError: python 3.6+ | |
imported_module = import_module('personal_modules.' + name, package="personal_modules") | |
for i in dir(imported_module): | |
attribute = getattr(imported_module, i) | |
if isinstance(attribute, type) and issubclass(attribute, BaseModule) and attribute != BaseModule: | |
setattr(sys.modules[__name__], attribute.__name__, attribute) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment