By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,640 Members | 1,598 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,640 IT Pros & Developers. It's quick & easy.

Running code on module import

P: n/a
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
gr**********@yahoo.pleasedontspamme.com (Use this one!)
Jul 18 '05 #1
Share this Question
Share on Google+
8 Replies


P: n/a
vb*******@aol.com (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
Jul 18 '05 #2

P: n/a
>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
gr**********@yahoo.pleasedontspamme.com
(Please use this address, not my AOL one.)
Jul 18 '05 #3

P: n/a
>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
gr**********@yahoo.pleasedontspamme.com
(Please use this address, not my AOL one.)
Jul 18 '05 #4

P: n/a
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, tr**@gci.net
--
The riddles of God are more satisfying than the solutions of man. - G. K.
Chesterton
Jul 18 '05 #5

P: n/a
vb*******@aol.com (Grant D. Watson) wrote in message news:<20***************************@mb-m06.aol.com>...
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
Jul 18 '05 #6

P: n/a
"Grant D. Watson" <vb*******@aol.com> wrote in message
news:20***************************@mb-m15.aol.com...
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
gr**********@yahoo.pleasedontspamme.com (Use this one!)

Jul 18 '05 #7

P: n/a
>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
gr**********@yahoo.pleasedontspamme.com
(Please use this address, not my AOL one.)
Jul 18 '05 #8

P: n/a
"John Roth" <ne********@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
Jul 18 '05 #9

This discussion thread is closed

Replies have been disabled for this discussion.