import importlib import logging import pathlib logger = logging.getLogger('import2ledger') def load_modules(src_dir_path): rel_path = src_dir_path.relative_to(pathlib.Path(__file__).parent) import_prefix = 'import2ledger.{}.'.format('.'.join(rel_path.parts)) for py_path in src_dir_path.glob('*.py'): mod_name = py_path.name[:-3] if mod_name.startswith(('.', '_')): continue try: module = importlib.import_module(import_prefix + mod_name) except ImportError as error: logger.info("failed to import %s: %s", py_path, error, exc_info=logger.isEnabledFor(logging.DEBUG)) else: yield module def module_contents(module): for name in dir(module): yield name, getattr(module, name) def submodule_items_named(file_path, name_test): for module in load_modules(pathlib.Path(file_path).parent): for name, item in module_contents(module): if name_test(name): yield item