Search code examples
pythonmodulepython-module

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.


Solution

  • 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;-).