Running code on module import

Grant D. Watson vbasicboy at aol.com
Fri May 21 05:05:34 EDT 2004


If this has been answered before, or if my terminology is off, please bear with
me; my Python experience is limited to use in one class and to personal
projects.

I'd like to do something rather silly:  I'd like to run a particular piece of
code from a given module every time that the module is imported, and not just
at the time that the module is originally loaded.  So, every time a module says
    import foo
or something analogous, I want foo.doYourThing() to be invoked, in addition to
the usual effects on the importing module's namespace.

Now, my reaction is to create a newfangled import hook that will intercept
requests to load "foo" and send back a reference to the first loaded copy, so
that I only have one copy of foo at any given time, but omit (or delete, as
necessary) a reference to foo from sys.modules; this way my import hook will be
invoked each time someone wants to import foo (from which I can launch
foo.doYourThing()).

The problem is that I want to do all this without use of another module or
additional code in the module that imports foo.  This means that I have to
install the hook from _inside_ foo.  But if I do that, I can't seem to avoid
leaving a reference in sys.modules; removing it prevents the initial import
(the one that loads the module in the first place) from succeeding.

You're probably all foo-ed out by now.  Is there any way to do this?  I'm not
married to the import hook idea, it just seemed like the most promising to me. 
Is there some API I missed that would simplify things?

Your help is much appreciated.

Grant D. Watson
grant_watson at yahoo.pleasedontspamme.com (Use this one!) 



More information about the Python-list mailing list