set/dict comp in Py2.6

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Oct 25 17:44:19 EDT 2008


Sorry for the answering delay, Google Groups is slow today.

Steven D'Aprano:

>Personally, I don't see the advantage of set and dict comprehensions. I think the value of them is very marginal, not worth the additional syntax.<

If it's worth in 3.0 then it's worth in 2.6 too. If it isn't worth in
2.6 then maybe it's not worth in 3.0 too.

It's just a little bit of sugar, and in this specific case I don't see
risk of "diabetes".

I think the dict generator syntax has a small advantage (the set
generator is probably there just for symmetry): it redueces the number
of perenthesys, and replaces a comma with a different symbol (a colon,
this helps you to distinguish the colon itself from the other commas),
this increases readability (Lisp docet).

If the example is very simple like this you don't see much readability
difference:
sqrts = dict((x, x*x) for x in range(1000))
sqrts = {x: x*x for x in range(1000)}

But if those x and x*x need perenthesys then you may see a difference:
sqrts = dict( ((sin(x) + 5) * 3, (x, (x*x, x*x*x))) for x in
range(1000) )
sqrts = {(sin(x) + 5) * 3: (x, (x*x, x*x*x)) for x in range(1000)}

What's the more readable? I think the in second one is much simpler to
tell if it's a correct expression, even after I have added extra
spaces in the first line.


And have you even received this error?

>>> dict(x,x*x for x in xrange(10))
  File "<stdin>", line 1
SyntaxError: Generator expression must be parenthesized if not sole
argument

This syntax avoid that class of errors:
{x:x*x for x in xrange(10)}

So summing up I like the new syntax (I think Fortress language has
something similar).

Bye,
bearophile



More information about the Python-list mailing list