diff options
author | Matthias Baumgartner <dev@igsor.net> | 2022-12-24 10:27:09 +0100 |
---|---|---|
committer | Matthias Baumgartner <dev@igsor.net> | 2022-12-24 10:27:09 +0100 |
commit | 266c2c9a072bf3289fd7f2d75278b7d59528378c (patch) | |
tree | 60760e0fec84d5cd7b3f3efef11e3892df5cc85a /bsie/utils/loading.py | |
parent | ed2074ae88f2db6cb6b38716b43b35e29eb2e16c (diff) | |
download | bsie-266c2c9a072bf3289fd7f2d75278b7d59528378c.tar.gz bsie-266c2c9a072bf3289fd7f2d75278b7d59528378c.tar.bz2 bsie-266c2c9a072bf3289fd7f2d75278b7d59528378c.zip |
package restructuring: base
* Reader and Extractor to respective reader/extractor modules
* ReaderBuilder to reader module
* ExtractorBuilder to extractor module
* Loading module in utils (safe_load, unpack_name)
* Pipeline and PipelineBuilder to lib module
* errors to utils
* documentation: "standard import" and "external import"
Diffstat (limited to 'bsie/utils/loading.py')
-rw-r--r-- | bsie/utils/loading.py | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/bsie/utils/loading.py b/bsie/utils/loading.py new file mode 100644 index 0000000..eb05c35 --- /dev/null +++ b/bsie/utils/loading.py @@ -0,0 +1,54 @@ +""" + +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 ## |