How do you determine which file is imported into Python using the import statement?

How do you determine which file is imported into Python using the 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.

+6
python import
source share
4 answers

Run python with the -v option to enable debug output. When you 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 also want to see in what other places Python was looking for a module, add the 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 ... 
+10
source share

Look at its __file__ attribute.

+6
source share

I get it. Imported modules have a __file__ field, which is the downloaded file. Combine this with __import__ , I defined a function:

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

+2
source share

Put the explicit version identifier in each module.

 __version__ = "Some.version.String" 

Put them 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 populate the version string for each commit.

0
source share

All Articles