Fernando Pérez fperez528 at
Mon Nov 26 17:47:04 CET 2001

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 
Namespace:      Local - IPython Session
File:           /usr/lib/python2.1/site-packages/Numeric/

> 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 the above example, I don't have the ranlib source (in this case I could 
get it, b/c the original Numeric distribution is open source, but that's 
besides the point). All python sees is the binary module, and 
that's all you'll ever get.



More information about the Python-list mailing list