[Python-ideas] if expensive_computation() as x:
Michele Lacchia
michelelacchia at gmail.com
Fri Feb 14 07:49:02 CET 2014
You could gather all the functions in a list and then iterate and break
when needed:
for func in [f1, f2, f3, f4]:
x = func()
if x:
# bla bla
break
Sorry for the indentation if it's not right, I'm writing from my phone.
Il 14/feb/2014 03:40 "Ram Rachum" <ram.rachum at gmail.com> ha scritto:
> 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.
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140214/68419cb7/attachment-0001.html>
More information about the Python-ideas
mailing list