title: How can I check on runtime that a python module is valid without importing it?
body: <p>I have a package containing subpackages only one of which I need imported during runtime - but I need to test they are valid. Here is my folder structure:</p>
  
  <pre><code>game/
   __init__.py
   game1/
     __init__.py
     constants.py
     ...
   game2/
     __init__.py
     constants.py
     ...
  </code></pre>
  
  <p>For now the code that runs on boot does:</p>
  
  <pre><code>import pkgutil
  import game as _game
  # Detect the known games
  for importer,modname,ispkg in pkgutil.iter_modules(_game.__path__):
      if not ispkg: continue # game support modules are packages
      # Equivalent of "from game import &lt;modname&gt;"
      try:
          module = __import__('game',globals(),locals(),[modname],-1)
      except ImportError:
          deprint(u'Error in game support module:', modname, traceback=True)
          continue
      submod = getattr(module,modname)
      if not hasattr(submod,'fsName') or not hasattr(submod,'exe'): continue
      _allGames[submod.fsName.lower()] = submod
  </code></pre>
  
  <p>but this has the disadvantage that all the subpackages are imported, importing the other modules in the subpackage (such as the constants.py etc) which amounts to some few magabytes of garbage. So I want to substitute this code with a test that the submodules are valid (they <em>would</em> import fine). I guess I should be using eval somehow - but how ? Or what should I do ?</p>
  
  <p><strong>EDIT:</strong> tldr;</p>
  
  <p>I am looking for an equivalent to the core of the loop above:</p>
  
  <pre><code>    try:
          probaly_eval(game, modname) # fails iff `from game import modname` fails
          # but does _not_ import the module
      except: # I'd rather have a more specific error here but methinks not possible
          deprint(u'Error in game support module:', modname, traceback=True)
          continue
  </code></pre>
  
  <p>So I want a clear answer if an <em>exact equivalent</em> to the import statement vis a vis error checking exists - <strong><em>without</em></strong> importing the module. That's my question, a lot of answerers and commenters answered different questions.</p>