Added documentation about higher-order functions.

This commit is contained in:
Eric Traut 2023-06-18 00:00:06 -07:00
parent 42a37f4b98
commit 2de35e3684

View File

@ -346,6 +346,29 @@ def func2(x: list[int], y: list[str] | int):
reveal_type(v2) # pyright: "list[int | str]" ("list[list[str] | int]" is also a valid answer)
```
#### Constraint Solver: Higher-order Functions
If a generic higher-order function is passed another generic callable as an argument, pyright is able to solve the type variables for both the target function and the argument. Mypy isnt able to handle higher-order functions.
```python
def identity(val: T) -> T:
return val
def higher_order1(cb: Callable[[S], T], arg: S) -> T:
return cb(arg)
v1 = higher_order1(identity, 1.0) # mypy generates an error
reveal_type(v1) # mypy: T, pyright: float
def higher_order2(cb: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R:
return cb(*args, **kwargs)
v2 = higher_order2(identity, "") # mypy generates an error
reveal_type(v2) # mypy: T, pyright: str
```
### Constrained Type Variables