module.__path__

Ken Seehof kseehof at neuralintegrator.com
Tue Nov 27 19:23:55 EST 2001


Fernando Pérez <fperez528 at yahoo.com> wrote:

> Ken Seehof wrote:
>
> > Why is the __file__ attribute (of a module) a relative filename rather
than
> > a fully qualified filename?  One would think that the __file__ attribute
> > might be used for the purpose of locating and opening a source file,
right?
> >  If somebody wants a relative filename couldn't they split it
themselves?
> > By making module.__file__ relative, information is lost.  What was Guido
> > thinking???  Perhaps a __fullpath__ should be added.
> >
> > Don't tell me about the fact that .pyc files might be moved along with
.py
> > file from a different computer, thereby rendering the full pathnames
> > incorrect.  That's a silly argument not worth addressing. :-)
> >
> > Is there a good general way to determine the full pathname of a module
file,
> > or is the best approach to search sys.path for module.__file__?
>
> I don't know what Guido was thinking, my telepathy cap broke yesterday.
But
> as far as finding full, correct pathnames, use the inspect module
(standard
> with python >=2.1). It can get you filenames, code, function headers, just
> about anything you want about an object.
>
> An example:
>
> In [21]: ranlib ?
> Details for:    ranlib
> Type:           module
> String Form:    <module 'ranlib' from
> '/usr/lib/python2.1/site-packages/Numeric/ranlib.so'>
> Namespace:      Local - IPython Session
> File:           /usr/lib/python2.1/site-packages/Numeric/ranlib.so

Cool, that is a big help.  Thanks.  Ka-Ping Yee comes up with some neat
ideas.

> > If the module is an extension module, how do I find the full pathname of
the
> > source code file (preferably platform independent)?
> >
>
> You can't. It may have been compiled to binary and the source may not even
be
> on your computer at all. So it's inherently impossible to get it.

In my case, the application is an IDE, and it is a reasonable assumption
that the source code exists locally (and that the extension module was built
from the source in it's current location).  Anyway, since I control the
source code, I'll just add a bit of code to do the trick.  I was just hoping
something like this happened to be standard already that I didn't know
about....

Perhaps something like this in the init function:

    PyObject *module, *dict, *sourcefile;
    module = Py_InitModule("engine", engine_methods);
    dict = PyModule_GetDict(module);
    sourcefile = PyStringFromString(__FILE__);
    PyDict_SetItemString(dict, "__sourcefile__", sourcefile);







More information about the Python-list mailing list