Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #111791

Re: How asyncio works? and event loop vs exceptions

From Ian Kelly <ian.g.kelly@gmail.com>
Newsgroups comp.lang.python
Subject Re: How asyncio works? and event loop vs exceptions
Date 2016-07-23 08:06 -0600
Message-ID <mailman.80.1469282838.22221.python-list@python.org> (permalink)
References <CABbU2U-4YaRNkY2KmtSW38B8MoQ+ezmv45hKwSoWGRiFzkSu8w@mail.gmail.com> <CALwzid=uN6mM8iDn9OiiV8LTLOj2Muzpgr9nmJPcjrEtEkRJ2g@mail.gmail.com>

Show all headers | View raw


On Fri, Jul 22, 2016 at 6:27 PM, Marco S. via Python-list
<python-list@python.org> wrote:
> Furthermore I have a question about exceptions in asyncio. If I
> understand well how it works, tasks exceptions can be caught only if
> you wait for task completion, with yield from, await or
> loop.run_until_complete(future). But in this case the coroutine blocks
> the execution of the program until it returns. On the contrary you can
> execute the coroutine inside an asyncio task and it will be
> non-blocking, but in this case exceptions can't be caught in a try
> statement.

If you don't want to block the current function on the task, then spin
off another task to do the error handling.  Instead of this:

async def do_something():
    try:
        await do_something_else()
    except DidNothingError as e:
        handle_error(e)
    ...

Consider this:

async def do_something():
    get_event_loop().create_task(await_and_handle(do_something_else()))
    ...

async def await_and_handle(awaitable):
    try:
        await awaitable
    except DidNothingError as e:
        handle_error(e)

If you want, you could generalize that further by passing in the
exception class and error handler as well:

async def do_something():
    get_event_loop().create_task(await_and_handle(
        do_something_else(), DidNothingError, handle_error))
    ...

async def await_and_handle(awaitable, error_class, handler):
    try:
        await awaitable
    except error_class as e:
        handler(e)

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: How asyncio works? and event loop vs exceptions Ian Kelly <ian.g.kelly@gmail.com> - 2016-07-23 08:06 -0600

csiph-web