Running code on module import

Grant D. Watson vbasicboy at aol.com
Sat May 22 03:57:01 EDT 2004


>I would also wonder just what on earth you are up to... it seems very
>unnatural to me.

Well, it is somewhat unnatural for Python.

By importing my magic module, I want to have my main() function invoked,
without any "if __name__..." stuff.  My C-and-Java trained aesthetic
sensibilities aside, I want to do this so that I can do a bunch of
argv-processing stuff and just pass the results to main() without having to
call anything manually.

So, for example, "demo.py":
---
import runmain

options = "ab:c"

def main(switches, args):
    if switches["a"]:
        print "-a is set"
    else:
        print "-a is not set"
    print "The value of -b is", switches["b"]
    print "Non-switch arguments:", args
    return 42
---

Now, I've got some stuff for dealing cleanly with invalid switches, and I've
just rewritten runmain to be a bit cleaner and to allow long-style switches
("--bar").

This works so long as runmain is the first module imported by any module that
uses it.  When the module is loaded, it can check what module loaded it and
whether that is the "top-level" module; if it is, it invokes main().  But if
the top-level module imports baz, and baz imports runmain, *then* the top-level
module imports runmain -- well, the code never gets to check the top-level
module for main(), because it is just imported from sys.modules.

I suppose I could just check the top module for main(), regardless of who
imported runmain, but I don't want to be calling main()s that were meant to
work differently and sending them the wrong parameters.

Hence the whole import-hook scheme and its flaw.  If I could get it to work,
that would let me check every module that imported runmain, to see if it was
the top one.

Grant D. Watson
grant_watson at yahoo.pleasedontspamme.com
(Please use this address, not my AOL one.)



More information about the Python-list mailing list