Empty collection not narrowing type for aesthetic oneliners
- Dominant language
- Python
- Stars
- 15.6k
- Forks
- 1.8k
- Avg merge
- 12h 13m
- Merged PRs (30d)
- 52
Description
I recently came across two scenarios where pyright in strict mode makes it hard to write a oneliner.
1. Optionally add an element into a collection
2. Merging a list of collections into one large collection
```python
# pyright: strict
optional = True
a = {"a", "b"} | {"c"} if optional else set()
b = set().union({"a"}, {"b"}, {"c"})
```
There is a type mismatch is the same in both cases:
An empty set has type set[Unknown] but these are temporary objects so the unknown can never become a problem. Mypy for example doesn't care about this.
I would find it nice if this was accepted by pyright.
I found a work around for case 2 but not case 1.
```python
from itertools import chain
b = set(chain(({"a"}, {"b"}, {"c"}))
```
I would understand if this doesn't make sense for pyright because the type checker encourages more explicit code, in this case the problem would be solved by simply using an if statement and spreading the logic over several lines. I wouldn't want to add complexity to the project. I don't know how pyright works internally but I thought maybe supporting this use case would be beneficial in more ways I can't see.
Contributor guide
Research direction
No source files, tests, or entry points are named. Start by reproducing both strict-mode examples in Pyright and tracing how the empty set is inferred in each expression; done means the reported type mismatches are resolved without weakening strict checking.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- developer-experience, tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100