Test module in Python without using exceptions

I can verify that the module in Python does something like:

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

But I do not want to use try / except. Is there any way to do this? (it should work on Python 2.5.x.)

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

+3
source share
4 answers

( raise , , PEP 302 , " ",!), : 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')

:

sys True
Cookie True
nonexistent False

, , try/except, , , (, , Python- wizards wannabes, - , , , URL-; -).

+7

, Python . , python, sys.modules, sys.meta_path sys.path, .

, ( ) , , !

+1

. , , .

, try/except. , , , . , -, , , try/except.

0

sys.modules, -, .

-1

Source: https://habr.com/ru/post/1714260/


All Articles