Change in scope of handled exception variable in Python 3?

Peter Otten __peter__ at web.de
Fri Dec 31 04:29:03 EST 2010


Baptiste Lepilleur wrote:

> I stumbled on a small bug with httplib2 that I reduced to the example
> below.
> 
> It seems that with Python 3, when an exception is handled it "unbound" the
> previously declared local variable. This did not occurs with Python 2.5.
> 
> It is a Python 3 feature? I did not find anything in the what's news, but
> it's hard to search... (notes: I'm using Python 3.1.2)
> 
> ---
> def main():
>     msg = 'a message'
>     try:
>         raise ValueError( 'An error' )
>     except ValueError as msg:
>         pass
>     return msg
> 
> main()
> 
> python localmask.py
> Traceback (most recent call last):
>   File "localmask.py", line 12, in <module>
>     main()
>   File "localmask.py", line 10, in main
>     return msg
> UnboundLocalError: local variable 'msg' referenced before assignment
> ---

Yes, that's intentional, see

http://docs.python.org/dev/py3k/whatsnew/3.0.html#changes-to-exceptions
http://www.python.org/dev/peps/pep-3110/#semantic-changes




More information about the Python-list mailing list