Running code on module import

G

Grant D. Watson

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
(e-mail address removed) (Use this one!)
 
M

Michael Hudson

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.

I'd agree with that.

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

Cheers,
mwh
 
G

Grant D. Watson

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
(e-mail address removed)
(Please use this address, not my AOL one.)
 
G

Grant D. Watson

This works so long as runmain is the first module imported by any module that

No sooner said than I find that this doesn't work in my rewrite, only in my
first "version" (prototype is more like). Anyway, I suspect that this is
because in the first one I used a recursive import. (Is this dangerous? It
seems like it ought to be.) In the second one I tried to find the main()
function in the module object when the module hadn't finished initializing
yet.

Am I attempting the impossible, here? Will recursive imports burn me?

Grant D. Watson
(e-mail address removed)
(Please use this address, not my AOL one.)
 
T

Troy Melhase

Am I attempting the impossible, here? Will recursive imports burn me?

Recursive imports won't bury you, but the next maintenance programmer might
for modifying the behavior of the import statement beyond it's original
intent.

And you just never know: that maintenance programmer might be you!
 
H

Hung Jung Lu

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.

---------------------

When in Rome, do as the Romans do.

I thought your posting had some more substance to it. But now I
realize you were simply a barbarian not used to the way of the Romans.

But if you really want to do things the barbarian way, here is one
way.

---------------------

I guess you are a Unix user. However, I'll give you a Windows version,
you should be able to easily do the same thing in Unix.

Instead of running:

python demo.py

Create a batch (shell) file called watson.bat, with a line like:

python runmain.py %1 %2 %3 %4 %5 %6

and inside your runmain.py:

# runmain.py
import sys
import os.path
module_name = os.path.splitext(sys.argv[1])[0]
exec 'import %s' % module_name
module = sys.modules[module_name]
del sys.modules[module_name] # if you want so
# tweak the args and set the switches
.....
# run main()
module.main(switches, args)

and then run your program using:

watson demo.py --option1 --option2

---------------------

Python may have some hooks that would allow you to intercept moments
like the end of compilation stage, the start of execution stage, and
the exit of normal execution. What you want to do falls into the
general category of aspect-oriented programming. So there may be some
other tricks. However, why complicate your life? It's much simpler
just to do things the way Romans do, when you are in Rome.

regards,

Hung Jung
 
J

John Roth

Grant D. Watson said:
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.

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.

John Roth
 
G

Grant D. Watson

I thought your posting had some more substance to it. But now I
realize you were simply a barbarian not used to the way of the Romans.

I may have visited Rome only to build a mead hall, but I'm building it with
concrete, arches and marble columns. ;-)
But if you really want to do things the barbarian way, here is one
way.

The way you described is quite practical, but not nearly as fun. If I was just
concerned with making things work, it would do very well.

It just doesn't fall into the "neat hack" category. My first concept and first
attempts at runmain didn't add anything to "if __name__..."; I just wanted to
see if I could do it, and learn a little bit about Python in the process. I
still want to see if I can do it, and learn something about Python; my target
is a bit bigger, is all.

Grant D. Watson
(e-mail address removed)
(Please use this address, not my AOL one.)
 
H

Hung Jung Lu

John Roth said:
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
 
G

Grant D. Watson

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. :)

Grant D. Watson
(e-mail address removed)
(Please use this address, not my AOL one.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top