I was wondering if anyone has a good clean Pythonic and effective method of implementing concepts that include the same defense expression as the result. To be clear, consider the following simple example:
def f(a): print "Calling", a return a + 1 print [ f(v) for v in xrange(3) if f(v) > 1 ]
Will open
Calling 0 Calling 1 Calling 1 Calling 2 Calling 2 [2, 3]
proving that f for most elements is called twice. This is fine, and we want if f has side effects, but if f is some expensive operation without side effects, a duplicate call is undesirable. But a solution that only calls once for each element seems awkward / verbose:
intermediate = ( f(v) for v in xrange(3) ) print [ r for r in intermediate if r > 1 ]
even if it is enclosed in one line
print [ r for r in ( f(v) for v in xrange(3) ) if r > 1 ]
So, can anyone come up with something better?
source share