Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

import

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.

like image 293
litghost Avatar asked Mar 30 '10 04:03

litghost


People also ask

How can I tell which Python modules are imported?

Practical Data Science using Python To find all the python modules from a particular package that are being used in an application, you can use the sys. modules dict. sys. modules is a dictionary mapping module names to modules.

How can I tell where Python is importing from?

Running "python -v"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built in modules.

How does import statement work in Python?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.


1 Answers

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
...
like image 93
sth Avatar answered Nov 03 '22 21:11

sth