2

I have to create and use a class derived from an upstream package (not modifiable) I want/need to add/modify a method in the derived class that should be async because i need to await a websocket send/recv in the method I tried just to add async to the method but i get the message (from the base class method) that my method from derived class RuntimeWarning: coroutine MyCopyProgressHandler.end was never awaited Is there a way to "convert" derived class method to async?

Adrian Sevcenco
  • 311
  • 1
  • 8

1 Answers1

1

When you need to convert sync method to async you have several different options. Second one (run_in_executor) is probably the easiest one.

For example, this is how you can make sync function requests.get to run asynchronously:

import asyncio
import requests
from concurrent.futures import ThreadPoolExecutor


executor = ThreadPoolExecutor(10)


async def get(url):
    loop = asyncio.get_running_loop()
    response = await loop.run_in_executor(
        executor, 
        requests.get, 
        url
    )
    return response.text


async def main():
    res = await get('http://httpbin.org/get')
    print(res)


asyncio.run(main())
Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159