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

Attachment: pgpFEnkgmOzgl.pgp
Description: PGP signature

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to