pyiron_base.utils.error module
Utility functions used in pyiron. In order to be accessible from anywhere in pyiron, they must remain free of any imports from pyiron!
- class pyiron_base.utils.error.ImportAlarm(message=None)
Bases:
object
In many places we have try/except loops around imports. This class is meant to accompany that code so that users get an early warning when they instantiate a job that won’t work when run.
Example:
>>> try: ... from mystery_package import Enigma, Puzzle, Conundrum ... import_alarm = ImportAlarm() >>> except ImportError: >>> import_alarm = ImportAlarm( ... "MysteryJob relies on mystery_package, but this was unavailable. Please ensure your python environment " ... "has access to mystery_package, e.g. with `conda install -c conda-forge mystery_package`" ... ) ... >>> class MysteryJob(GenericJob): ... @import_alarm ... def __init__(self, project, job_name) ... super().__init__() ... self.riddles = [Enigma(), Puzzle(), Conundrum()]
This class is also a context manager that can be used as a short-cut, like this:
>>> with ImportAlarm("MysteryJob relies on mystery_package, but this was unavailable.") as import_alarm: ... import mystery_package
If you do not use import_alarm as a decorator, but only to get a consistent warning message, call
warn_if_failed()
after the with statement.>>> import_alarm.warn_if_failed()
- warn_if_failed()
Print warning message if import has failed. In case you are not using ImportAlarm as a decorator you can call this method manually to trigger the warning.
- wrapper(function)
- pyiron_base.utils.error.retry(func: Callable[[], T], error: Type[Exception] | Tuple[Type[Exception], ...], msg: str, at_most: int | None = None, delay: float = 1.0, delay_factor: float = 1.0) T
Try to call func until it no longer raises error.
Any other exception besides error is still raised.
- Parameters:
func (callable) – function to call, should take no arguments
error (Exception or tuple thereof) – any exceptions to be caught
msg (str) – messing to be written to the log if error occurs.
at_most (int, optional) – retry at most this many times, None means retry forever
delay (float) – time to wait between retries in seconds
delay_factor (float) – multiply delay between retries by this factor
- Raises:
error – if at_most is exceeded the last error is re-raised
Exception – any exception raised by func that does not match error
- Returns:
whatever is returned by func
- Return type:
object