facebook / facebook/pyrefly

support "top" types

Open
#3,736 1 comment 0 reactions 0 assignees View on GitHub
needs-discussion typechecking
Dominant language
Rust
Stars
7k
Forks
516
PR merge metrics
No merged PRs in 30d

Description

ty has a `Top` type which is used to "replace" the `Any`s from any given type with their corresponding "top" type depending on the contex (ie. the variance). see discussion in https://github.com/astral-sh/ty/issues/2943#issuecomment-3988397317:

> ah so a gradual type just means `Any`/`Unknown`?
>
> so does `Top` basically just mean "disable the unsafe behavior of `Any`/`Unknown` of the enclosed type", and is used here to work around the fact that there's no safe way to denote the upper bound of an invariant generic? so like:
>
> * `Top[Any]` is equivalent to `object`
> * `Top[Iterable[Any]]` is equivalent to `Iterable[object]`
> * `Top[Callable[[Any], Any]]` is equivalent to `Callable[[Never], object]`
> * and `Top[list[Any]]` can't be represented any other way

it's especially useful in that last example -- representing types that otherwise cannot be represented in a typesafe way

another example where it comes up is narrowing callable types. in ty, this is an error:

```py
from typing import reveal_type
def f(x: object):
if callable(x):
reveal_type(x) # Top[(...) -> object]
x() # error: Object of type `Top[(...) -> object]` is not safe to call; its signature is not known (call-top-callable)
```
[playground](https://play.ty.dev/ff6aa968-9c68-4e2b-adc4-773993bd608c)

without the `Top`, the parameters `...` are treated as `Any`, which is unsafe: [pyrefly sandbox](https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN2UYANxiooAfSbEYAHSwwwdMAAp8iOrmwArGAGMGASkRy6pzot1ioqbLFVGTZp4JFjJzGPboBiOssIBBnQAtAB8Gtp6DI5OpvjKQT506Lh0MJTUlCAANCBkgmBQpIQMtFAUZAwAFrjowSKUcBC1dAC8dDIgAMyEAIwALJ1yxIJwMPztnXAMlBD6Q%2BgA2umZcAC6cpgwI3qoDDCYbR0gK7ydHehcxFBzEAzBNtOUqPrButZwcEedp5QLVzddHdgldeBNjr9znIAbcGEVgltIOgDg8GDMINgAK77b4nDJnEByGgQT6sNjBOC4TGUXQwXGQwnoFJ1GD4KqoTHTCAiYI0Pa6Kr0-F-Rkpe6CACOmIggkwwQA1jBSA9dLTPkLMgtcNI6pj0MQXvKyRqCRdZXrMBh7pZpiaRWaDharW9apg7s10Haoeg9ci1WhKMrdLQDbNKZ7JnjNSALr69PAA8qpDAXegGk0WpGGbH0IIXuzbHSs8LvXq8wKbLBefyqm9UGMvTG5GX4LgoEJKynMBb0g8oFBGznk3LQXxB82fWMR2wUoJx2nULMMLTeSS%2BQwBfPWB2bnKtsHnqVKI2QABfXIvBjcmAAMWgMAoaCweCIZDPQA)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.