Scope of variable inside list comprehensions?

Terry Reedy tjreedy at udel.edu
Mon Dec 5 15:22:05 EST 2011


On 12/5/2011 2:15 PM, Roy Smith wrote:
> Hmmm, the use of id was just a simplification for the sake of
> posting.  The real code is a bit more complicated and used a
> different variable name, but that's a good point.
>
> As far as storing the value in the exception, unfortunately,
> DoesNotExist is not my exception; it comes from deep within django.
> I'm just passing it along.

It is hard to sensibly answer a question when the questioner 
*significantly* changes the problem in the process of 'simplifying' it. 
Both of those are significant changes ;-)

Changing a name to a built-in name is a complexification, not a 
simplification, because it introduces new issues that were not in the 
original.

Changing the exception from one you do not control to one you apparently 
do also changes the appropriate answer. If you do not control the 
exception and you want guaranteed access to the loop variable with 
Python 3 (and the upgrade of django to work with Python 3 is more or 
less done), then use an explicit loop. If you want the loop to continue 
after an error, instead of stopping, you can put the try/except within 
the loop, instead of without. This possibility is one advantage of using 
an explicit loop.

songs = []
for song_id in song_ids:
   try:
     songs.append(Song(song_id))
   except django.error:
     print("unknown song id {}".format(song_id))

-- 
Terry Jan Reedy




More information about the Python-list mailing list