Overwrite import, show the names of the modules importing the module

Possible duplicate:
know file_name: line_no where the import was made in my_module

I want to know which modules import my sample module "foo":

foo.py

# pseudocode, this should be triggered when "foo" is imported on_import(): print "foo is imported by module X" 

bar.py

 # this should print "foo is imported by module bar" import foo 

How can I implement this behavior?

+4
source share
1 answer

@Wooble you're right

Here the solution from knows the file name: line_no, where the import was made in my_module

 import inspect last_frame = inspect.stack()[1] print 'Module imported from file:line_no = %s:%i' % last_frame[1:3] 
0
source

All Articles