Skip to content

Instantly share code, notes, and snippets.

@nenetto
Created September 26, 2023 07:56
Show Gist options
  • Save nenetto/5998c4e1905b3fc5fcfad508ba055e44 to your computer and use it in GitHub Desktop.
Save nenetto/5998c4e1905b3fc5fcfad508ba055e44 to your computer and use it in GitHub Desktop.
Python Corutines
# 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