On Sat, 14 Aug 2010 16:05:05 -0700, bvdp wrote: > Assuming I have a module 'foo.py' with something like this: > > def error(s): > print "Error", s > sys.exit(1) > > def func(s): > ... do some processing > ... call error() if bad .. go to system exit. ... more processing > > and then I write a new program, test.py, which: > > import foo > > def myerror(s): > print "new error message" > > foo.error = myerror > > a = foo.func(..)
This general technique is called "monkey patching". > Now, if an error is encountered myerror() is called. Fine. But execution > resumes in func(). Not exactly what I wanted. Of course it does. Your new error handler fails to exit, so execution resumes like it does after any other function. You can either manually exit from your own error handler: def myerror(s): print "new error message" sys.exit(2) or call the original error handler: def myerror(s): print "new error message" foo._error(s) That second technique requires some preparation before hand. In module foo, after defining the error() function, you then need to create a second, private, name to it: _error = error > I can "fix" this simply by wrapping the call to foo.func() in a try/ > expect and have myerror() raise an exception. This appears to work, but > I'm hesitant to use this out of fear that I'm building up some kind of > stack overflow or something which will bite me later. Exceptions are the standard way of doing things. That's what sys.exit() does -- it raises SystemExit exception. With very few exceptions, if you're writing your own error handlers like this, you're doing it wrong. Your error handler throws away useful debugging information, and it gives you no extra information that a standard Python traceback couldn't give. > Is there a better way? Simplest for an old assembler guy like me would > be pop a return address off the stack ... but python isn't assembler :) Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in Python, even VB in Python, but this is the first time I've meet some one who wants to write assembler in Python :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list