tags:

views:

83

answers:

4

How do you determine which file is imported in Python with an "import" statement?

I want to determine that I am loading the correct version of a locally modified .py file. Basically the equivalent of "which" in a POSIX environment.

+3  A: 

I figured it out. Imported modules have a __file__ field that is the file that was loaded. Combine that with __import__, I defined a function:

which = lambda str : __import__(str).__file__.

litghost
When you immediately assign a lambda to a variable, you should just use a def statement: `def which(str): return __import__(str).__file__`.
Roger Pate
+5  A: 

Look at its __file__ attribute.

Mike Graham
Yes, this is definitely the easiest method.import moduleprint module.__file__
Brendan Abel
+7  A: 

Start python with the -v parameter to enable debugging output. When you then import a module, Python will print out where the module was imported from:

$ python -v
...
>>> import re
# /usr/lib/python2.6/re.pyc matches /usr/lib/python2.6/re.py
import re # precompiled from /usr/lib/python2.6/re.pyc
...

If you additionally want to see in what other places Python searched for the module, add a second -v:

$ python -v -v
...
>>> import re
# trying re.so
# trying remodule.so
# trying re.py
# trying re.pyc
# trying /usr/lib/python2.6/re.so
# trying /usr/lib/python2.6/remodule.so
# trying /usr/lib/python2.6/re.py
# /usr/lib/python2.6/re.pyc matches /usr/lib/python2.6/re.py
import re # precompiled from /usr/lib/python2.6/re.pyc
...
sth
A: 

Put an explicit version identifier in each module.

__version__ = "Some.version.String"

Put these in every module you write, without exception.

import someModule
print someModule.__version__

This is (a) explicit, (b) easy to manage. You can also use "Keyword Substitution" from your version control tool to actually fill in the version string for you on each commit.

S.Lott