python / python/mypy

using __new__ with type(x: T) resolvestype(x: T) as being of type type

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

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

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

説明

The following code passes a MyPy check with flying colors:

from typing import TypeVar, Any
T = TypeVar("T", bound=Any)

def this_one_works(x: T) -> T:
    res = x.__new__(type(x))
    return res

But the following does not:

from typing import TypeVar, Any
T = TypeVar("T", bound=Any)

def this_one_not_so_much(x: T) -> T:
    res = type(x).__new__(type(x))
    return res

Instead it seems to resolve type(x) as <class 'type'> when used with __new__() and complains about missing arguments:

test.py:5: error: No overload variant of "new" of "type" matches argument type "Type[T]"
test.py:5: note: Possible overload variants:
test.py:5: note: def new(cls, cls: Type[type], o: object) -> type
test.py:5: note: def new(cls, cls: Type[type], name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type
Found 1 error in 1 file (checked 1 source file)

Is this expected behavior, or is it resolving incorrectly in the second case?

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

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

はじめの一歩

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

調査の方向性

まず、issue にある 2 つのコードスニペットを mypy で実行し、type(x) と x.new がどのように推論されるかを比較します。type(x).new の型チェック経路を追跡し、報告された解決が想定どおりかどうかを判断します。意図された動作を確立し、その結果を文書化またはテストできれば完了です。

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

評価

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

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

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