-
Notifications
You must be signed in to change notification settings - Fork 1.5k
[ty] Support async
/await
, async with
and yield from
#19595
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
655b8c3
[ty] Support async/await
sharkdp e7bccbb
Fix async with
sharkdp 7ead318
Add support for yield from
sharkdp 7baf834
StopIteration value
sharkdp 651ac18
Adapt 'upcasting' logic to work for instances of nominal classes that…
sharkdp 9b59414
AlwaysTruthy
sharkdp dbd1419
Just typing
sharkdp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
# `async` / `await` | ||
|
||
## Basic | ||
|
||
```py | ||
async def retrieve() -> int: | ||
return 42 | ||
|
||
async def main(): | ||
result = await retrieve() | ||
|
||
reveal_type(result) # revealed: int | ||
``` | ||
|
||
## Generic `async` functions | ||
|
||
```py | ||
from typing import TypeVar | ||
|
||
T = TypeVar("T") | ||
|
||
async def persist(x: T) -> T: | ||
return x | ||
|
||
async def f(x: int): | ||
result = await persist(x) | ||
|
||
reveal_type(result) # revealed: int | ||
``` | ||
|
||
## Use cases | ||
|
||
### `Future` | ||
|
||
```py | ||
import asyncio | ||
import concurrent.futures | ||
|
||
def blocking_function() -> int: | ||
return 42 | ||
|
||
async def main(): | ||
loop = asyncio.get_event_loop() | ||
with concurrent.futures.ThreadPoolExecutor() as pool: | ||
result = await loop.run_in_executor(pool, blocking_function) | ||
|
||
# TODO: should be `int` | ||
reveal_type(result) # revealed: Unknown | ||
``` | ||
|
||
### `asyncio.Task` | ||
|
||
```py | ||
import asyncio | ||
|
||
async def f() -> int: | ||
return 1 | ||
|
||
async def main(): | ||
task = asyncio.create_task(f()) | ||
|
||
result = await task | ||
|
||
# TODO: this should be `int` | ||
reveal_type(result) # revealed: Unknown | ||
``` | ||
|
||
### `asyncio.gather` | ||
|
||
```py | ||
import asyncio | ||
|
||
async def task(name: str) -> int: | ||
return len(name) | ||
|
||
async def main(): | ||
(a, b) = await asyncio.gather( | ||
task("A"), | ||
task("B"), | ||
) | ||
|
||
# TODO: these should be `int` | ||
reveal_type(a) # revealed: Unknown | ||
reveal_type(b) # revealed: Unknown | ||
``` | ||
|
||
## Under the hood | ||
|
||
```toml | ||
[environment] | ||
python-version = "3.12" # Use 3.12 to be able to use PEP 695 generics | ||
``` | ||
|
||
Let's look at the example from the beginning again: | ||
|
||
```py | ||
async def retrieve() -> int: | ||
return 42 | ||
``` | ||
|
||
When we look at the signature of this function, we see that it actually returns a `CoroutineType`: | ||
|
||
```py | ||
reveal_type(retrieve) # revealed: def retrieve() -> CoroutineType[Any, Any, int] | ||
``` | ||
|
||
The expression `await retrieve()` desugars into a call to the `__await__` dunder method on the | ||
`CoroutineType` object, followed by a `yield from`. Let's first see the return type of `__await__`: | ||
|
||
```py | ||
reveal_type(retrieve().__await__()) # revealed: Generator[Any, None, int] | ||
``` | ||
|
||
We can see that this returns a `Generator` that yields `Any`, and eventually returns `int`. For the | ||
final type of the `await` expression, we retrieve that third argument of the `Generator` type: | ||
|
||
```py | ||
from typing import Generator | ||
|
||
def _(): | ||
result = yield from retrieve().__await__() | ||
reveal_type(result) # revealed: int | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
101 changes: 101 additions & 0 deletions
101
crates/ty_python_semantic/resources/mdtest/expression/yield_and_yield_from.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
# `yield` and `yield from` | ||
|
||
## Basic `yield` and `yield from` | ||
|
||
The type of a `yield` expression is the "send" type of the generator function. The type of a | ||
`yield from` expression is the return type of the inner generator: | ||
|
||
```py | ||
from typing import Generator | ||
|
||
def inner_generator() -> Generator[int, bytes, str]: | ||
yield 1 | ||
yield 2 | ||
x = yield 3 | ||
|
||
# TODO: this should be `bytes` | ||
reveal_type(x) # revealed: @Todo(yield expressions) | ||
|
||
return "done" | ||
|
||
def outer_generator(): | ||
result = yield from inner_generator() | ||
reveal_type(result) # revealed: str | ||
``` | ||
|
||
## `yield from` with a custom iterable | ||
|
||
`yield from` can also be used with custom iterable types. In that case, the type of the `yield from` | ||
expression can not be determined | ||
|
||
```py | ||
from typing import Generator, TypeVar, Generic | ||
|
||
T = TypeVar("T") | ||
|
||
class OnceIterator(Generic[T]): | ||
def __init__(self, value: T): | ||
self.value = value | ||
self.returned = False | ||
|
||
def __next__(self) -> T: | ||
if self.returned: | ||
raise StopIteration | ||
|
||
self.returned = True | ||
return self.value | ||
|
||
class Once(Generic[T]): | ||
def __init__(self, value: T): | ||
self.value = value | ||
|
||
def __iter__(self) -> OnceIterator[T]: | ||
return OnceIterator(self.value) | ||
|
||
for x in Once("a"): | ||
reveal_type(x) # revealed: str | ||
|
||
def generator() -> Generator: | ||
result = yield from Once("a") | ||
|
||
# The `StopIteration` exception might have a `value` attribute which the default of `None`, | ||
# or it could have been customized. So we just return `Unknown` here: | ||
reveal_type(result) # revealed: Unknown | ||
``` | ||
|
||
## Error cases | ||
|
||
### Non-iterable type | ||
|
||
```py | ||
from typing import Generator | ||
|
||
def generator() -> Generator: | ||
yield from 42 # error: [not-iterable] "Object of type `Literal[42]` is not iterable" | ||
``` | ||
|
||
### Invalid `yield` type | ||
|
||
```py | ||
from typing import Generator | ||
|
||
# TODO: This should be an error. Claims to yield `int`, but yields `str`. | ||
def invalid_generator() -> Generator[int, None, None]: | ||
yield "not an int" # This should be an `int` | ||
``` | ||
|
||
### Invalid return type | ||
|
||
```py | ||
from typing import Generator | ||
|
||
# TODO: should emit an error (does not return `str`) | ||
def invalid_generator1() -> Generator[int, None, str]: | ||
yield 1 | ||
|
||
# TODO: should emit an error (does not return `int`) | ||
def invalid_generator2() -> Generator[int, None, None]: | ||
yield 1 | ||
|
||
return "done" | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.