Skip to content

Runnify - Async Code With Arguments

Continuing with the last example, let's see the first use case where Asyncer could be useful. 🤓

Async Main Function with Arguments

Let's say that now you want your async main() function to take arguments:

# Code above omitted 👆

async def main(name: str):
    result = await do_work(name=name)
    return result

# Code below omitted 👇
👀 Full file preview
import anyio
import asyncer


async def do_work(name: str):
    await anyio.sleep(1)
    return f"Hello, {name}"


async def main(name: str):
    result = await do_work(name=name)
    return result


result = asyncer.runnify(main)(name="World")
print(result)

Runnify with Arguments

Now you can use asyncer.runnify() to run this function passing arguments:

# Code above omitted 👆

result = asyncer.runnify(main)(name="World")

# Code below omitted 👇
👀 Full file preview
import anyio
import asyncer


async def do_work(name: str):
    await anyio.sleep(1)
    return f"Hello, {name}"


async def main(name: str):
    result = await do_work(name=name)
    return result


result = asyncer.runnify(main)(name="World")
print(result)

asyncer.runnify() takes the async function you want to call, and then it returns another function that takes the positional and keyword arguments needed, in this case it's just name="World".

When you call that function with the arguments, it actually uses anyio.run() underneath to run the async function with the arguments.

And here's the advantage of this approach, you get better typing support.

For example, you will get editor autocompletion:

And you will get editor inline errors:

You will also get mypy support if you use it.

Run the Program in the Command Line

If you run that, you will see the expected result, almost the same as with AnyIO, it will wait for 1 second and then print Hello, World:

$ python main.py

// Wait for it...

// After around one second
Hello, World

Next Steps

I'll show you next how to mix async code and regular (sync, blocking) code. 😎