0

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

Daniele Grattarola
  • 1,517
  • 17
  • 25
  • I don't know exactly what you're trying to accomplish here, but I would use a decorator. – Tom Wojcik Sep 13 '18 at 08:01
  • 1
    relevant https://stackoverflow.com/questions/20226347/importing-python-libraries-and-gracefully-handling-if-they-are-not-availalble – Chris_Rands Sep 13 '18 at 08:04
  • Your ``print`` message implies the module will not work without its dependency - why catch the error at all in this case? An ``ImportError`` can be caught by code trying to use your module, a ``print`` must be manually noticed by someone. – MisterMiyagi Sep 13 '18 at 09:07
  • I want to catch the error because the rest of the library can still work without the dependency, so I don't want `__init__.py` to crash for the `ImportError` – Daniele Grattarola Sep 13 '18 at 13:13

0 Answers0