Proper use of __file__

David Bolen db3l at
Tue Oct 5 20:40:33 CEST 2004

aahz at (Aahz) writes:

> In article <10m5hc4mn8j3l04 at>,
> Jeffrey Froman  <jeffrey at> wrote:
> >
> >__file__ is the name of the file in which the statement containing
> >"__file__" appears. If your file reads:
> >
> >print __file__
> >
> >You can run "import foo" from the interpreter, and it will print "",
> >just like if you ran "python". But if you run "print __file__" in
> >the interpreter directly, NameError is raised because the call is not being
> >made from any file, so __file__ is undefined.
> One gotcha: in Python 2.2 and earlier, __file__ is only defined for
> imported modules; "python" will raise a NameError.

And even in later versions it can also be a problem for your main
script if you've packaged up your script into a standalone setup
(e.g., with installer/py2exe).

-- David

More information about the Python-list mailing list