Scope of variable inside list comprehensions?

Jussi Piitulainen jpiitula at ling.helsinki.fi
Mon Dec 5 13:04:04 EST 2011


Roy Smith writes:

> Consider the following django snippet.  Song(id) raises DoesNotExist
> if the id is unknown.
> 
>     try:
>         songs = [Song(id) for id in song_ids]
>     except Song.DoesNotExist:
>         print "unknown song id (%d)" % id
> 
> Is id guaranteed to be in scope in the print statement?  I found one
> thread
> (http://mail.python.org/pipermail/python-bugs-list/2006-April/033235.html)
> which says yes, but hints that it might not always be in the future.
> Now that we're in the future, is that still true?  And for Python 3
> also?

Another id is in scope in this Python3 example (3.1.2, Ubuntu):

>>> try:
...    songs = [1/0 for id in [1]]
... except Exception:
...    print('Caught', id)
... 
Caught <built-in function id>



More information about the Python-list mailing list