Proper use of __file__

Discussion in 'Python' started by Darren Dale, Oct 5, 2004.

  1. Darren Dale

    Darren Dale Guest

    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

    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?

    Darren Dale, Oct 5, 2004
    1. Advertisements

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

    It is most certainly intended.

    Hope that helps,
    Jeffrey Froman, Oct 5, 2004
    1. Advertisements

  3. Darren Dale

    Aahz Guest

    One gotcha: in Python 2.2 and earlier, __file__ is only defined for
    imported modules; "python" will raise a NameError.
    Aahz, Oct 5, 2004
  4. Darren Dale

    David Bolen Guest

    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
    David Bolen, Oct 5, 2004
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.