python / python/mypy

Non-inline `__init_subclass__` definition not recognized, despite giving type hints.

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

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

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

説明

Mypy does not recognize overwritten __init_subclass__ and complains that it's different from object's __init_subclass__.

So a simple code would be something like:

import dataclasses as dcls
from typing import Protocol, TypeVar, Callable

class InitSubclassWithKey(Protocol):
    """
    The ``__init_subclass__`` method of the classes making use of a factory.
    """

    def __call__(self, cls, *, key: str = "") -> None: ...

GLOBAL_REGISTRY = {}

def generate_init_subclass[T](lazy_base_class: Callable[[], T]) -> InitSubclassWithKey:
    def __init_subclass__(cls, *, key: str = "") -> None:
        base_class = lazy_base_class()
        GLOBAL_REGISTRY[base_class, key] = cls
        print("Registered:", base_class, key, cls)

    return __init_subclass__


class Base:
    # Have to use a lazy getter here because or else it would be ``NameError``.
    __init_subclass__ = generate_init_subclass(lambda: Base)

class Derived(Base, key="derived"):
    pass

Expected Derived to pass without issue (as is the case if I define __init_subclass__ directly).
Note: mypy has full type information here because of the protocol given (InitSubclassWithKey).

However, I get:

main.py:26: error: Unexpected keyword argument "key" for "__init_subclass__" of "object"  [call-arg]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.15.0 (compiled: yes)
  • Mypy command-line flags: main.py
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.13

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

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

はじめの一歩

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

調査の方向性

main.py の再現コードから始め、Python 3.13 で mypy 1.15.0 を実行して、予期しないキーワード引数エラーを確認します。mypy が init_subclass へのインラインでない代入をどのように処理し、object にフォールバックするかを追跡します。型付きの Protocol 代入によって Derived(Base, key="derived") がエラーなしで許可されれば完了です。

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

評価

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

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

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