Created
October 23, 2020 14:10
-
-
Save Mark1002/a39a58f603d61ed8c999f11ab680b6e1 to your computer and use it in GitHub Desktop.
python auto load sub module class.
This file contains hidden or 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
from inspect import isclass | |
from pkgutil import iter_modules | |
from pathlib import Path | |
from importlib import import_module | |
REF = {} | |
# iterate through the modules in the current package | |
package_dir = str(Path(__file__).resolve().parent) | |
def load_class(package_dir, import_path): | |
for (_, module_name, ispkg) in iter_modules([package_dir]): | |
if ispkg: | |
import_path = f'{import_path}.{module_name}' | |
package_dir = f'{package_dir}/{module_name}' | |
load_class(package_dir, import_path) | |
else: | |
# import the module and iterate through its attributes | |
module = import_module(f"{import_path}.{module_name}") | |
for attribute_name in dir(module): | |
attribute = getattr(module, attribute_name) | |
if isclass(attribute): | |
# Add the class to this package's variables | |
REF[attribute_name] = attribute | |
load_class(package_dir, __name__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment