python / python/mypy

generic subclasss and typevar with constraint

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

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

bug false-positive priority-1-normal topic-type-variables
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Not sure if this is a "bug" or I didn't understand generics, but

import typing

T = typing.TypeVar('T', str, int)


class Base(typing.Generic[T]):

    def __init__(self, bar: T):
        self.bar: T = bar


class Child(Base[T]):

    def __init__(self, bar: T):
        super().__init__(bar)

mypy 0.720 (on windows) says

> mypy.exe test\__init__.py
test\__init__.py:15: error: Argument 1 to "__init__" of "Base" has incompatible type "str"; expected "T"
test\__init__.py:15: error: Argument 1 to "__init__" of "Base" has incompatible type "int"; expected "T"

but if I change the T definition to T = typing.TypeVar('T') the errors go away

What I want is to specify that

  • the "Base" constructor has a parameter that could be an int or a str
  • the "Child" constructor has the same "signature" of the "Base" one (well, this is a simplified example, I want something more...)

is this a bug? di I misinterpreted the TypeVar usage?

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

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

はじめの一歩

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

調査の方向性

mypy 0.720 を使って test_init_.py の例を再現し、制約付き TypeVar と制約なしバージョンを比較します。関連する generic および TypeVar-checking のパスを読み、報告された診断が想定されたものかどうかを確認します。動作を文書化するか、回帰テストを追加し、バグであれば修正すれば完了です。

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

評価

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

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

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