[Tutor] When is and isn't "__file__" set?

boB Stepp robertvstepp at gmail.com
Wed Jan 10 21:02:24 EST 2018


I am actually interested in the answer to this question for Python
versions 2.4, 2.6 and 3.x.

At https://docs.python.org/3/reference/import.html?highlight=__file__#__file__
it says:

<quote>
__file__ is optional. If set, this attribute’s value must be a string.
The import system may opt to leave __file__ unset if it has no
semantic meaning (e.g. a module loaded from a database).

If __file__ is set, it may also be appropriate to set the __cached__
attribute which is the path to any compiled version of the code (e.g.
byte-compiled file). The file does not need to exist to set this
attribute; the path can simply point to where the compiled file would
exist (see PEP 3147).

It is also appropriate to set __cached__ when __file__ is not set.
However, that scenario is quite atypical. Ultimately, the loader is
what makes use of __file__ and/or __cached__. So if a loader can load
from a cached module but otherwise does not load from a file, that
atypical scenario may be appropriate.
</quote>

I am still puzzling over things from the thread, "Why does
os.path.realpath('test_main.py') give different results for unittest
than for testing statement in interpreter?"  The basic question I am
trying to answer is how to determine the path to a particular module
that is being run.  For the experiments I have run thus far, the
module attribute, "__file__", has so far reliably given me the
absolute path to the module being run.  But the documentation suggests
that this attribute is optional.  So what can I rely on here with
"__file__"?  The first sentence of the cited quote is not illuminating
this sufficiently for me.


-- 
boB


More information about the Tutor mailing list