Scope of variable inside list comprehensions?

Roy Smith roy at panix.com
Mon Dec 5 17:57:43 EST 2011


Sigh.  I attempted to reduce this to a minimal example to focus the discussion on the question of list comprehension variable scope.  Instead I seem to have gotten people off on other tangents.  I suppose I should post more of the real code...

    song_ids = request.POST.getlist('song_id')
    try:
        songs = [Song.get(int(id)) for id in song_ids]
    except Song.DoesNotExist:
        return HttpResponseBadRequest("unknown song id (%d)" % id)

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.



More information about the Python-list mailing list