Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Running code on module import

Reply
Thread Tools

Running code on module import

 
 
Grant D. Watson
Guest
Posts: n/a
 
      05-21-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
http://www.velocityreviews.com/forums/(E-Mail Removed) (Use this one!)
 
Reply With Quote
 
 
 
 
Michael Hudson
Guest
Posts: n/a
 
      05-21-2004
(E-Mail Removed) (Grant D. Watson) writes:

> 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

--
It's a measure of how much I love Python that I moved to VA, where
if things don't work out Guido will buy a plantation and put us to
work harvesting peanuts instead. -- Tim Peters, comp.lang.python
 
Reply With Quote
 
 
 
 
Grant D. Watson
Guest
Posts: n/a
 
      05-22-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
(E-Mail Removed)
(Please use this address, not my AOL one.)
 
Reply With Quote
 
Grant D. Watson
Guest
Posts: n/a
 
      05-22-2004
>This works so long as runmain is the first module imported by any module that
>uses it.


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 Removed)
(Please use this address, not my AOL one.)
 
Reply With Quote
 
Troy Melhase
Guest
Posts: n/a
 
      05-22-2004
On Saturday 22 May 2004 12:13 am, Grant D. Watson wrote:
> 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!

--
Troy Melhase, (E-Mail Removed)
--
The riddles of God are more satisfying than the solutions of man. - G. K.
Chesterton


 
Reply With Quote
 
Hung Jung Lu
Guest
Posts: n/a
 
      05-22-2004
(E-Mail Removed) (Grant D. Watson) wrote in message news:<(E-Mail Removed)>...
> 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
 
Reply With Quote
 
John Roth
Guest
Posts: n/a
 
      05-22-2004
"Grant D. Watson" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> 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

> Grant D. Watson
> (E-Mail Removed) (Use this one!)



 
Reply With Quote
 
Grant D. Watson
Guest
Posts: n/a
 
      05-23-2004
>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 Removed)
(Please use this address, not my AOL one.)
 
Reply With Quote
 
Hung Jung Lu
Guest
Posts: n/a
 
      05-23-2004
"John Roth" <(E-Mail Removed)> 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
 
Reply With Quote
 
Grant D. Watson
Guest
Posts: n/a
 
      05-23-2004
>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 Removed)
(Please use this address, not my AOL one.)
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
imp.find_module don't found my module but standard import statement can import this module… why ? Stéphane Klein Python 0 07-05-2011 07:36 AM
Why 'import module' will not import module.py but the directorymodule? Peng Yu Python 0 10-31-2009 11:51 PM
Handling import conflicts when module has the same name as a library module that it needs to import? plb Python 0 02-08-2005 01:08 PM
Handling import conflicts when module has the same name as a library module that it needs to import? plb Python 0 02-08-2005 01:01 PM
import vs from module import : any performance issue? Pierre Rouleau Python 4 03-07-2004 05:06 PM



Advertisments