The select() function in pychanio brings Go-style non-deterministic concurrency control to Python’s asyncio. This chapter explores the select block’s design, semantics, and practical usage.
Overview
select() allows a coroutine to wait on multiple channel operations concurrently and react to the first one that becomes ready.
ch = chan() if condition else nil()
result = await select(
(ch >> None, handle_data),
default=lambda: "skip"
)
ch1 = chan()
ch2 = nil() # disable this branch
result = await select(
(ch1 >> None, lambda val, ok: f"got {val}"),
(ch2 >> None, lambda val, ok: "should never be picked"),
timeout=1
)
def handle(val, ok):
if not ok:
return "channel closed"
return f"got {val}"
async def fan_in_consumer(ch1, ch2, done):
while True:
result = await select(
(done >> None, lambda val, ok: DONE if val is DONE or not ok else None),
(ch1 >> None, lambda val, ok: f"ch1: {val}" if ok else "ch1 closed"),
(ch2 >> None, lambda val, ok: f"ch2: {val}" if ok else "ch2 closed"),
default=lambda: "idle",
timeout=1.0,
)
if result == DONE:
print("shutting down")
break
print(result)