Import a module from a non-file?

Alex Martelli aleax at aleax.it
Sat Oct 18 06:16:16 EDT 2003


David Boddie wrote:

> Alex Martelli <aleax at aleax.it> wrote in message
> news:<sAUjb.7504$e5.250987 at news1.tin.it>...
>> Petri Savolainen wrote:
>> 
>> > I was trying to roll my own python code importer, but in the end, it
>> > seems that no matter what you try, it is always necessary to supply a
>> > REAL file object for python lower-level import machinery to work. Is
>> > this really true? Or did I miss something?
>> 
>> No, it's not true.  Read PEP 302,
>> http://www.python.org/peps/pep-0302.html , for details.
> 
> That's only for Python 2.3 and later, though, isn't it? I ran into this

Yes, PEP 302 and its early benefits (import-from-zip) were first implemented
with Python 2.3.

> problem using Python 2.2 with the ihooks and imp modules. I don't remember

Admittedly not the cleanest architecture, though quite workable.

> exactly which part of the infrastructure was insisting on file objects but
> the following lines from Python/import.c in the Python 2.3 source
> distribution would appear to be relevant:
> 
>     /* First check that there's an open file (if we need one)  */
>     switch (type) {
>     case PY_SOURCE:
>     case PY_COMPILED:
>         if (fp == NULL) {
>             PyErr_Format(PyExc_ValueError,
>                "file object required for import (type code %d)",
>                      type);
>             return NULL;
>         }
>     }

That's the load_module function exposed by module imp -- and in
any case when your type is IMP_HOOK you don't enter this test (in
2.3 ff -- no older sources around to check, sorry).


> I really should investigate the new import mechanism. In the meantime,
> it's good to know that the alternative import hook solutions still work
> with Python 2.3.

You mean overriding the builtin __import__ ?  Yes, it's kept around
for backwards compatibility, of course (also weird cases in which you
WANT the sys.modules cache to be systematically bypassed, though I
admit I can't think of a use case for that right now...;-).


Alex





More information about the Python-list mailing list