Skip to content

Instantly share code, notes, and snippets.

@benbr8
Last active December 24, 2023 00:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbr8/c75499baa1aa73314e9923abd2e4cd06 to your computer and use it in GitHub Desktop.
Save benbr8/c75499baa1aa73314e9923abd2e4cd06 to your computer and use it in GitHub Desktop.
Everything there is to know about Python async/await (without asyncio)
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()
@waynevanson
Copy link

Thank you, can't believe this kind of stuff isn't the top result on google.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment