[Python-ideas] if expensive_computation() as x:
spir
denis.spir at gmail.com
Fri Feb 14 09:05:01 CET 2014
On 02/13/2014 10: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...
Such a pattern is rather common, eg in some kind of hand-baked parsing. (Say you
have match funcs returning False if no match, True if match but you don't
want/need the result, some "form" having a truth value of True if you need the
form; then you are matching a pattern choice).
Solution 0: for a little and particular choice:
x = expensive_computation_0()
if not x:
x = expensive_computation_1()
if not x:
x = expensive_computation_2()
# assert(x) # or whatever check
Alternative:
x = expensive_computation_0() \
or expensive_computation_1() \
or expensive_computation_2()
# assert(x)
Works due to lazy evaluation of logical operations.
Solution 1: for a big choice, or the general case:
for comp in computations:
x = comp()
if x: break
# assert(x)
However, one must notice that in some way we are here abusing the logical idea
of truth value (of a result, specifically) to make it indcate the success of a
computation. In other words, we are carrying two pieces of information
(result+success) in the same single piece of data.
And the loop version only works if all comp's take no param, or the same one(s),
or you have a parallel array of param sets (in parsing, all match funcs take
source & index).
d
More information about the Python-ideas
mailing list