Do something every time a module is imported
1 answer
One of the possibilities could be the monkey patch __import__
:
>>> old_import = __import__
>>> def my_import(module,*args,**kwargs):
... print module, 'loaded'
... return old_import(module,*args,**kwargs)
...
>>> __builtins__.__import__ = my_import
>>> import datetime
datetime loaded
>>> import datetime
datetime loaded
>>> import django
django loaded
It worked fine on the command line (using Python 2.7.3 on Windows XP), but I don't know if it will work in other environments.
To access the module object (and not just the module name - so you can do something useful with it), simply intercept the return value instead of the argument:
>>> def my_import(*args,**kwargs):
... ret = old_import(*args,**kwargs)
... print ret
... return ret
...
>>> __builtins__.__import__ = my_import
>>> import datetime
<module 'datetime' (built-in)>
>>> import django
<module 'django' from 'C:\Python27\lib\site-packages\django\__init__.pyc'>
Update: Just confirmed that it works if it is also used in the python file - although in this case the correct way to assign it is __builtins__['__import__'] = my_import
.
+6
source to share