microsoft / microsoft/pyright

Feature Request: Type-narrowing of a list item for an inline list multiplied with a type-guard on said item

Open
#11,344 0 comments 0 reactions 0 assignees View on GitHub
enhancement request
Dominant language
Python
Stars
15.6k
Forks
1.8k
Avg merge
12h 13m
Merged PRs (30d)
52

Description

If you have a question about a behavior that you’re seeing in pyright, consider posting to the [Pyright discussion forum](https://github.com/microsoft/pyright/discussions).

**Is your feature request related to a problem? Please describe.**

Multiplying an inline list with a typeguard results in `List[Unknown]`. I'm opening this as a feature request, not a bug, as the feature I want is better described by the current title, and `List[Unknown]` seems like an intentional symptom of that missing feature.

Let me quote @jaraco directly, as this is a pattern used a lot in his ecosystem (which includes setuptools): https://github.com/jaraco/jaraco.context/pull/16#discussion_r2967882086
> I very much prefer to use algebraic expressions over branching logic. The expressiveness of multiplying by a bool is important to the aesthetic of simplicity here.

**Describe the solution you’d like**

I would like the following to work:

```py
from typing import assert_type

def _(foo: str | None) -> None:
assert_type(["a", "b", foo] * bool(foo), list[str])
```

playground url: https://pyright-play.net/?code=GYJw9gtgBALgngBwJYDsDmUkQWEMoCGAzkQKZ4D68CpAULQCanBQUAUwYYAXFETCCgAfKADkwKUgEooAWgB8YiaW60o6zCzYAjLgBsOXKVNUazhEuRhVEpQ2AA0fAVLUbiZStTsBtAEQEfk5%2B2kFQnGAAulAAVFC6YAYRUk56SPw%2B-CCRUkA

As shown by the playground, unlike mypy, pyright already does type-narrowing on `bool`, so I'm essentially asking to propagate that type narrowing to inline lists `__mul__'ed with a typeguard.

Contributor guide

Open the contributing guide

Research direction

Reproduce the example in the linked Pyright playground and compare its current List[Unknown] result with the requested list[str] result. Start by tracing the existing bool type-narrowing behavior, then add coverage showing that narrowing is propagated through multiplication of an inline list; done means the assert_type example accepts list[str].

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.