Instagram / Instagram/LibCST

pyright + `__or__` in generic type annotations gives unknown type

Open
#1,143 1 comment 0 reactions 0 assignees View on GitHub
enhancement machinery
Dominant language
Python
Stars
1.9k
Forks
229
PR merge metrics
No merged PRs in 30d

Description

pyright gets confused by your custom `__or__` methods on matcher classes, giving "Expected type expression but received `UnionType`". It does work with mypy, though I suspect that might simply be because mypy doesn't try to parse it for type hints.
It's possible to work around it by using `Union` in types, but that's on its way out & inconvenient.

## repro
```python
from __future__ import annotations

from libcst.matchers import Name
from typing_extensions import reveal_type

# Name.__or__ is broken
l1: list[Name|int] = [Name("foo"), 5]
reveal_type(l1)
# int.__or__ works, but if you want to union multiple matcher types it's not going to help
l2: list[int|Name] = [Name("foo"), 5]
reveal_type(l2)
```
```sh
$ pyright foo.py
./foo.py
./foo.py:8:1 - error: Type of "l1" is partially unknown
  Type of "l1" is "list[Unknown]" (reportUnknownVariableType)
./foo.py:8:10 - error: Expected type expression but received "UnionType" (reportGeneralTypeIssues)
./foo.py:9:13 - information: Type of "l1" is "list[Unknown]"
./foo.py:11:13 - information: Type of "l2" is "list[int | Name]"
2 errors, 0 warnings, 2 informations
```
```sh
$ mypy foo.py
foo.py:7: note: Revealed type is "builtins.list[Union[libcst.matchers.Name, builtins.int]]"
foo.py:9: note: Revealed type is "builtins.list[Union[builtins.int, libcst.matchers.Name]]"
Success: no issues found in 1 source file
```
## versions
libcst 1.3.1
pyright 1.1.362
mypy 1.9.0

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.