Skip to content

Instantly share code, notes, and snippets.

@Menziess
Last active January 21, 2025 08:05
Show Gist options
  • Save Menziess/8824932f0dc1e1b7a3340b6e5192ce35 to your computer and use it in GitHub Desktop.
Save Menziess/8824932f0dc1e1b7a3340b6e5192ce35 to your computer and use it in GitHub Desktop.
A generator that can be paused by sending a boolean value.
"""Pausable generator."""
import asyncio
SENTINEL = object()
async def gen():
active = True
for n in range(100):
if not active:
print('generator paused')
while True:
active = (
yield SENTINEL
)
if active:
break
await asyncio.sleep(1)
active = (
yield n
)
async def main():
g = gen()
await g.asend(None) # prime generator
for active in (True, True, False, True, True):
result = await g.asend(active)
if result is SENTINEL:
continue
print('result', result)
if __name__ == '__main__':
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment