python / python/mypy

`__new__()` on a `Generic` class doesn't work with `Self` as return type if the typevar is not specified, picking the first element of the typevar

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

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

bug
主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

説明

Bug Report

In pandas-stubs, we want to be able to return Series[int], Series[str], etc., as well as just Series from a __new__() constructor. In the current released version, we had return types of Series[S1] and Series and everything worked fine. But pyright made a change and developers there (@erictraut) say that Self needs to be the return type. See discussion starting here: https://github.com/microsoft/pyright/issues/5178#issuecomment-1563478640

With that change, mypy has a strange behavior, where returning Self in an overload that doesn't specify the value of the Generic parameter picks the first value. in the list provided in the TypeVar declaration.

To Reproduce

from typing import Generic, Self, TypeVar, overload, cast

S = TypeVar("S", int, str, bytes)


class Foo(Generic[S]):
    @overload
    def __new__(cls, dtype: type[S]) -> Self:
        ...

    @overload
    def __new__(cls, dtype=None) -> Self:
        ...

    def __new__(cls, dtype: type[S] | None = None) -> Self:
        return cast(Self, object.__new__(cls))


f = Foo(None)
reveal_type(f)  # Mypy reveals: Foo[int]; should be Foo[Any]

f2 = Foo(str)
reveal_type(f2)

Expected Behavior

Output from pyright:

gennewself.py:20:13 - information: Type of "f" is "Foo[Unknown]"
gennewself.py:23:13 - information: Type of "f2" is "Foo[str]"

Actual Behavior

gennewself.py:20: note: Revealed type is "gennewself.Foo[builtins.int]"
gennewself.py:23: note: Revealed type is "gennewself.Foo[builtins.str]"

The issue here is that the type of f should be Foo[Any], not Foo[int] .

Your Environment

  • Mypy version used: 1.3.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11.31

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

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

はじめの一歩

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

調査の方向性

まず、提供されている Generic、overload、Self の再現コードを mypy 1.3.0 で実行し、reveal された型を pyright の出力と比較します。new の overload における未指定の Generic パラメーターの型推論を追跡します。Foo(None) が Foo[Any] を reveal し、Foo(str) が引き続き Foo[str] のままとなり、両方のケースに対するリグレッションカバレッジがあれば完了です。

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

評価

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

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

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