Hello.

I've been thinking it would be nice to be able to use await to suspend
execution until a condition is met (as represented by a function or lambda
which returns a boolean.

Currently, as far as I can tell, the way to accomplish this is with a while
loop which frequently checks the condition, suspending execution in between
checks. My use case is in robotics, so I'll use that. Here's a minimal
version of my current approach.

start_moving_to(dest)
while distance_to(dest) > tolerance:
    await asyncio.sleep(1 / 60)

This requires choosing a somewhat arbitrary frequency with which to check
the condition. But if the frequency is too high, the function may not be
suspended often enough for other tasks to run and if it's too low, there's
a significant delay before the condition's satisfaction can be noticed.

So here's my proposal for syntax that I think is quite a bit cleaner:

start_moving_to(dest)
await lambda: distance_to(dest) <= tolerance

This eliminates the need to choose a frequency and makes the code even more
readable. Of course, a previously-defined function could be used in place
of a lambda, which would allow for the even cleaner expression

await has_arrived

if has_arrived is already defined.

While I only have a basic understanding of how the event loop works, it
seems to me it should be fairly straightforward to add a list of that pairs
conditions with callbacks and check those conditions on each pass through
the list of registered callbacks, fairly similarly to how scheduled
callbacks created with asyncio.sleep wait until enough time has passed.

Looking forward to hearing people's thoughts.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/BYHSWSIWEOWHVCCTXRKQRKN7KGA33ON6/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to