python / python/mypy

Nondeterministic type-var error with LiteralString-bounded TypeVars

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

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

bug
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

After upgrading from mypy 1.19.0 to 1.19.1, we're experiencing nondeterministic type checking behavior:

  1. Without type: ignore[type-var]: Sometimes reports "Value of type variable 'S' of 'Response' cannot be 'object'" [type-var]
  2. With type: ignore[type-var]: Sometimes reports "Unused 'type: ignore[type-var]' comment" [unused-ignore]

The error state is inconsistent and appears related to PR #20345 (which fixed issue #20344 about nondeterministic behavior with tuple type vars).

Environment

  • Mypy version: 1.19.1
  • Python version: 3.13
  • Upgraded from: mypy 1.19.0 (no errors)

Example

Granted, this is a simplified, sanitized example I have extracted from our code base but I believe it highlights the case where the issue is happening

from typing import LiteralString


class Container[S: LiteralString, T]:
    """A container with a LiteralString key."""

    def __init__(self, key: S, value: T) -> None:
        self.key = key
        self.value = value


class Response[S: LiteralString, T]:
    """A response parameterized by LiteralString."""

    def __init__(self, container: Container[S, T]) -> None:
        self.container = container


def process[S: LiteralString, S1: LiteralString](
    containers: list[Container[S, int] | Container[S1, str]],
) -> dict[int, Response]:
    """Create responses from a union of containers with different LiteralString keys."""
    return {
        i: Response(container)  # May error: type-var or unused-ignore
        for i, container in enumerate(containers)
    }
Scenario 1: With type: ignore[type-var] comment
example.py:28: error: Unused "type: ignore[type-var]" comment  [unused-ignore]
Scenario 2: Without the comment (in different contexts)

Sometimes passes with no errors, sometimes shows:

example.py:28: error: Value of type variable "S" of "Response" cannot be "object"  [type-var]

I'm not able to nail down exactly when each scenario surfaces but hopefully this is enough to go on as it otherwise presents as a regression since 1.19.0

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

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

はじめの一歩

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

調査の方向性

まず、付属の例を mypy 1.19.0 と 1.19.1 で、コメント type: ignore[type-var] がある場合とない場合の両方について実行し、診断結果を比較します。関連する tuple の type-var の非決定的な挙動については PR #20345 と issue #20344 を読みます。LiteralString によって境界付けられた TypeVar のケースが決定的で正しい結果を生成すれば完了です。

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

評価

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

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

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