can't reload with PEP 302 import hooks

Mustafa Thamer mus at
Fri Aug 13 23:30:50 CEST 2004

Hi, I'm using import hooks according to PEP 302, in order to load
python files from a game PAK file.  The game is C++ using embedded and
extended Python (v2.33) and Boost.  The importing works fine, but
after modules are imported I can't reload them.  I've tried
'reload(foo)' and 'PyImport_ReloadModule(pModPtr)', but both return
'ImportError: No module named foo'.
Is it safe to assume that reload doesn't respect the import hook? 
That seems like a problem.  Is there any work-around?


Here is my hook object code:

class myImportHandler:
   def find_module(self, fullname, path=None):
      return self                      # returns the loader object
   def _get_code(self, fullname):            # load code from game PAK
      if (fullname in sys.builtin_module_names):
         return False,None
      codeString = loadImportModule(fullname)   # CALLING C++ FUNCTION
      bIsPackage = False                  # not using PACKAGES
      if len(codeString):
         codeString2 = codeString.replace('\\r\','\')
         code = compile(codeString2, fullname, 'exec')
      return bIsPackage,code
   def normal_import(self, fullname):        # for built-ins
      return imp.load_module(fullname,file,pathname,desc)
   def load_module(self, fullname):          
         mod = sys.modules[fullname]         # check if module is
already loaded in sys.module?
      except KeyError:
         ispkg, code = self._get_code(fullname)
         if code==None:                # failed importing from game
            return self.normal_import(fullname)
         mod = imp.new_module(fullname)      # create new module
         sys.modules[fullname] = mod
         mod.__file__ = '<%s>' % self.__class__.__name__
         mod.__loader__ = self
         if ispkg:
            mod.__path__ = []          
         exec code in mod.__dict__
      return mod

More information about the Python-list mailing list