Scope of variable inside list comprehensions?

Chris Kaynor ckaynor at zindagigames.com
Mon Dec 5 13:04:36 EST 2011


On Mon, Dec 5, 2011 at 9:04 AM, Roy Smith <roy at panix.com> wrote:

> 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?
>

In Python2, id will always be in scope, unless the first iteration fails
(aka, an empty iterable, or a custom iterable which raises an exception
before yielding a result).
I believe in Python3, the scoping of list comprehensions was changed to
match that of generator expressions, which is that the loop variable(s)
fall out of scope outside of the expression.


>
> The current docs,
> http://docs.python.org/tutorial/datastructures.html#list-comprehensions,
> are mute on this point.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111205/91094ea0/attachment.html>


More information about the Python-list mailing list