Search code examples
pythonasynchronous

How to call an async method from a sync method within a larger async method


As said I want to call an async method from a sync method, the problem is the sync method is being called by another async method so roughly something like this...

async def parent_async()
    sync_method()

def sync_method():
    #call utility_async_method

I can't just call asyncio.run since I'm already in an event loop in this case. The obvious answer would be to just turn my sync_method into an async method, but I don't want to do that for two key reasons.

  1. the sync_method I'm writing is overriding a method in a parent class. The parent method is called all over the place so trying to make it async would require a major refactoring effort
  2. sync_method is called by third party tools. I can't make those third party tools asynchronous.

I'm okay with sync_method blocking briefly while the async method is called, I just need to figure out how to call it.


Solution

  • The package nest-asyncio is for this exact use case. It allows nested use of asyncio.run and loop.run_until_complete

    simply put

    import nest_asyncio
    nest_asyncio.apply()
    

    Before your script.

    I often use it in Jupyter notebooks.