[Python] Copy a generator

Discussão em 'Python' iniciado por Stack, Novembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    Let's say I have a generator like so

    def gen():
    a = yield "Hello World"
    a_ = a + 1 #Imagine that on my computer "+ 1" is an expensive operation
    print "a_ = ", a_
    b = yield a_
    print "b =", b
    print "a_ =", a_
    yield b


    Now let's say I do

    >>> g = gen()
    >>> g.next()
    >>> g.send(42)
    a_ = 43
    43


    Now we have calculated a_. Now I would like to clone my generator like so.

    >>> newG = clonify(g)
    >>> newG.send(7)
    b = 7
    a_ = 43
    7


    but my original g still works.

    >>> g.send(11)
    b = 11
    a_ = 43
    11


    Specifically, clonify takes the state of a generator, and copies it. I could just reset my generator to be like the old one, but that would require calculating a_. Note also that I would not want to modify the generator extensively. Ideally, I could just take a generator object from a library and clonify it.

    Note: itertools.tee won't work, because it does not handle sends.

    Note: I only care about generators created by placing yield statements in a function.

    Continue reading...

Compartilhe esta Página