Adrian Sevcenco
Adrian Sevcenco

Reputation: 311

Make method of derived class async

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?

Upvotes: 2

Views: 794

Answers (1)

Mikhail Gerasimov
Mikhail Gerasimov

Reputation: 39546

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())

Upvotes: 1

Related Questions