[New-bugs-announce] [issue42682] awaiting a wrapped asyncio.Task multiple times gives long, repeative tracebacks

lilydjwg report at bugs.python.org
Sat Dec 19 03:09:24 EST 2020


New submission from lilydjwg <lilydjwg at gmail.com>:

import asyncio

async def crash(key):
  raise Exception('crash!')

async def wait(fu):
  await fu

async def main():
  crasher = asyncio.create_task(crash(()))
  fs = [wait(crasher) for _ in range(10)]
  for fu in asyncio.as_completed(fs):
    try:
      await fu
    except Exception:
      import traceback
      traceback.print_exc()

if __name__ == '__main__':
  asyncio.run(main())

This code will give a very long traceback 10 times. I expect it to be short.

I'm caching the result of an async function like this:

  async def get(
    self,
    key: Hashable,
    func: Callable[[Hashable], Coroutine[Any, Any, Any]],
  ) -> Any:
    async with self.lock:
      cached = self.cache.get(key)
      if cached is None:
        coro = func(key)
        fu = asyncio.create_task(coro)
        self.cache[key] = fu

    if asyncio.isfuture(cached): # pending
      return await cached # type: ignore
    elif cached is not None: # cached
      return cached
    else: # not cached
      r = await fu
      self.cache[key] = r
      return r

It works fine, except that when there is an exception the traceback is very long.

----------
components: asyncio
messages: 383364
nosy: asvetlov, lilydjwg, yselivanov
priority: normal
severity: normal
status: open
title: awaiting a wrapped asyncio.Task multiple times gives long, repeative tracebacks
type: enhancement
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42682>
_______________________________________


More information about the New-bugs-announce mailing list