On 2022-05-15 03:10, Aaron Fink wrote:
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.
I don't see how that could work.
It's still just polling, so it could be expensive to check very often.
All the callback is returning is True/False, which isn't very helpful
for deciding how often it should check.
As for your robotics example, you could adjust the frequency of checking
according to how far it still has to go and how fast it's getting there
- if it won't get anywhere close to the destination in, say, the next
second, there's not much point in checking every 1/60 seconds. There can
be a minimum frequency of checking, and you can increase the frequency
as it gets very close to the destination.
_______________________________________________
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/KXNSV3TBAGPTYGVJVQQZJOGYNFP76HU6/
Code of Conduct: http://python.org/psf/codeofconduct/