Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type
Bryan Olson
fakeaddress at nowhere.org
Wed Aug 31 05:55:59 EDT 2005
Paul Rubin wrote:
> Not every sequence needs __len__; for example, infinite sequences, or
> sequences that implement slicing and subscripts by doing lazy
> evaluation of iterators:
>
> digits_of_pi = memoize(generate_pi_digits()) # 3,1,4,1,5,9,2,...
> print digits_of_pi[5] # computes 6 digits and prints '9'
> print digits_of_pi($-5) # raises exception
Good point. I like the memoize thing, so here is one:
class memoize (object):
""" Build a sequence from an iterable, evaluating as needed.
"""
def __init__(self, iterable):
self.it = iterable
self.known = []
def extend_(self, stop):
while len(self.known) < stop:
self.known.append(self.it.next())
def __getitem__(self, key):
if isinstance(key, (int, long)):
self.extend_(key + 1)
return self.known[key]
elif isinstance(key, slice):
start, stop, step = key.start, key.stop, key.step
stop = start + 1 + (stop - start - 1) // step * step
self.extend_(stop)
return self.known[start : stop : step]
else:
raise TypeError(_type_err_note), "Bad subscript type"
--
--Bryan
More information about the Python-list
mailing list