Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a coroutine twice in Python?

I have a wrapper function which might run a courutine several times:

async def _request_wraper(self, courutine, attempts=5):
   for i in range(1, attempts):
      try:
         task_result = await asyncio.ensure_future(courutine)
         return task_result
      except SOME_ERRORS:
         do_smth()
         continue 

Corutine might be created from differect async func, which may accept diferent number of necessary/unnecessary arguments. When I have a second loop iteration, I am getting error --> cannot reuse already awaited coroutine

I have tried to make a copy of courutine, but it is not possible with methods copy and deepcopy. What could be possible solution to run corutine twice?

like image 700
Oleksii Avatar asked Sep 13 '25 23:09

Oleksii


1 Answers

As you already found out, you can't await a coroutine many times. It simply doesn't make sense, coroutines aren't functions.

It seems what you're really trying to do is retry an async function call with arbitrary arguments. You can use arbitrary argument lists (*args) and the keyword argument equivalent (**kwargs) to capture all arguments and pass them to the function.

async def retry(async_function, *args, **kwargs, attempts=5):
  for i in range(attempts):
    try:
      return await async_function(*args, **kwargs)
    except Exception:
      pass  # (you should probably handle the error here instead of ignoring it)
like image 113
Tulir Avatar answered Sep 16 '25 12:09

Tulir