Reputation: 13893
In the UDP client example in the Python docs, they use loop.create_future()
to create a new Future
. The main program await
s this future until result is set on it, at which point the program cleans up resources and terminates.
However, I have always used an asyncio.Event
for this kind of thing.
Is there any difference between these two techniques? Is there any reason to prefer the Future instead of the Event?
loop = asyncio.get_running_loop()
future = loop.create_future()
await future
event = asyncio.Event()
await event.wait()
Upvotes: 5
Views: 340
Reputation: 106
They can be both used for synchronization, but a Future has a proper result and can raise exceptions.
So, Event provides less features, but when the use case is only synchronization, it may express the intent better and be less error-prone. In fact, an Event is implemented as a list of futures.
Upvotes: 3