Running code on module import

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Sun May 23 20:22:06 EDT 2004


Grant D. Watson wrote:

>> At the moment, I can only think on the sys.exitfunc as a proper hook.
>> :) It's totally esoteric/un-orthodox.
> 
> And it's got major style points.  The stuff I'd been playing around
> with since the after thread began has involved grabbing the source
> code from __main__ and rerunning it on a new module's namespace (with
> __file__ and __doc__ copied over), then running main() from that. 
> When I'm done, I raise a SystemExit. 
> 
> sys.exitfunc seems more elegant and far easier; plus, it looks like
> its down sides aren't any greater than what I've been doing.  (Life
> became saner when I realized I could also implement a wrapper
>  function to be called interactively.) I'll have to test this.
> 
> Hmm... I wonder if I can use a callable instead of a function; the
> docs say a function, but...  Okay, I tried it and it worked.  But the
> atexit module looks promising too -- you have opened up so many
> possiblities.  :-) 

The next person to look at your code is going to want to kill you.

Seriously, don't go down this path with any code you care about. It's
fine for determining what you can do, but *never* put something like
this in *any* code that anyone else could ever possibly see.

Oh - and either throw away your experimental code once you're done, or
mark in big letters to NEVER DO THIS and why ...

Tim Delaney




More information about the Python-list mailing list