New syntax for blocks

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Nov 11 03:37:35 EST 2009


On Wed, 11 Nov 2009 00:08:58 -0800, r wrote:


>> >    #variable "var" will never be created!
>> That will cause no end of trouble.
>> if range(N) as var:
>>     do_something_with_var()
>> if var:
>>     print "Oops, this blows up if N <= 0"
>> Conditional assignments are a terrible idea.
> 
> Yea it's called a NameError. Would it not also blow up in the current
> state of syntax usage?

No.


> if var:
>     print 'var'
> 
> Traceback (most recent call last):
>   File "<pyshell#45>", line 1, in <module>
>     if var:
> NameError: name 'var' is not defined


You missed a line:

var = range(N)
if var:
    ...

The problem isn't the if statement, it is the conditional assignment. 
Sometimes "x as y" creates y, sometimes it doesn't, according to some 
mysterious rule something to do without whether the assignment is true or 
false, whatever that means.



>> 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)





>> Would you suggest we can write this?
>> # instead of var = range(N)
>> p = range(N).index(5) as var  # var might be range(N), or undefined.
>> var.append(42)
> 
> No if you read my post my usage of this syntax only includes "if" and
> "elif" constructs and nothing "else" because usage outside of such a
> "truth-seeking" construct is pointless.

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

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".



-- 
Steven



More information about the Python-list mailing list