Request for loading zipped modules in some context

Kay Schluehr kay.schluehr at gmx.net
Sat Jan 5 02:55:06 EST 2008


When trying to import a module from a filesystem directory there are
several possibilities. Most obviously one can use an import statement
but if this is not sufficient one has also API functions. However
these API functions don't seem to be consistent with each other.

If one uses the builtin __import__ function one can import the module
in some context i.e. one can pass locals and globals:

__import__( name[, globals[, locals[, fromlist[, level]]]])

If one uses the imp module instead one has several different
possibilities to load a module ( load_source, load_compiled ) but none
of them imports the module in some context.

The situation becomes worse when using zipimport. The zipimport module
provides methods get_code and load_module.

>>> import zipimport
>>> importer = zipimport.zipimporter("myziparchive.zip")
>>> mod = importer.load_module("mymodule")
>>> mod
<module 'mymodule' from 'myziparchive.zip\mymodule.py'>

Using load_module returns a module object. One cannot initialize the
module in some context though. One can also use get_code and use a
code object:

>>> mod_code = importer.get_code("mymodule")
>>> mod_code
<code object <module> at 00B05260, file "myziparchive.zip
\mymodule.py", line 1>
>>> eval(mod_code, locals(), globals())
>>>

One can evaluate the code object but this won't give you much. It
won't magically transform the code object into a module object being
returned and cached. Creating a module object from a code object isn't
possible AFAIK. The get_code method doesn't seem to be particular
usefull.

I'd like to see things being made more uniform - but uniform in the
sense of providing the most powerfull options all over the place.



More information about the Python-list mailing list