Last active
May 15, 2017 13:46
-
-
Save scukonick/2ef6d8303a785e45060a64b868664ce0 to your computer and use it in GitHub Desktop.
Python - playing with send function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def gen(): | |
print("running up to yield!") | |
while 1: | |
# Receiving value from 'send' | |
x = yield | |
print("Incoming: {}".format(x)) | |
if x is None: | |
print("Exiting") | |
break | |
doubled = x * 2 | |
print("Yielding: {}".format(doubled)) | |
# yielding back doubled value. | |
# This value would be used as result of send function | |
yield doubled | |
yield # final yield in case if None received | |
print("Creating generator") | |
g = gen() | |
print("Calling next!") | |
next(g) | |
print("Sending: 5") | |
received = g.send(5) | |
print("Received {}".format(received)) | |
next(g) | |
print("Sending: 3") | |
received = g.send(3) | |
print("Received {}".format(received)) | |
next(g) | |
print("Sending: 10") | |
received = g.send(10) | |
print("Received {}".format(received)) | |
next(g) | |
print("Sending: None") | |
received = g.send(None) | |
print("Received {}".format(received)) | |
# output | |
""" | |
Creating generator | |
Calling next! | |
running up to yield! | |
Sending: 5 | |
Incoming: 5 | |
Yielding: 10 | |
Received 10 | |
Sending: 3 | |
Incoming: 3 | |
Yielding: 6 | |
Received 6 | |
Sending: 10 | |
Incoming: 10 | |
Yielding: 20 | |
Received 20 | |
Sending: None | |
Incoming: None | |
Exiting | |
Received None | |
Process finished with exit code 0 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment