About a week ago I asked in the help section of this forum how to copy a generator here, hoping that there may be some trick, shortcut or hack to do it even if not “officially supported”, there was no response, so I guess there is really nothing it can be done just yet.
I think this is a feature that may be very useful and was requested directly or indirectly multiple times, there was even a deferred pep more than 20 years ago (PEP 323 – Copyable Iterators | peps.python.org) in this direction.
The lack of this feature produces multiple issues that may look unrelated but affect many users of python. For instance generators can’t be pickled and therefore they can not stored nor passed to a multiprocessing worker or any function that requires pickling. And of course there are also legit use-cases for forking/bifurcating a generator that cannot be solved with itertools.tee.
There is a bunch of questions regarding this topic in SO and other forums, with tens of thousands of views which shows that there would be at least some demand for this feature.
Of course the implementation may be tricky, but I wanted to ask if there would be some interest on supporting this feature.
Edit 1:
Simple yet realistic example where this feature is needed without involving multiprocessing:
def avg():
# online average generator
# in general this generator may come from a package (hard to modify)
i = 1
new = yield None
while True:
new+= yield new/i
i+=1
# keeps the current average of online given data without storing the data
t = avg()
next(t)
t.send(0) # 0/1 =0
t.send(100) # (0+100)/2 = 50
# Imagine that I got a provisional value, and i want a provisional result, here it arises the necessity of a bifurcation.
t_copy = copy(t) # NOT SUPORTED
# provisional value
t_copy.send(100) # (100+ 100)/3 = 66.66666666666667
# after the real data arises I need the definitive result.
# definitive
t.send(80) # (100+ 80)/3 = 60 NOT happening as is not bifurcated
Till now i didn´t find any convincing solution to this problem that can be generalized even for a small subset of generators.
Edit 2:
As noted from @yoavdw this feature already exist in stackless python where you can copy a generator by pickling and unpikling it. It also used to exist in pypy, the functionality was lost in a version change but one of the mantainers recently wrote that they may look into support it again, let’s hope it is not a very complicated task and they are successful to do so.