""" Part of the bsie module. A copy of the license is provided with the project. Author: Matthias Baumgartner, 2022 """ # standard imports import importlib import typing # inner-module imports from . import errors # exports __all__: typing.Sequence[str] = ( 'safe_load', 'unpack_qualified_name', ) ## code ## def safe_load(module_name: str, class_name: str): """Get a class from a module. Raise BuilderError if anything goes wrong.""" try: # load the module module = importlib.import_module(module_name) except Exception as err: # cannot import module raise errors.LoaderError(f'cannot load module {module_name}') from err try: # get the class from the module cls = getattr(module, class_name) except Exception as err: # cannot find the class raise errors.LoaderError(f'cannot load class {class_name} from module {module_name}') from err return cls def unpack_qualified_name(name): """Split a name into its module and class component (dot-separated).""" if not isinstance(name, str): raise TypeError(name) if '.' not in name: raise ValueError('name must be a qualified class name.') module_name, class_name = name[:name.rfind('.')], name[name.rfind('.')+1:] if module_name == '': raise ValueError('name must be a qualified class name.') return module_name, class_name ## EOF ##