[Python-ideas] if with as

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Mar 6 00:00:33 CET 2007

Larry Hastings wrote:

> So the intent for "except E as N" is that N does *not* outlive the 
> "except" block.  And indeed that's what happens in my month-old Py3k.

That's only because the traceback is being attached
to the exception, and there's a desire to avoid
creating a cycle. There are indications that this
idea might be dropped, in which case deleting the
exception would no longer be necessary.

In any case, it's still not really introducing
a new scope, since if you use 'e' anywhere else
in the function, it's the same variable.

> I'm sure people have requested inline 
> assignment zillions of times before.  Since Python does not support it, 
> I'm guessing Guido doesn't want it for some reason.

I believe the main objection is that it would
reintroduce the potential for accidentally

   if a = b:

instead of

   if a == b:

and having it go undetected. Using an 'as' clause
would be one way of avoiding that. Using a different
operator, such as

   if a := b:

would be another way.

A further possible objection is that allowing in-line
assignments anywhere in any expression could lead to
hard-to-follow code. That could be mitigated by only
allowing them in certain places, such as the conditions
of if and while statements.

 > Clearly the original intent with "as" was that it was
 > specifically *not* direct assignment.

Each usage of "as" is unique. It's whatever it needs to
be in each case. In general it's not direct assignment,
but that doesn't mean that some of its uses couldn't be
direct assignment if we wanted.


More information about the Python-ideas mailing list