Import a module from a non-file?

David Boddie davidb at mcs.st-and.ac.uk
Fri Oct 17 18:57:54 EDT 2003


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 problem
using Python 2.2 with the ihooks and imp modules. I don't remember 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;
        }
    }

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.

David




More information about the Python-list mailing list