1

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()
Manuel
  • 649
  • 5
  • 22
  • write an `async` function and inside call `add`, a module is not a `Promise` – rioV8 May 06 '22 at 07:38
  • Does this answer your question? [How to call a async function from a synchronized code Python](https://stackoverflow.com/questions/51762227/how-to-call-a-async-function-from-a-synchronized-code-python) – Kemp May 06 '22 at 07: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? – Manuel May 06 '22 at 11:08
  • my PyLance does not allow `x = add(); await x` – rioV8 May 06 '22 at 11:31

1 Answers1

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.

rioV8
  • 24,506
  • 3
  • 32
  • 49