0

This is for a discord bot I am making, using the discord.py API in which basically everything is done in these async functions.

Lets say I have an async method thats look like this:

async def async_function():
    await something()

and a regular method in which I would like to run the async function:

def regular():
   if condition:
      async_function()

Can I run the async method in a regular method, and if I can, how?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
weeg luigi
  • 23
  • 2
  • 4
  • 1
    Are you expecting the asynchronous function to then run in the background? In most cases where people ask this question, they have unrealistic expectations about what will happen once they do manage to call the asynchronous function - but unless you write some of the rest of your code to deal with asynchronous code, it won't solve your problem. Otherwise: `.run_until_complete(coroutine)` – Grismar Jan 03 '22 at 22:41

1 Answers1

2

You can do this:

import asyncio
def regular():
    if condition:
        asyncio.run(async_function())

Or a decorator approach. Not sure if it is pythonic, but you can also make a decorator if you frequently call a lot of async functions from sync functions. You add this decorator on your async function. Then you can call it in your sync function like you would call another sync function.

def async_decorator(f):
    """Decorator to allow calling an async function like a sync function"""
    @wraps(f)
    def wrapper(*args, **kwargs):
        ret = asyncio.run(f(*args, **kwargs))

        return ret
    return wrapper

@async_decorator
async def async_function():
    await something()

def regular():
    if condition:
        async_function()

Note: You cannot use this approach to nest async functions, I mean call an async function inside another async function.

Sai
  • 58
  • 5
  • 1
    Your decorator approach inhibits the ability to use `async_function` as async. Might as well just remove the `async` from the function definition. – Woodford Jan 03 '22 at 22:45
  • @Woodford You are right, the async function will run synchronously with the rest of the code, but will allow one to do things like async requests inside it using aiohttp or other packages. – Sai Jan 03 '22 at 22:58
  • @GinoMempin Updated. Thank you for suggestion. – Sai Jan 03 '22 at 22:59