py-scopes/scopes/core/actor.py

49 lines
962 B
Python

# scopes.core.actor
import asyncio
QUIT = object()
async def loop(q, bhv):
while True:
msg = await q.get()
if msg == QUIT:
break
bhv = await bhv(msg) or bhv
def create(bhv):
q = asyncio.Queue()
task = asyncio.create_task(loop(q, bhv))
return q, task
# interactive tests
async def handle_basic(msg):
match msg[0]:
case "show": show(msg)
case "switch": return handle_alt
case _: show(msg)
async def handle_alt(msg):
await asyncio.sleep(0.01)
match msg[0]:
case "show": print('no way')
case _: show(msg)
def show(msg):
print(msg)
async def main():
q, task = create(handle_basic)
await q.put(["Hello World!"])
await q.put(["switch"])
await q.put(["show", "nope"])
await q.put(["Hello World!"])
await q.put(QUIT)
#await task
await asyncio.wait([task])
#await asyncio.sleep(10)
def run():
asyncio.run(main())