__file__ for relative imports

François Pinard pinard at iro.umontreal.ca
Thu Mar 21 20:17:26 EST 2002


[Ken Seehof]

> > Robin Becker <robin at jessikat.fsnet.co.uk> writes:
> > 
> > > Is there an obvious reason why modules imported from the current
> > > directory don't have an absolute pathname for __file__?

> I keep bumping into that one too.  [...]

There is another tiny bit in that area which might be debated as well.

`__file__' is not defined for the `__main__' module.  But `sys.argv[0]' in
that case contains the information one might have hoped out of `__file__'.
I would like if `__file__' was just dependably defined in all circumstances,
the best the Python interpreter can.  If this was done, the programmer would
then not have to resort anymore to convoluted code for finding the directory
and file for the current module.  Or maybe there is trick I do not know?

The only reason that would come to mind for not having `__file__' defined
is that some other platforms or systems (I'm only experienced with Python
on Linux) might have a hard time getting that information.  But even then,
if it is the case, is really sticking to the least common denominator the
proper approach?  Maybe `__file__' being set to the empty string in such
cases might be better than letting it undefined.

On the other hand, I would understand there is a difficulty with `__file__'
within a script read by the interpreter from standard input, or compiled
from the contents of a string.  I'm not sure what is the best approach in
those cases.  I still think the best would be that `__file__' be always
defined, in the most sensible way, whatever that may mean! :-)

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list