[Python-Dev] Short-circuiting iterators
Raymond Hettinger
raymond.hettinger at verizon.net
Thu Dec 8 05:15:55 CET 2005
[Matthew F. Barnes]
> The ability to remotely terminate a for-loop also struck me as
somewhat
> interesting:
>
> def estimate(item, iterable):
> . . .
> if good_enough:
> iterable.stop()
> return result
>
> for x in iterable:
> . . .
> approx *= estimate(x, iterable)
Good inspiration; wrong technique. For the RightWay(tm), try a
functional approach composing a target calculation with a function
generating successively more accurate approximations and a consumer
function that stops when the desired accuracy is achieved. The idea is
to decouple the steps into side-effect-free, reusable components. For a
worked-out, comprehensive example, see
http://www.md.chalmers.se/~rjmh/Papers/whyfp.pdf .
> But these are highly contrived and hardly compelling.
That suggests an answer to your earlier question as to whether
itertools.interruptable(iterable) would be a useful addition ;-)
Raymond
More information about the Python-Dev
mailing list