Where is module being imported from?

Assuming I have two Python modules and path_b is in the import path:

# file: path_b/my_module.py
print "I was imported from ???"

#file: path_a/app.py
import my_module

Is it possible to see where the module is imported from? I want an output like "I was imported from path_a/app.py", if I start app.py (because I need the file name).

Edit: For better understanding; I could write:

# file: path_b/my_module.py
def foo(file):
    print "I was imported from %s" % file

#file: path_a/app.py
import my_module
my_module.foo(__file__)

So the output would be:

$> python path_app.py
I was imported from path_a/app.py

Try this:

>>> import my_module
>>> my_module.__file__
'/Users/myUser/.virtualenvs/foobar/lib/python2.7/site-packages/my_module/__init__.pyc'

Edit

In that case write into the __init__.py file of your module:

print("%s: I was imported from %s" %(__name__, __file__))

There may be an easier way to do this, but this works:

import inspect

print inspect.getframeinfo(inspect.getouterframes(inspect.currentframe())[1][0])[0]

Note that the path will be printed relative to the current working directory if it's a parent directory of the script location.


Try my_module.__file__ to find out where it is from. If you get an AttributeError, it is probably not a Python source (.py) file.


Also, if you have a function/class f from a module m you can get the path of the module using the module inspect

import inspect
from m import f

print inspect.getmodule(f)

This is how I do it:

print(module_name.__path__)