Last active
December 24, 2023 00:04
-
-
Save benbr8/c75499baa1aa73314e9923abd2e4cd06 to your computer and use it in GitHub Desktop.
Everything there is to know about Python async/await (without asyncio)
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 Counter: | |
def __init__(self, n=3) -> None: | |
self.n = n | |
self._cnt = 0 | |
def __await__(self): | |
for _ in range(self.n): | |
r = yield self._cnt | |
print(f"incrementing by {r}") | |
self._cnt = r | |
return self._cnt | |
async def await_counter(n): | |
cnt = Counter(n) | |
for _ in range(3): | |
r = await cnt | |
print(f"ok {r}") | |
return r | |
def main(): | |
a = await_counter(5) | |
send = None | |
for i in range(12): | |
print(f"sending... {send}") | |
try: | |
r = a.send(send) | |
send = i 1 | |
print(f"receiving... {r}") | |
except StopIteration as done: | |
print(f"done: {done.value}") | |
break | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, can't believe this kind of stuff isn't the top result on google.