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

Ethan Furman ethan at stoneleaf.us
Fri Feb 14 04:47:46 CET 2014


On 02/13/2014 01:59 PM, Ram Rachum wrote:
> Hi everybody,
>
> Please excuse the recent torrent of crazy ideas :)
>
> I was reading code of the Shpaml project, trying to make a patch, while I saw code that looked inelegant to me. I
> considered how to improve it, but then saw I don't know how to.
>
> 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 problem here is that we're doing the expensive computation twice. That's because we first need to check its truth
> value, and if it's true we need to actually use the value and do stuff with it.

Use a pocket function:

def pocket(value=None, _storage=[]):
    if value is not None:
       _storage[:] = [value]
    return _storage[0]

and then:

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

--
~Ethan~


More information about the Python-ideas mailing list