What happens after return statement?

sismex01 at hebmex.com sismex01 at hebmex.com
Mon Oct 21 10:11:14 EDT 2002


> From: Andreas Jung [mailto:lists at andreas-jung.com]
>
> ... But there is one exception:
> look at the document for try...except...finally.
> 'finally' allows you to specify actions that are
> executed in case of an exception.
> 
> -aj
>

Or even if there was no exception:

def simple(n):
  # Try to return 2*n
  try:
    # But, if "n" is odd, raise exception.
    if n % 2: raise ValueError("Number is odd")
    return 2*n
  finally:
    print "Number:",2*n

This simple function produces this behaviour:

>>> simple(2)
Number: 4
4
>>> simple(4)
Number: 8
8
>>> simple(5)
Number: 10
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in ?
    simple(5)
  File "<pyshell#14>", line 3, in simple
    if n % 2: raise ValueError("Number is odd")
ValueError: Number is odd
>>> simple(1)
Number: 2
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in ?
    simple(1)
  File "<pyshell#14>", line 3, in simple
    if n % 2: raise ValueError("Number is odd")
ValueError: Number is odd
>>> 

So, what's in the "finally" clause get's executed before
exiting the function, even after a "return" statement;
this is kinda neat when playing with threaded functions,
because you can specify that you with to release a lock
inside the finally:

   mutex.acquire()
   try:
      # do some interesting stuff.
      return result
   finally:
      mutex.release()

In this case, the mutex gets released no matter if there
was or there wasn't an exception; this is really cool.

HTH

-gustavo




More information about the Python-list mailing list