[Python-ideas] Enabling Event.set to notify all waiters with an exception

Nathaniel Smith njs at pobox.com
Wed Jul 19 14:39:47 EDT 2017


On Jul 18, 2017 11:37 PM, "Pau Freixes" <pfreixes at gmail.com> wrote:

Yeps,


> 'Event' is designed as a lowish-level primitive: the idea is that it
> purely provides the operation of "waiting for something", and then you
> can compose it with other data structures to build whatever
> higher-level semantics you need.

[...]

> But I don't think adding exception-throwing functionality to Event()
> is the right solution :-)

Then I will be forced to make the code stateful, getting as an output
as a complex solution if you compare it with the code that you might
get using the Event()


Not really – the point of the first part of my message is that if you
really want a Future/Event hybrid that can raise an error from 'wait', then
python gives you the tools to implement this yourself, and then you can use
it however you like.

Something like

class ErrorfulOneShotEvent:
    def __init__(self):
        self._event = asyncio.Event()
        self._error = None

    def set(self, error=None):
        self._error = error
        self._event.set()

    async def wait(self):
        await self._event.wait()
        if self._error is not None:
            raise self._error

...and you're good to go.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170719/0f1cfd86/attachment-0001.html>


More information about the Python-ideas mailing list