473,698 Members | 2,192 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Running code on module import

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**********@ya hoo.pleasedonts pamme.com (Use this one!)
Jul 18 '05 #1
8 2078
vb*******@aol.c om (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.pytho n
Jul 18 '05 #2
>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**********@ya hoo.pleasedonts pamme.com
(Please use this address, not my AOL one.)
Jul 18 '05 #3
>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**********@ya hoo.pleasedonts pamme.com
(Please use this address, not my AOL one.)
Jul 18 '05 #4
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
vb*******@aol.c om (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.splitex t(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(swi tches, 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
"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**********@ya hoo.pleasedonts pamme.com (Use this one!)

Jul 18 '05 #7
>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**********@ya hoo.pleasedonts pamme.com
(Please use this address, not my AOL one.)
Jul 18 '05 #8
"John Roth" <ne********@jhr othjr.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.switch es

if __name__ == '__main__':
main()

Hung Jung
Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1134
by: cameron.mccloud | last post by:
Hi, When trying to import the WMI module in a Python Windows Service, I get the following: dynamic module does not define init function (initwmi) The WMI version is 0.6. Python 2.4 on Win32, Python Win32 extensions version 203
8
3034
by: Paul Cochrane | last post by:
Hi all, I've got an application that I'm writing that autogenerates python code which I then execute with exec(). I know that this is not the best way to run things, and I'm not 100% sure as to what I really should do. I've had a look through Programming Python and the Python Cookbook, which have given me ideas, but nothing has gelled yet, so I thought I'd put the question to the community. But first, let me be a little more detailed...
2
8103
by: kkrizl | last post by:
I have an Access database that has a few huge tables. It was taking about 20 minutes per table to import them from another application. I used the upsize wizard to put them in a SQL server database. I created a DTS package to import the files and it runs in less than 5 minutes. I'd like to change my macro that used transfer text to import my files to run my DTS package. I've seen several posts regarding this, but I don't understand...
2
2326
by: jim-on-linux | last post by:
py help, The file below will run as a stand alone file. It works fine as it is. But, when I call it from another module it locks my computer, The off switch is the only salvation. This module when run as a stand alone, it will
4
1829
by: Michael Malinowski | last post by:
Is there a way to read the directory that the currently running python file is located in? Cheers Mike.
24
2833
by: Mark | last post by:
Hi, I'm new to python and looking for a better idiom to use for the manner I have been organising my python scripts. I've googled all over the place about this but found absolutely nothing. I'm a linux/unix command line guy quite experienced in shell scripts etc. I have a heap of command line utility scripts which I run directly. What is the best way to create python command line scripts but exploit the (loadonly) speed-up benefit of...
8
2773
by: geert | last post by:
Hi all, I have a mac mini running maocosx 10.5 leopard I want to deploy a django project on. My backend is MySQL, and I have it running as a 64- bit app. Of course, apache2 is also running as 64-bit. MySQLdb installs with the usual warnings after applying the various patches I found here and there. These patches consist of altering _mysql.c and site.cfg.
7
2185
by: alito | last post by:
Hi all, I am new to using packages to group my modules. I can't figure out how to run a module that uses relative imports without writing a wrapper that imports that module. Everything I try it complains that I am attempting a relative import in a non-package. eg ~/python/testpackage$ ls config.py importer.py __init__.py
20
5787
by: Nates | last post by:
I have a .bas file saved locally that I load into my Acces project to run a particular sub. I use the following code to load the module (which works fine): I use the following loop to remove the module: The above works fine (both adding the module and subsequantly removing it) provided I do not run any code within the module once it is loaded. The second I use code within the module the deletion loop does not seem to remove the...
0
8603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9026
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8893
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7723
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2328
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.