In TypeScript, you would do something like
async function getString(word: string): Promise<string> {
return word;
}
How can I do the same in Python? I tried the following:
async def get_string(word: str) -> Coroutine[str]:
return word
And got this traceback:
TypeError: Too few parameters for typing.Coroutine; actual 1, expected 3
So Coroutine
expects 3 types. But why? And what should they be in this case?
This is also specified in the docs, but I still don't understand
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.
Async functions always return an Awaitable, even with a plain return . You only get the actual result by calling await .
To run an async function (coroutine) you have to call it using an Event Loop. Event Loops: You can think of Event Loop as functions to run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses. Example 1: Event Loop example to run async Function to run a single async function: Python3.
The Python return statement is a special statement that you can use inside a function or method to send the function's result back to the caller. A return statement consists of the return keyword followed by an optional return value. The return value of a Python function can be any Python object.
The example in the docs shows what the three types are:
from typing import List, Coroutine c = None # type: Coroutine[List[str], str, int] ... x = c.send('hi') # type: List[str] async def bar() -> None: x = await c # type: int
It also links to the Generator definition with more examples, and a slightly clearer definition:
Generator[YieldType, SendType, ReturnType]
In your case I'd guess [None, None, str]
, as you only care about the awaitable value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With