Import weirdness

R

Remy C. Cool

Hello,

A couple of months ago, I posted a question related to the same
problem, but didn't get any replies. I've created a ugly workaround
but still would like to get some insight on the matter.

Case:

XMLRPC client imports modules and packages from a XMLRPC server.

Method used:

path_hooks
See PEP302 - http://www.python.org/peps/pep-0302.html

Basic layout of the importer class:

class RemoteImporter:

def __init__(self, path):
self.path = path
if path.split('.')[0] not in self.pathlist:
raise ImportError

def find_module(self, fullname, path=None):
print 'FIND MODULE:', fullname
self.package, self.code = self.server.import(fullname)
if self.code:
self.request_path = fullname.split('.')
return self

def load_module(self, fullname):
print 'LOAD MODULE:', fullname
path = self._get_code(fullname)
# create new module
mod = imp.new_module(fullname)
mod.__file__ = "<%s>" % fullname
mod.__loader__ = self
mod.__path__ = path
# register with sys.modules
sys.modules[fullname] = mod
# exec
exec self.code in mod.__dict__
return mod

def _get_code(self, fullname):
if len(self.request_path) > 1:
_fname = '.'.join(self.request_path[0:-1])
return self._get_subfile(fname, self.request_path[-1])
del fname
else:
return self._get_archive(self.request_path[-1])

def _get_archive(self, modname):
# assemble path
if self.package:
path = ["%s" % self.fullname]
else:
path = []
# return results
return path

def _get_subfile(self, parent, modname):
# assemble path
if self.package:
path = ["%s.%s" % (parent, modname)]
else:
path = []
# return results
return path


Note: pathlist contains ie: ['mymodules', 'RemoteImporter']

In the xmlrpc client app I have: import mymodules

The package mymodules get's imported and modules contained in
mymodules wil also be imported. One of the problems is that when I
want to import modules in other modules contained in the package.

Example:

mymodules
__init__.py
module_1.py
module_2.py
module_3.py

When I use the line: 'import module_2' in module_1.py, the 'fullname'
as printed by find_module is not mymodules.module_2 but only
module_2. Without the base, the module can't be found. It is solvable
by prefixing imports with 'mymodules' like 'import
mymodules.module_2', but that is not a portable solution since the
name 'mymodules' could change.

Is this behavour a bug?

< Remy >
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top