New syntax for blocks

Steven D'Aprano steven at
Wed Nov 11 08:25:35 CET 2009

On Tue, 10 Nov 2009 23:00:09 -0800, r wrote:

> I think what has escaped everyone (including myself until my second
> post) is the fact that what really needs to happen 


> is for variable
> *assignments* to return a boolean to any "statements" that evaluate the
> assignment -- like in an "if" or "elif" construct.

I don't even understand what that means.

> The current "with"
> statement cannot replace that action and was never meant for such
> things.
> if range(0) as var:
>    #python will never execute even one line 
>    #in this block because bool(var) == None

No, that's impossible. bool() always returns True or False, not None.

>    #also since bool(var) equals None, the 


>>> True == None
>>> False == None

>    #variable "var" will never be created!

That will cause no end of trouble.

if range(N) as var:
if var:
    print "Oops, this blows up if N <= 0"

Conditional assignments are a terrible idea.

> elif range(10) as var:
>    #this block will execute and the variable "var" 
>    #will be added to appropriate namespace containing 
>    #a list of 10 ints
> var = 100 #var is still available in this namespace!
> Very clean, very elegant solution to a messy problem that pops up in
> python code quite often. 

You haven't actually explained what the messy problem is.

var = range(N)
if var:

is not a messy problem. It's perfectly reasonable. If you need to do two 
things with a value, you assign it to a name first:

var = range(N)
p = var.index(5)

x = func(10)
y = x + 1
z = x*2

x = func(10)
if x:
    y = x + 1

Why is the third example, with an if... test, so special that it needs 
special syntax to make it a two-liner?

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.

> It not only saves one distracting line of code
> per usage but makes the code more readable.

What distracting line of code?


More information about the Python-list mailing list