I am developing a Python library with a module that depends on a third-party package not available through PyPi or Anaconda. The module should expose some functions if the dependency is available on the system, and otherwise fail gracefully with an appropriate message.
For now, I am handling this as follows:
try:
import the_dependency as td
def foo(x):
return td.bar(x)
except ImportError:
print('Failed to import the_dependency, the whole module will not be available')
This works, for now, but I don't like the idea of having function declarations inside the try block (it seems messy). I've looked at other libraries that have this behavior, and I've found this solution:
try:
import the_dependency as td
except ImportError:
td = None
def foo(x):
if td is None:
raise ImportError('the_dependency is required to run foo')
return td.bar(x)
but again, it looks messy and requires duplicating code/error messages.
Is there a better way to handle this, in Python?
Thanks