python / python/mypy

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

オープン
#21,099 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

feature topic-type-narrowing
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

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:

  1. Understanding bool is a truthyness typeguard. ie roughly treating bool(a) as: def bool[T](a: T | |Literal['', False, 0] | None) -> TypeGuard[T]: ...
  2. 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.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

リンクされた mypy playground から始め、assert_type の例を再現します。要求された 2 つの動作—bool(foo) による truthiness narrowing と、その guard を乗算した inline list の要素型の narrowing—を調査し、例が list[str] をアサーションとして受け入れられたら issue の完了とします。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
静か
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。