pyiron_snippets.import_alarm module

Graceful failure for missing optional dependencies.

class pyiron_snippets.import_alarm.ImportAlarm(message=None, raise_exception: bool = False)[source]

Bases: object

This class allows you to fail gracefully when some object has optional dependencies and the user does not have those dependencies installed.

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:
...     @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()[source]

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)[source]
exception pyiron_snippets.import_alarm.ImportAlarmError[source]

Bases: ImportError

To be raised instead of a warning when a package is missing.