How to execute code when a module is imported ?

jepler at unpythonic.net jepler at unpythonic.net
Mon Aug 1 21:06:59 EDT 2005


Depending what you mean, it may be dirt simple:
-- foo.py --
print "bar"
-- end of foo.py --

When a module is first imported, all the statements in it are executed.  "def"
statements define functions, and "class" statements define clasess.  But you
can have any type of statement you like at the top level of a module.

However, the module is only executed at the first import.  On subsequent
imports, nothing happens except that the name 'foo' gets assigned the existing
foo module from sys.modules['foo']:
>>> import foo
bar
>>> import foo
>>> import foo

If you really need to do something each time 'import foo' is executed, then
you'll have more work to do.  One thing to do is override builtins.__import__.
Something like this (untested):

	class ArthasHook:
		def __init__(self):
			import __builtin__
			self.old_import = __builtin__.__import__
			__builtin__.__import__ = self.do_import


		def do_import(self, *args):
			m = self.old_import(*args)
			f = getattr(m, "__onimport__", None)
			if f: f()
			
	hook = ArthasHook()

After ArthasHook is created, then each 'import' statement will call
hook.do_import() That will look for a module-level function __onimport__, which
will be called with no arguments if it exists.

I don't recommend doing this.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050801/dbd4ae14/attachment.sig>


More information about the Python-list mailing list