Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for a module in Python without using exceptions

I can check for a module in Python doing something like:

try:
  import some_module
except ImportError:
  print "No some_module!"

But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.)

Note: The reason for no using try/except is arbitrary, it is just because I want to know if there is a way to test this without using exceptions.

like image 696
BlogueroConnor Avatar asked Aug 14 '26 11:08

BlogueroConnor


1 Answers

It takes trickery to perform the request (and one raise statement is in fact inevitable because it's the one and only way specified in the PEP 302 for an import hook to say "I don't deal with this path item"!), but the following would avoid any try/except:

import sys

sentinel = object()

class FakeLoader(object):
  def find_module(self, fullname, path=None):
    return self
  def load_module(*_):
    return sentinel

def fakeHook(apath):
  if apath == 'GIVINGUP!!!':
    return FakeLoader()
  raise ImportError

sys.path.append('GIVINGUP!!!')
sys.path_hooks.append(fakeHook)

def isModuleOK(modulename):
  result = __import__(modulename)
  return result is not sentinel

print 'sys', isModuleOK('sys')
print 'Cookie', isModuleOK('Cookie')
print 'nonexistent', isModuleOK('nonexistent')

This prints:

sys True
Cookie True
nonexistent False

Of course, these would be absurd lengths to go to in real life for the pointless purpose of avoiding a perfectly normal try/except, but they seem to satisfy the request as posed (and can hopefully prompt Python-wizards wannabes to start their own research -- finding out exactly how and why all of this code does work as required is in fact instructive, which is why for once I'm not offering detailed explanations and URLs;-).

like image 64
Alex Martelli Avatar answered Aug 17 '26 03:08

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!