[Python-ideas] the optional "as" statement inside "if" statements

Nick Coghlan ncoghlan at gmail.com
Sat Jun 30 17:06:39 CEST 2012

On Sat, Jun 30, 2012 at 11:59 PM,  <fiatjaf at yahoo.com.br> wrote:
> the idea is to make an variable assignment at the same time that the
> existence of that variable -- which is being returned by a function -- is
> made.
> suppose we are returning a variable from the method 'get' from the 'request'
> object and them making some stuff with it, but that stuff we will only do if
> it exists, if not, we'll just pass, instead of writing:
> variable = self.request.get('variable')
> if variable:
>    print variable
> we could write
> if self.request.get('variable') as variable:
>    print variable
> seems stupid (or not?), but with lots of variables to process, this
> pre-assignment could be very unpleasant -- especially if, as the in the
> example case, very little use will be made of the tested variable.
> also, the "as" expression already exists and is very pythonic.

This proposal has been considered and rejected many times. It's not
general enough - it *only* works for those cases where the value to be
retained *and* the interesting condition are the same.

Consider the simple case of a value that may be either None (not
interesting) or a number (interesting). Since the interesting values
include "0", which evaluates as False along with None, this limited
form of embedded assignment syntax would not help.

Embedded assignment in C isn't that limited., but nobody has yet
volunteered to take the radical step of proposing "(X as Y)" as a
general embedded assignment syntax. I suggest anyone consider such an
idea do a *lot* of research in the python-ideas archives first, though
(as the idea has seen plenty of discussion). It is not as obviously
flawed as the if-and-while statement only variant, but it would still
involve being rather persuasive to make such a significant change to
the language.

You're also unlikely to get much in the way of core developer feedback
until after the 3.3 release in August.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list