Last active
January 21, 2025 08:05
-
-
Save Menziess/8824932f0dc1e1b7a3340b6e5192ce35 to your computer and use it in GitHub Desktop.
A generator that can be paused by sending a boolean value.
This file contains hidden or 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
"""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