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


Groups > comp.lang.python > #111791 > unrolled thread

Re: How asyncio works? and event loop vs exceptions

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2016-07-23 08:06 -0600
Last post2016-07-23 08:06 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#111791 — Re: How asyncio works? and event loop vs exceptions

FromIan Kelly <ian.g.kelly@gmail.com>
Date2016-07-23 08:06 -0600
SubjectRe: How asyncio works? and event loop vs exceptions
Message-ID<mailman.80.1469282838.22221.python-list@python.org>
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)

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web