Type-narrowing of a list item for an inline list multiplied with a type-guard on said item
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit dem verlinkten mypy playground und reproduziere das assert_type-Beispiel. Untersuche die beiden angeforderten Verhaltensweisen—die Eingrenzung anhand der Wahrhaftigkeit durch bool(foo) und die Eingrenzung des Elementtyps einer Inline-Liste, die mit diesem Guard multipliziert wird—und betrachte das Issue als abgeschlossen, wenn das Beispiel mit list[str] als Assertion akzeptiert wird.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Ruhig
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100