Last active
May 16, 2023 23:11
-
-
Save marvhus/044022d9fd95590ebcfaae790935ca23 to your computer and use it in GitHub Desktop.
Python Coroutines
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
class Coroutine: # I JUST WANT STRUCTS, BUT THIS LANGUAGE WONT LET ME | |
def __init__(self, start, end, name): | |
self.iterator = Coroutine.coroutine(start, end, name) | |
self.is_done = False | |
def next(self): | |
if not self.is_done: | |
self.is_done = next(self.iterator) | |
return self.is_done | |
@staticmethod | |
def from_list(vals): | |
return [ | |
Coroutine(start, end, name) | |
for (start, end, name) in vals | |
] | |
@staticmethod | |
def coroutine(start, end, name): | |
while start < end: | |
print(f"[co - {name}] Doing stuff {start}"); | |
start += 1 | |
yield False # you can return a value if you want | |
print(f"[co - {name}] Done!") | |
yield True | |
coroutines = Coroutine.from_list([ | |
(0, 10, "one "), | |
(10, 19, "two "), | |
(2, 8, "three"), | |
]) | |
not_done = [False] | |
while False in not_done: | |
not_done = [] | |
for co in coroutines: | |
not_done.append( co.next() ) |
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 coroutine(start, end, name): | |
while start < end: | |
print(f"[co - {name}] Doing stuff {start}"); | |
start += 1 | |
yield False # you can return a value if you want | |
yield True | |
iter1 = coroutine(0, 10, "####") | |
iter2 = coroutine(5, 10, "----") | |
iter1_is_done = False | |
iter2_is_done = False | |
while not iter1_is_done or not iter2_is_done: | |
if not iter1_is_done: | |
iter1_is_done = next(iter1) | |
if not iter2_is_done: | |
iter2_is_done = next(iter2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment