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

Ram Rachum ram.rachum at gmail.com
Thu Feb 13 22:59:31 CET 2014


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. 

One solution would be to calculate it and put it in a variable before 
checking truth value. The problem with that is, besides being quite 
verbose, it doesn't work with the `elif` lines. You want to calculate the 
values only if the `elif` branch is being taken. (i.e. you can't do it 
before the `if` because then you might be calculating it needlessly since 
maybe the first condition would be true.)

Obviously this can be "solved", i.e. rewritten in a way that wouldn't call 
the expensive operation twice, but the solution would probably be quite 
verbose, which is something we don't want.

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...

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

What do you think? 


Ram.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140213/dc0ce161/attachment.html>


More information about the Python-ideas mailing list