Pop return from stack?

Thomas Jollans thomas at jollybox.de
Sun Aug 15 01:23:11 CEST 2010


On Sunday 15 August 2010, it occurred to bvdp to exclaim:
> 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(..)
> 
> Now, if an error is encountered myerror() is called. Fine. But
> execution resumes in func(). Not exactly what I wanted.
> 
> 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.

An exception will walk up the stack, calling any cleaning-up code that needs 
to be done (removing object references, executing finally: blocks, exiting 
context managers properly. It won't break anything. Don't be afraid of 
Python's high-level features!

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

Now that has a decent chance of messing things up and you (if you wrote decent 
assembly ;-)) know it -- without properly cleaning up before resuming 
execution in the right place, you could end up in a right state with memory 
leaks, leaked file descriptors, half-arsed database transactions, etc etc. 

> 
> I don't want to change stuff in the foo.py module since it's part of
> an existing program. But, if I must, I suppose I could. I'd prefer to
> just short-circuit this if possible.

Exceptions. Simple. In the end, all system.exit does is raise a SystemExit 
exception...


- Thomas



More information about the Python-list mailing list