Proper use of __file__

D

Darren Dale

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?

Thanks,
Darren
 
J

Jeffrey Froman

Darren said:
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
 
A

Aahz

__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.

One gotcha: in Python 2.2 and earlier, __file__ is only defined for
imported modules; "python foo.py" will raise a NameError.
 
D

David Bolen

One gotcha: in Python 2.2 and earlier, __file__ is only defined for
imported modules; "python foo.py" 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top