facebook / facebook/pyrefly

Contextual typing using TypeVar union bounds fails

Open
#3,269 0 comments 0 reactions 0 assignees View on GitHub
contextual-typing
Dominant language
Rust
Stars
7k
Forks
519
PR merge metrics
No merged PRs in 30d

Description

### Describe the Bug

Pyrefly is able to use a TypeVar's bound as a contextual hint, like so:
```
class A: ...
class B: ...
class B2(B): ...

def f[T: list[B]](x: T) -> T:
return x

f([B2()]) # this succeeds - pyrefly infers the type of `[B2()]` as `list[B]`
```
([sandbox](https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeSIAxlKnHAAQCCi9hbAOgE7vrW0MAhFm0JcefOvQEAmABQCAlMI7d0YrDDD0wAbQAqLKBDgAXHQIC6F2fhZ6F9ALQA%2BegfX1P9TjBMBXTnR6fHV1MFlzOQULBRAAGhAyHzAoUkITXABbKAoAYnoABVJk1Po0LDx8ekpcdEgAcwDUEwha0XR8gGUYGHoACxMTYjhEAHpRpM1UwlxOetGYdFHMXEo4UZq6iEbOZtal7Vn6VAA3VGhUbFhq2oamltr6XGIH9Dh2shM%2B2scTmE44Pt6ABeejsEAAZkIAEZpOCeDp-pxZnALDw-OgMOhcCZmjBMI5miZOBBsH4TL1QeCAO6oQLgkAAXwSqEoLT%2BADFoDAKOUcAQSORGUA))

However, this fails when the bound is a union:
```
class A: ...
class B: ...
class B2(B): ...

def f[T: list[A] | list[B]](x: T) -> T:
return x

f([B2()]) # Error: `list[B2]` is not assignable to upper bound `list[A] | list[B]` of type variable `T`
```
([sandbox](https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeSIAxlKnHAAQCCi9hbAOgE7vrW0MAhFm0JcefOvQEAmABQCAlMI7d0YrDDD0wAbQAqLKBDgAXHYwC69AD70jpnQIsXZ%2BFnoX0AtAD56B9Xog%2Bk4YEwBXTnR6fHV1MFlHOQULBRAAGhAyULAoUkITXABbKAoAYnoABVIcvPo0LDx8ekpcdEgAc0jUEwg20XQKgGUYGHoACxMTYjhEAHo57M08wlxODrmYdDnMXEo4Odb2iC7OHr7t7TX6VAA3VGhUbFgWts7u3rb6XGJP9DgBmQTOM2l5bjBOHALvQALz0dggADMhAAjNIETwdBDOGs4BYeOF0Bh0LgTD0YJgvD0TJwINhwiYxnCEQB3VBRBEgAC%2BmVQlF64IAYtAYBQGjgCCRyFygA))

More context: https://github.com/facebook/pyrefly/issues/793

### Sandbox Link

_No response_

### (Only applicable for extension issues) IDE Information

_No response_

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.