Async Python code from sync code

About async Python and why do you need it you can find from article Non-sequential Python.

Sometimes you want to call async code from sync evironment like REPL.

Before Python 3.7 it was not easy

import asyncio


async def main():
    print('Hello World!')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
Hello World!

In Python 3.7 we have function asyncio.run

import asyncio


async def main():
    print('Hello World!')


if __name__ == '__main__':
    asyncio.run(main()) 
Hello World!

And in Python 3.8 we even can run REPL in async mode (python -m asyncio).

Suppose the code above is in file sync_async.py:

python -m asyncio
>>> import sync_async
>>> await sync_async.main()
Hello World!