Created
September 26, 2023 07:56
-
-
Save nenetto/5998c4e1905b3fc5fcfad508ba055e44 to your computer and use it in GitHub Desktop.
Python Corutines
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
# Corutines | |
# Extension of generators | |
# They serve like "microservices" | |
def my_corutine(): | |
while True: # Alive microservice | |
received_value = yield # This will freeze the corutine until a value is "send" to it | |
# Do amazing work | |
print("Job done with input", received_value) | |
service = my_corutine() | |
next(service) # This initializes the corutine until next yield | |
service.send(42) | |
# output: "Job done with input 42" | |
## Connect corutines "yield from" | |
# Corutines also can recieve values from other corutines | |
def wrapper(data): | |
"""Generator that yields data row by row""" | |
for row in data: | |
yield row | |
def wrapper(data): | |
"""Generator that yields data row by row""" | |
yield from data | |
# Both functions do the same | |
# Important: when we want to consume from other service/corutine, | |
# you can use yield from to call that corutine and freeze yours | |
# waiting for an answer. Pretty cool uh? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment