Running code on module import
Hung Jung Lu
hungjunglu at yahoo.com
Sun May 23 04:12:31 EDT 2004
"John Roth" <newsgroups at jhrothjr.com> wrote:
> Look at the built-in __import__() function, and the ihooks module.
> For what you want to do, you should be able to hook __import__
> so that you get control both before and after it.
He wants action performed *after* the main() is defined, not around
the time of import of his runmain. So, in a sense, he wants something
like a metaclass for the __main__ module.
Unfortunately:
(a) Python's modules are not classes, you can't intercept module
features with metaclasses.
(b) He wants something specified at the top module, like an "import"
statement. (If the *something* were specified at the bottom, it would
make things a bit easier.)
At the moment, I can only think on the sys.exitfunc as a proper hook.
:) It's totally esoteric/un-orthodox. But for whatever it's worth,
here is one example. Since it's totally un-orthodox, do not expect it
to run properly under all circumstances. (E.g.: it won't run from
console, it won't run inside Pythonwin, etc.) But it does run when
executed with standard shell command line.
#--- demo.py
import runmain
x=3
def main(switches, args):
if switches['print']:
legend = args[0]
print legend, x
#--- runmain.py
import sys
def runmain():
args = ['The value of %s is' % sys.argv[1]]
switches = {'print': 1}
sys.modules['__main__'].main(switches, args)
sys.exitfunc = runmain
#--- command line
python demo.py x
#--- result
The value of x is 3
--------------------------------
As I have said, it's best to do as the Romans do, when in Rome. Bite
the bullet and use the "if __name__ == '__main__':" that everyone else
uses. It's really not that bad looking. Any args tweaking or switches
can be done at the import of a tweaking module. Seriously, something
like below would do.
import myparams # creates args (from sys.argv) and switches
def main():
.... uses myparams.args and myparams.switches
if __name__ == '__main__':
main()
Hung Jung
More information about the Python-list
mailing list