Scope of variable inside list comprehensions?

Chris Angelico rosuav at gmail.com
Mon Dec 5 21:35:45 EST 2011


On Tue, Dec 6, 2011 at 9:57 AM, Roy Smith <roy at panix.com> wrote:
> I may be in the minority here, but it doesn't bother me much that my use of 'id' shadows a built-in.  Especially in small scopes like this, I use whatever variable names make the the code easiest to read and don't worry about shadowing builtins.  I don't have an exhaustive list of builtins in my head, so even if I worried about common ones like file or id, I'm sure I'd miss some others.  So I don't sweat it.
>
> If shadowing builtins was really evil, they'd be reserved keywords and then you wouldn't be able to do it.

Agreed. The name 'id' is one that's shadowed benignly in a lot of
code. In the context of the original question, it's not an issue -
there'll be no confusion.

Python's scoping rules are "do what the programmer probably wants".
This works most of the time, but occasionally you get edge cases where
things are a bit weird, and C-style explicit scoping (with infinitely
nested block scope) begins to look better. But for probably 99% of
situations, Python's system "just works".

If you need more flexibility in the exception you throw, it may be
worth putting together a filter:

def HttpSongId(id):
   try:
       return Song.get(int(id))
   except Song.DoesNotExist:
       return HttpResponseBadRequest("unknown song id (%d)" % id)

   song_ids = request.POST.getlist('song_id')
   songs = [HttpSongId(id) for id in song_ids]

This encapsulates things in a somewhat weird way, but if there's any
other work to be done at the same time, you could probably come up
with a better name for the exception filter function.

ChrisA



More information about the Python-list mailing list