Skip to content Skip to sidebar Skip to footer

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 aw

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


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


asyncdefmain():
    res = await get('http://httpbin.org/get')
    print(res)


asyncio.run(main())

Post a Comment for "Make Method Of Derived Class Async"