midgard.dev.optional
Midgard library module for handling optional dependencies
Description:
Import dependencies that are only necessary for specific parts of Midgard. Using this module will delay raising an ImportError until the dependency is actually used. This means that if one for instance only wants to run a GNSS analysis (or only use a Rinex-parser) installing special libraries only used for VLBI is not necessary.
Examples:
The optional import is typically used as follows::
from midgard.lib import optional
netCDF4 = optional.optional_import('netCDF4')
EmptyStringMock
EmptyStringMock(name:str, raise_error:bool=True, attrs:Union[Dict[str, Any], NoneType]=None) -> None
A mock object whose properties are all empty strings
SimpleMock
SimpleMock(name:str, raise_error:bool=True, attrs:Union[Dict[str, Any], NoneType]=None) -> None
Class that can stand in for any other object
The SimpleMock is used to stand in for any library that can not be imported. The mock object simply returns itself whenever it is called, or any attributes are looked up on the object. This is done, to avoid ImportErrors when a library is imported, but never used (for instance if a plugin is loaded but never called).
Instead the ImportError is raised when the SimpleMock is used in any way. The ImportError will only be raised once for any SimpleMock-object (which is only important if the ImportError is caught and the program carries on).
The exception is if any attributes (attrs
) are explicitly defined on the mock. No exception is raised if those
attributes are looked up.
optional_import()
optional_import(module_name:str, raise_error:bool=True, mock_cls:type=<class 'midgard.dev.optional.SimpleMock'>, attrs:Union[Dict[str, Any], NoneType]=None) -> Union[Any, midgard.dev.optional.SimpleMock]
Try to import an optional module
If the module does not exist, a SimpleMock-object is returned instead. If this SimpleMock-object is later used, an
ImportError will be raised then (if raise_error
is True, which is default).
Args:
module_name
: Name of module to import.raise_error
: Whether an ImportError should be raised if the module does not exist, but is used.attrs
: Attributes that should be added to the SimpleMock used if the module does not exist.
Returns:
Imported module object, or a SimpleMock-object if the module can not be imported.