Lets say I have a generator function that looks like this:
def fib():
x,y = 1,1
while True:
x, y = y, x+y
yield x
Ideally, I could just use fib()[10] or fib()[2:12:2] to get indexes and slices, but currently I have to use itertools for these things. I can’t use a generator for a drop in replacement for lists.
I believe the solution will be to wrap fib() in a class:
class Indexable(object):
....
fib_seq = Indexable(fib())
What should Indexable look like to make this work?
You could use it like this:
Notice that
it[2:12:2]does not return[3, 8, 21, 55, 144]since the iterator had already advanced 11 elements because of the call toit[10].Edit: If you’d like
it[2:12:2]to return[3, 8, 21, 55, 144]then perhaps use this instead:This version saves the results in
self.already_computedand uses those resultsif possible. Otherwise, it computes more results until it has sufficiently many
to return the indexed element or slice.