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

spir denis.spir at gmail.com
Fri Feb 14 09:12:45 CET 2014


On 02/14/2014 04:19 AM, Nathan Schneider wrote:
> 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

Isn't this asking for a python variant of C's
     X x;
     if (x = f()) {...}
     for (x = f()) {...}
?

Remember all the critics around such constructs? (IIRC partly, but not only, due 
to the misuse of '=' to mean assignment; the other part is that it is hard to 
think right, intuitively the mix of a computation [f()] and an action 
[assignment] is a single construct; this is also partly why people never check 
the fake error-results of "action-functions")

d


More information about the Python-ideas mailing list