[Python-Dev] capturing RETURN_VALUE

Christian Tismer tismer at stackless.com
Sun Aug 8 19:04:35 CEST 2004


Dear list,

just by chance, I discovered a probably very unknown
feature of the block stack machinery of Python's frames:

--  It is possible to abandon a return statement.  --

My question: Is this an artifact, or can I rely on this
feature to persist for a while (while while >= 1 year) ?

Example code:
I have a code body which either computes and returns a value,
or it raises an exception. Surrounding it, I have a while
true loop, embracing a try..finally block. In case of an
exception, it simply lets the exception pass. In case of a
return value, it intercepts it and can do anything (in the
example, it just decorates the value and returns).

def return_capture(n, do_raise=False):
	_have_value = False
	# outer while loop, just there to get cancelled
	while True:
		try:
			# function body, returning a value or raising
			if do_raise:
				raise ValueError, "was told to raise"
			# signal valid value
			_have_value = True
			retval = n*n
			return
		finally:
			if _have_value:
				break
	# here we end after a captured return, and can do postprocessing
	retval = ("here the captured return value", retval)
	return retval

Sample output:
 >>> return_capture(5)
('here the captured return value', 25)
 >>> return_capture(5, True)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<interactive input>", line 8, in return_capture
ValueError: was told to raise
 >>>


Again the question: Artifact, or a reliable feature?

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at stackless.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  mobile +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/




More information about the Python-Dev mailing list