Sending Values Into Generators

BustACode 0 Tallied Votes 338 Views Share

I just love generators in Python.

One of the cool things I found out from this site was that one could send in a value when calling on an active generator.

To do so one uses the send() method and a yield like so: "x = yield".

The send with a value will assign the sent value to the variable associated with the yield.

I used this once to iterate through my generator once with one set of values, and then later with a different set.

Cool stuff.

# Main #
def main():

        # Main Code
    go_Test = g_Test() ## Create gen. obj. instance
    go_Test.send(None) ## Inits gen. and also sends a "None" value
    go_Test.send(4) ## Sends a 4 to the gen. to start it again, but this 4 is lost, as there is no assign on the "yield"
    go_Test.send(7) ## Sends a 7 to the gen. to run it again.

#-----------Basement------------

def g_Test():
    x = 1
    yield ## First send returns here, but there is no assign so "x" stays "1" and sent "4" is ignored/lost
    while True:
        print("x is: %s") %(x) ## Will print "1", as "4" has been lost.
        x = yield ## Mid-stream yield that will assign to "x" when sent into gen. again.
        print("x is: %s") %(x) ## 7
        yield

    # Main Loop #
if __name__ == '__main__':
    main()