Scope of variable inside list comprehensions?

88888 Dihedral dihedral88888 at googlemail.com
Tue Dec 6 05:16:42 EST 2011


On Tuesday, December 6, 2011 2:42:35 PM UTC+8, Rainer Grimm wrote:
> Hello,
> 
> >     try:
> >         songs = [Song(id) for id in song_ids]
> >     except Song.DoesNotExist:
> >         print "unknown song id (%d)" % id
> that's is a bad programming style. So it will be forbidden with python 3. The reason is that list comprehension is a construct from the functional world. It's only syntactic sugar for the functions map and filter. So functions have to be pure functions. To say it in other words, they have to be side-effect free. But the python construct from above pollutes the namespace with name id.
> 
> Greetings from Rottenburg,
> Rainer

The list might have to grow in a careless way that might lead to a crash
in the for inside a list that can't be trapped for errors directly. 




More information about the Python-list mailing list