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

Mathias Panzenböck grosser.meister.morti at gmx.net
Fri Feb 14 04:29:05 CET 2014


Am 2014-02-14 03:58, schrieb Chris Angelico:
> 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...
>
>> 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.
>
> There is another cheat you can do, though, and that's to use break or
> return instead of an elif chain. Going back to your original:
>
>> The code paraphrased is this:
>>
>>      if expensive_computation_0():
>>          x = expensive_computation_0()
>>          # Do something with x...
>>      elif expensive_computation_1():
>>          x = expensive_computation_1()
>>          # Do something with x...
>>      elif expensive_computation_2():
>>          x = expensive_computation_2()
>>          # Do something with x...
>
> the alternative would be something like this:
>
> while "allow_break":
>      x = expensive_computation_0():
>      if x:
>          # Do something with x...
>          break
>      x = expensive_computation_1():
>      if x:
>          # Do something with x...
>          break
>      x = expensive_computation_2():
>      if x:
>          # Do something with x...
>          break
>      # whatever your 'else' clause would be, if any
>      break
>
> Or, using a function instead:
>
> def allow_return():
>      nonlocal everything, you, need
>      x = expensive_computation_0():
>      if x:
>          # Do something with x...
>          return
>      x = expensive_computation_1():
>      if x:
>          # Do something with x...
>          return
>      x = expensive_computation_2():
>      if x:
>          # Do something with x...
>          return
> allow_return()
>
> Both of them are abusing their keywords into gotos, but ultimately,
> that's what if/elif/elif is anyway - as soon as you finish one elif,
> you goto the end of the block. It's not perfect by any means, but it
> works.
>

Or if "Do something with x" is always the same:

x = expensive_computation_0() or expensive_computation_1() or expensive_computation_2()
if x:
	# Do something with x...


More information about the Python-ideas mailing list