python / python/mypy

Keep `Literal` after indexing?

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

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

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

説明

EDIT: MWE

from typing import Literal

foo = 0
bar: tuple[Literal[1], ...] = (1,)[foo:]  # error: Incompatible types in assignment (expression has type "tuple[int, ...]", variable has type "tuple[Literal[1], ...]")  [assignment]
baz: tuple[Literal[1], ...] = (1,)[0:]    # OK

bar_fix: tuple[Literal[1], ...] = (1,)    # In two steps...
bar_fix = bar_fix[foo:]                   # ...works fine

Original message

Hi there,

As always, I'm not sure whether I should post on mypy or python typing page. The problem I encounter is the following.

aligns: tuple[Literal["center", "right"], ...] = ("center", "right", "center")[no_extra:]
error: Incompatible types in assignment (expression has type "tuple[str, ...]", variable has type "tuple[Literal['center', 'right'], ...]")  [assignment]
            aligns: tuple[Literal["center", "right"], ...] = ("center", "right", "center")[no_extra:]

where no_extra is a bool. Essentially, I either keep or not the first element with my_tuple[no_extra:], and this makes it into a tuple[str, ...].

Is it normal? If so, is there a recommended practice around it, or should this be a new feature?

Thanks in advance!

All the best.
Élie

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

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

はじめの一歩

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

調査の方向性

まず issue の MWE を再現し、変数インデックスとリテラルインデックスを使ったスライスの推論型を比較します。変数インデックスのスライスがタプルの Literal 要素型を保持し、既存のリテラルインデックスの挙動を後退させなければ、変更は完了です。

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

評価

技術スタック
python
領域
tooling
issue の種類
機能追加
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

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

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