0

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()
4
  • 1
    write an async function and inside call add, a module is not a Promise Commented May 6, 2022 at 7:38
  • 1
    Does this answer your question? How to call a async function from a synchronized code Python Commented May 6, 2022 at 7:45
  • @Kemp well it helps to understand the problem but does not answer mine completely. @rioV8 could you elaborate how this would look and why this does not work? It worked for me when I replaced x=await add() with x=add(); await x. Although I would say that both code blocks should be equivalent. Why does one work and the other does not? Commented May 6, 2022 at 11:08
  • my PyLance does not allow x = add(); await x Commented May 6, 2022 at 11:31

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.