<div class="gmail_quote">On Mon, Dec 5, 2011 at 9:04 AM, Roy Smith <span dir="ltr"><<a href="mailto:roy@panix.com">roy@panix.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">

Consider the following django snippet.  Song(id) raises DoesNotExist if the id is unknown.<br>
<br>
    try:<br>
        songs = [Song(id) for id in song_ids]<br>
    except Song.DoesNotExist:<br>
        print "unknown song id (%d)" % id<br>
<br>
Is id guaranteed to be in scope in the print statement?  I found one thread (<a href="http://mail.python.org/pipermail/python-bugs-list/2006-April/033235.html" target="_blank">http://mail.python.org/pipermail/python-bugs-list/2006-April/033235.html</a>) 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?<br>

</blockquote><div><br></div><div>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).</div><div>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.</div>

<div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<br>
The current docs, <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" target="_blank">http://docs.python.org/tutorial/datastructures.html#list-comprehensions</a>, are mute on this point.<br>


<span class="HOEnZb"><font color="#888888">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></span></blockquote></div><br>