I am currently trying to import an (selfwritten) async function in python, but the compiler gives me an error message. See the minimalistic example below (yes I know that in this example async does not really make any sense but for demonstrating purposes I guess it is fine).
In example2.py the complier tells me that ' "await" allowed only within async function Pylance'. If I start the same code in an .ipynb file, the complier still shows the error but if I run it, it works as expected.
My first suspect is that I need to mark the function as async on import but I cannot find anything how I would do this. My other idea is that it is an Editor problem and that I somehow need to define a exception for the complier. But as I am using VS Code I would think that someone would have solved the problem by now.
Does anyone know what the problem is/ how to solve it? I would like to understand why this problem occures.
example.py:
async def add():
return 1 1
example2.py:
from example import add
x =await add()
CodePudding user response:
Reading the Python Async/Await doc
import asyncio
from example import add
x = asyncio.run(add())
print(f'x={x}')
Calling an async
function returns a Promise
.
You have to wait for the Promise generated by calling an async
function.