简体   繁体   中英

Can not import async function from module in python

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM