Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Look at its __file__ attribute.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow