So here is my scenario:
def gen1(a):
for item in a:
yield item
def gen2(a):
for item in a:
yield item**2
a = range(10)
g1 = gen1(a)
g2 = gen2(g1)
for item1, item2 in zip(g2, g1):
print(item1, item2)
Output:
0 1
4 3
16 5
36 7
64 9
But I want to get:
0 0
1 1
4 2
9 3
16 4
25 5
36 6
49 7
64 8
81 9
Basically I have several generators that feed through each other doing some streaming transformations on data. However, I then want to go and write some test functions that can look at the input and output streams simultaneously so I can compare them and make sure the results are what I expect. But, I cannot iterate over them in the way I tried above because the iterations get triggered for the bottom iterator twice per loop, messing it all up.
Is there some clever thing I can do to duplicate the input or something to achieve what I want? I supposed I can try to instantiate two copies of the bottom-level iterator, but my real one is rather more complicated to create than the range(10)
in this example, so it would be better to be able to copy it or something. Not sure what the best approach is.