Boolean value of generators
Arnaud Delobelle
arnodel at gmail.com
Fri Oct 15 02:21:37 EDT 2010
Paul Rubin <no.email at nospam.invalid> writes:
> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
>> (4) Expensive generators. The beauty of generators is that they produce
>> values on demand. Making all generators cache their first value means
>> that you pay that cost even if you end up never needing the first value.
>
> You wouldn't generate the cached value ahead of time. You'd just
> remember the last generated value so that you could use it again.
> Sort of like getc/ungetc.
>
> An intermediate measure might be to have a stdlib wrapper that added
> caching like this to an arbitrary generator. I've written such things a
> few times in various clumsy ways. Having the caching available in the C
> code would eliminate a bunch of indirection.
I've done such a thing myself a few times. I remember posting on
python-ideas a while ago (no time to find the thread ATM). My
suggestion was to add a function peekable(it) that returns an iterator
with a peek() method, whose behaviour is exactly the one that you
describe (i.e. similar to getc/ungetc). I also suggested that iterators
could optionally implement a peek() method themselves, in which case
peek(it) would return the iterator without modification. For examples,
list_iterators, str_iterators and other iterators over sequences could
implement next() without any cost. I don't recall that this proposal
gained much traction!
--
Arnaud
More information about the Python-list
mailing list