Thursday, 8 June 2017

python - Overwrite import, show names of modules importing a module










I want to find out which modules are importing 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?


Answer



@Wooble you are right



Here's the solution from know filename:line_no where an import to my_module was made



import inspect

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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...