Pyright not narrowing list comprehension.
- Dominant language
- Python
- Stars
- 15.6k
- Forks
- 1.8k
- Avg merge
- 12h 13m
- Merged PRs (30d)
- 52
Description
**Describe the bug**
When using a function to change a type inside list comprehension, if the exactly function is unknown statically, pyright says the result of the list comprehensions is a list *with a mix* of types from the possible functions. However, only one function will end up being selected at runtime, so the type should be a list of types from one function, or a list of types from another function.
**Code or Screenshots**
Code sample in [pyright playground](https://pyright-play.net/?code=GYJw9gtgBALgngBwJYDsDmUkQWEMoCCKcAsAFDkDGANgIYDO9UAagKYhLBwAqirA2twC6ALnLkokqABNWwKAH0FqJDCUAKeq2rAANFABuC%2BAlYjYfQUICU5gHQPxZKTLmH2nOJu16oYAEYAVuZEcNZQALQAfFDc9o4UibLyrCj0AK4grMZ80lbqtCAgtHDm1Ej0MPyhQvpGJmYWplZQAD5QAHJgKKxQALyd3azh0VDllfyVIEJtYxVVwmLOUpyGOaaYTChg%2BF09Sy4utNK0CDDs-SweXLzN9XxC6vem1hJS2loHh5LHp%2BcglzYHBulimjymr0SLiyMEyKCg-F%2BZ3YdgM1y8Blo1HCwFwhixmHhhWKcCETiAA)
```python
from typing import Any
class VerifyType[T]:
def __init__(self, v_type: type[T]): ...
def verify(self, obj: Any) -> T: ...
def ensure_typed[T](array: list[Any], v_type: type[T] | None = None) -> list[str] | list[T]:
if v_type is not None:
adapter = VerifyType[v_type](v_type)
else:
adapter = VerifyType[str](str)
return [adapter.verify(val) for val in array]
# ^ Type "list[T@ensure_typed | str]" is not assignable to return type "list[str] | list[T@ensure_typed]" (reportReturnType)
```
Pyright should say the list comprehension lines up with the function signature in this example.
**VS Code extension or command-line**
I'm using basedpyright, but I was able to reproduce this issue in the pyright playground.
Contributor guide
Research direction
Start with the linked Pyright playground example and reproduce the reported list-comprehension diagnostic. Trace the type-inference path for the comprehension and the conditional adapter selection, then verify the example accepts the declared return type without producing a mixed list type.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 50/100