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