Scope of variable inside list comprehensions?
Roy Smith
roy at panix.com
Mon Dec 5 12:04:52 EST 2011
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?
The current docs, http://docs.python.org/tutorial/datastructures.html#list-comprehensions, are mute on this point.
More information about the Python-list
mailing list