New syntax for blocks

Terry Reedy tjreedy at udel.edu
Wed Nov 11 14:33:09 EST 2009


Steven D'Aprano wrote:

>>> Why is the third example, with an if... test, so special that it needs
>>> special syntax to make it a two-liner?
>> ...because Beautiful is better than ugly.
> 
> I can quote the Zen too:
> 
> Special cases aren't special enough to break the rules.
> 
> You haven't demonstrated that your construct is "beautiful", or the 
> existing way of writing it is "ugly".
> 
> # apparently not ugly
> x = func()
> y = x + 1
> z = 2*x 
> 
> # also not ugly
> var = range(N)
> var.append(42)
> find(23, var)
> 
> # still not ugly
> var = range(N)
> for x in var:
>     do_something_with(x, var)
> 
> # not ugly
> var = MyClass()
> with var.magic as x:
>     process(var)
> 
> 
> # why is this ugly?
> var = range(N)
> if var:
>     process(var)

This is the first time I have seen this explanation and justification of 
the status quo. Thanks for posting it so clearly.

...
> What's so special about "truth-seeking"?

as a second use
> 
> for x in range(N) as var:
>     do_something_with(x, var)
> 
> 
> That would save a line too, it would behave exactly as you specified, and 
> it uses virtually the identical syntax: "expr as name".

I know that Guido does not want to generalize 'as' as a substitute for 
'=' except where really necessary. The three current uses in import, 
with, and except statements are necessary because the object being bound 
is produced in the statement itself and so the assignment cannot be 
separated into a prior proper assignment statement.

Terry Jan Reedy




More information about the Python-list mailing list