Proper use of __file__

Jeffrey Froman jeffrey at fro.man
Tue Oct 5 12:02:12 EDT 2004


Darren Dale wrote:

> Would somebody explain how to use __file__? I mean, what information it
> carries, and more importantly, when it does and does not exist? A one line
> script:
> 
> print __file__
> 
> will yield the relative path if run from a shell, but will raise NameError
> when the script is run interactively from the interpreter. Is this the
> intended behavior?

__file__ is the name of the file in which the statement containing
"__file__" appears. If your file foo.py reads:

print __file__

You can run "import foo" from the interpreter, and it will print "foo.py",
just like if you ran "python foo.py". 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.

It is most certainly intended.

Hope that helps,
Jeffrey



More information about the Python-list mailing list