-
Notifications
You must be signed in to change notification settings - Fork 1.4k
[ty] Add partial support for TypeIs
#18294
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
Closed
Closed
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
62bb243
[ty] Add partial support for `TypeIs`
InSyncWithFoo b740815
Formatting
InSyncWithFoo 874818b
Do not report calls with unrecognized targets
InSyncWithFoo a5da083
Address failing tests
InSyncWithFoo bc17256
Remove `dbg!()`
InSyncWithFoo a451a16
Update docs/schema
InSyncWithFoo 4379dd4
Formatting
InSyncWithFoo 62c14df
Formatting
InSyncWithFoo f894e8d
Bound `TypeIs` types are singleton/single-valued
InSyncWithFoo ef3d3eb
Account for non-fully-static `TypeIs` types in `is_assignable_to()`
InSyncWithFoo 90f93c7
Fix
InSyncWithFoo ea0d9d6
Merge branch 'main' into ty-typeis
InSyncWithFoo 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
Large diffs are not rendered by default.
Oops, something went wrong.
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
264 changes: 264 additions & 0 deletions
264
crates/ty_python_semantic/resources/mdtest/narrow/type_guards.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,264 @@ | ||
# User-defined type guards | ||
|
||
User-defined type guards are functions of which the return type is either `TypeGuard[...]` or | ||
`TypeIs[...]`. | ||
|
||
## Display | ||
|
||
```py | ||
from ty_extensions import Intersection, Not, TypeOf | ||
from typing_extensions import TypeGuard, TypeIs | ||
|
||
def _( | ||
a: TypeGuard[str], | ||
b: TypeIs[str | int], | ||
c: TypeGuard[Intersection[complex, Not[int], Not[float]]], | ||
d: TypeIs[tuple[TypeOf[bytes]]], | ||
e: TypeGuard, # error: [invalid-type-form] | ||
f: TypeIs, # error: [invalid-type-form] | ||
): | ||
# TODO: Should be `TypeGuard[str]` | ||
reveal_type(a) # revealed: @Todo(`TypeGuard[]` special form) | ||
reveal_type(b) # revealed: TypeIs[str | int] | ||
# TODO: Should be `TypeGuard[complex & ~int & ~float]` | ||
reveal_type(c) # revealed: @Todo(`TypeGuard[]` special form) | ||
reveal_type(d) # revealed: TypeIs[tuple[<class 'bytes'>]] | ||
reveal_type(e) # revealed: Unknown | ||
reveal_type(f) # revealed: Unknown | ||
|
||
# TODO: error: [invalid-return-type] "Function always implicitly returns `None`, which is not assignable to return type `TypeGuard[str]`" | ||
def _(a) -> TypeGuard[str]: ... | ||
|
||
# error: [invalid-return-type] "Function always implicitly returns `None`, which is not assignable to return type `TypeIs[str]`" | ||
def _(a) -> TypeIs[str]: ... | ||
def f(a) -> TypeGuard[str]: | ||
return True | ||
|
||
def g(a) -> TypeIs[str]: | ||
return True | ||
|
||
def _(a: object): | ||
# TODO: Should be `TypeGuard[a, str]` | ||
reveal_type(f(a)) # revealed: @Todo(`TypeGuard[]` special form) | ||
reveal_type(g(a)) # revealed: TypeIs[a, str] | ||
``` | ||
|
||
## Parameters | ||
|
||
A user-defined type guard must accept at least one positional argument (in addition to `self`/`cls` | ||
for non-static methods). | ||
|
||
```pyi | ||
from typing_extensions import TypeGuard, TypeIs | ||
|
||
# TODO: error: [invalid-type-guard-definition] | ||
def _() -> TypeGuard[str]: ... | ||
|
||
# TODO: error: [invalid-type-guard-definition] | ||
def _(**kwargs) -> TypeIs[str]: ... | ||
|
||
class _: | ||
# fine | ||
def _(self, /, a) -> TypeGuard[str]: ... | ||
@classmethod | ||
def _(cls, a) -> TypeGuard[str]: ... | ||
@staticmethod | ||
def _(a) -> TypeIs[str]: ... | ||
|
||
# errors | ||
def _(self) -> TypeGuard[str]: ... # TODO: error: [invalid-type-guard-definition] | ||
def _(self, /, *, a) -> TypeGuard[str]: ... # TODO: error: [invalid-type-guard-definition] | ||
@classmethod | ||
def _(cls) -> TypeIs[str]: ... # TODO: error: [invalid-type-guard-definition] | ||
@classmethod | ||
def _() -> TypeIs[str]: ... # TODO: error: [invalid-type-guard-definition] | ||
@staticmethod | ||
def _(*, a) -> TypeGuard[str]: ... # TODO: error: [invalid-type-guard-definition] | ||
``` | ||
|
||
For `TypeIs` functions, the narrowed type must be assignable to the declared type of that parameter, | ||
if any. | ||
|
||
```pyi | ||
from typing import Any | ||
from typing_extensions import TypeIs | ||
|
||
def _(a: object) -> TypeIs[str]: ... | ||
def _(a: Any) -> TypeIs[str]: ... | ||
def _(a: tuple[object]) -> TypeIs[tuple[str]]: ... | ||
def _(a: str | Any) -> TypeIs[str]: ... | ||
def _(a) -> TypeIs[str]: ... | ||
|
||
# TODO: error: [invalid-type-guard-definition] | ||
def _(a: int) -> TypeIs[str]: ... | ||
|
||
# TODO: error: [invalid-type-guard-definition] | ||
def _(a: bool | str) -> TypeIs[int]: ... | ||
``` | ||
|
||
## Arguments to special forms | ||
|
||
`TypeGuard` and `TypeIs` accept exactly one type argument. | ||
|
||
```py | ||
from typing_extensions import TypeGuard, TypeIs | ||
|
||
a = 123 | ||
|
||
# TODO: error: [invalid-type-form] | ||
def f(_) -> TypeGuard[int, str]: ... | ||
|
||
# error: [invalid-type-form] | ||
def g(_) -> TypeIs[a, str]: ... | ||
|
||
# TODO: Should be `Unknown` | ||
reveal_type(f(0)) # revealed: @Todo(`TypeGuard[]` special form) | ||
reveal_type(g(0)) # revealed: Unknown | ||
``` | ||
|
||
## Return types | ||
|
||
All code paths in a type guard function must return booleans. | ||
|
||
```py | ||
from typing_extensions import Literal, TypeGuard, TypeIs, assert_never | ||
|
||
def _(a: object, flag: bool) -> TypeGuard[str]: | ||
if flag: | ||
return 0 | ||
|
||
return "foo" | ||
|
||
# error: [invalid-return-type] "Function can implicitly return `None`, which is not assignable to return type `TypeIs[str]`" | ||
def f(a: object, flag: bool) -> TypeIs[str]: | ||
if flag: | ||
# error: [invalid-return-type] "Return type does not match returned value: expected `TypeIs[str]`, found `float`" | ||
return 1.2 | ||
|
||
def g(a: Literal["foo", "bar"]) -> TypeIs[Literal["foo"]]: | ||
if a == "foo": | ||
# Logically wrong, but allowed regardless | ||
return False | ||
|
||
return False | ||
``` | ||
|
||
## Invalid calls | ||
|
||
```py | ||
from typing import Any | ||
from typing_extensions import TypeGuard, TypeIs | ||
|
||
def f(a: object) -> TypeGuard[str]: | ||
return True | ||
|
||
def g(a: object) -> TypeIs[int]: | ||
return True | ||
|
||
def _(d: Any): | ||
if f(): # error: [missing-argument] | ||
... | ||
|
||
# TODO: Is this error correct? | ||
InSyncWithFoo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if g(*d): # error: [missing-argument] | ||
... | ||
|
||
if f("foo"): # TODO: error: [invalid-type-guard-call] | ||
... | ||
|
||
if g(a=d): # error: [invalid-type-guard-call] | ||
... | ||
|
||
def _(a: tuple[str, int] | tuple[int, str]): | ||
if g(a[0]): | ||
# TODO: Should be `tuple[str, int]` | ||
InSyncWithFoo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
reveal_type(a) # revealed: tuple[str, int] | tuple[int, str] | ||
``` | ||
InSyncWithFoo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
## Narrowing | ||
|
||
```py | ||
from typing import Any | ||
from typing_extensions import TypeGuard, TypeIs | ||
|
||
def guard_str(a: object) -> TypeGuard[str]: | ||
return True | ||
|
||
def is_int(a: object) -> TypeIs[int]: | ||
return True | ||
|
||
def _(a: str | int): | ||
if guard_str(a): | ||
# TODO: Should be `str` | ||
reveal_type(a) # revealed: str | int | ||
else: | ||
reveal_type(a) # revealed: str | int | ||
|
||
if is_int(a): | ||
reveal_type(a) # revealed: int | ||
else: | ||
reveal_type(a) # revealed: str & ~int | ||
|
||
def _(a: str | int): | ||
b = guard_str(a) | ||
c = is_int(a) | ||
|
||
reveal_type(a) # revealed: str | int | ||
# TODO: Should be `TypeGuard[a, str]` | ||
reveal_type(b) # revealed: @Todo(`TypeGuard[]` special form) | ||
reveal_type(c) # revealed: TypeIs[a, int] | ||
|
||
if b: | ||
# TODO: Should be `str` | ||
reveal_type(a) # revealed: str | int | ||
else: | ||
reveal_type(a) # revealed: str | int | ||
|
||
if c: | ||
reveal_type(a) # revealed: int | ||
else: | ||
reveal_type(a) # revealed: str & ~int | ||
|
||
def _(x: str | int, flag: bool) -> None: | ||
b = is_int(x) | ||
reveal_type(b) # revealed: TypeIs[x, int] | ||
|
||
if flag: | ||
x = "" | ||
|
||
if b: | ||
# TODO: Should be `str | int` | ||
InSyncWithFoo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
reveal_type(x) # revealed: int | ||
``` | ||
|
||
## `TypeGuard` special cases | ||
|
||
```py | ||
from typing import Any | ||
from typing_extensions import TypeGuard, TypeIs | ||
|
||
def guard_int(a: object) -> TypeGuard[int]: | ||
return True | ||
|
||
def is_int(a: object) -> TypeIs[int]: | ||
return True | ||
|
||
def does_not_narrow_in_negative_case(a: str | int): | ||
if not guard_int(a): | ||
# TODO: Should be `str` | ||
reveal_type(a) # revealed: str | int | ||
else: | ||
reveal_type(a) # revealed: str | int | ||
|
||
def narrowed_type_must_be_exact(a: object, b: bool): | ||
if guard_int(b): | ||
# TODO: Should be `int` | ||
reveal_type(b) # revealed: bool | ||
|
||
if isinstance(a, bool) and is_int(a): | ||
reveal_type(a) # revealed: bool | ||
|
||
if isinstance(a, bool) and guard_int(a): | ||
# TODO: Should be `int` | ||
reveal_type(a) # revealed: bool | ||
``` |
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.