[Python-ideas] if expensive_computation() as x:

Jelle Zijlstra jelle.zijlstra at gmail.com
Fri Feb 14 04:34:35 CET 2014


Worth noting that Go has a similar syntax:

if x := expensive_computation(); x < 5 {
   fmt.Println("x is smaller than 5: %d", x)
} else {
   fmt.Println("also have access to x here: %d", x)
}



2014-02-13 19:19 GMT-08:00 Nathan Schneider <nathan at cmu.edu>:
>
> On Thu, Feb 13, 2014 at 9:58 PM, Chris Angelico <rosuav at gmail.com> wrote:
>>
>> Responding to your post in different order to the original.
>>
>> On Fri, Feb 14, 2014 at 8:59 AM, Ram Rachum <ram.rachum at gmail.com> wrote:
>> > If you'd like to bind to a variable only a part of the condition, this
>> > would
>> > work too:
>> >
>> >     if x<5 with expensive_computation_0() as x:
>> >         # Do something with x
>>
>> Definitely don't like this syntax - while it might be useful to
>> snapshot part of a condition (I've done it in C plenty of times), this
>> notation feels clumsy. However...
>>
>>
>
> I agree that a non-clunky way to extract variables from conditions with an
> operator would be nice. Maybe a better syntax would be:
>
>     if (expensive_computation_0() as x)<5:
>
>          # Do something with x
>
> And likewise for `while` loops,
>
>     while (expensive_computation_0() as x)<5:
>
>          # Do something with x
>
>> > My suggestion:
>> >
>> >     if expensive_computation_0() as x:
>> >         # Do something with x...
>> >     elif expensive_computation_1() as x:
>> >         # Do something with x...
>> >     elif expensive_computation_2() as x:
>> >         # Do something with x...
>>
>> ... this simpler form does look reasonable. The "as" part will *only*
>> come at the end of the expression, and it *always* applies to the
>> whole expression, so it's fairly clear.
>
>
> Agreed, this looks reasonable to me.
>
> These are special cases of PEP 379, "Adding an Assignment Expression"
> (http://www.python.org/dev/peps/pep-0379/) from 2009, which has been
> withdrawn. Perhaps it would be better received if restricted to if/while
> conditions.
>
> Nathan
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list