Type-narrowing of a list item for an inline list multiplied with a type-guard on said item
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Feature
I would like the following to work:
from typing import assert_type
def _(foo: str | None) -> None:
assert_type(["a", "b", foo] * bool(foo), list[str])
playground url: https://mypy-play.net/?gist=f6454b1662920bc8df00dfe047a80044
To my understanding, this would require 2 things that mypy currently doesn't do as shown by the above playground:
- Understanding
boolis a truthyness typeguard. ie roughly treatingbool(a)as:def bool[T](a: T | |Literal['', False, 0] | None) -> TypeGuard[T]: ... - Doing type-narrowing on
list.__mul__with a type-guard.
Pitch
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked mypy playground and reproduce the assert_type example. Investigate the two requested behaviors—truthiness narrowing through bool(foo) and narrowing the element type of an inline list multiplied by that guard—and consider the issue complete when the example is accepted with list[str] as asserted.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100