python / python/mypy

Typing with ClassVar[Optional[Callable]] doesn't work if the callable has arguments

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

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

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

説明

Typing an attribute in a base class with ClassVar[Optional[Callable]] results in a type error even though the typing is seemingly sound.

To Reproduce

Playground: https://mypy-play.net/?mypy=master&python=3.11&gist=4f52f561801eeb053b6d0a47c9afbc15

class BaseClass:
    attr: ClassVar[Optional[Callable]] = None

class ChildClass2(BaseClass):
    @staticmethod
    def attr(s: str):
        pass

Expected Behavior

Mypy shouldn't return any errors.

Additionally, the same should happen when Callable is also typed itself, e.g. Callable[[str], None]. Right now both fail when they shouldn't.

Actual Behavior

test.py:10: error: Signature of "attr" incompatible with supertype "BaseClass"  [override]

Your Environment

  • Mypy version used: 1.1.1, 1.2
  • Mypy command-line flags: no relevant options
  • Mypy configuration options from mypy.ini (and other config files): no relevant options
  • Python version used: 3.11

Additional information

Interestingly, if the callable doesn't have any arguments, mypy doesn't fail:

class BaseClass:
    attr: ClassVar[Optional[Callable]] = None

class ChildClass2(BaseClass):
    @staticmethod
    def attr():
        pass

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

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

はじめの一歩

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

調査の方向性

リンクされている mypy-play の再現例を Python 3.11 で開始し、型付けされていない Callable のケースと型付けされた Callable のケースを比較します。ClassVar Optional Callable の override チェックの経路を追跡し、両方の staticmethod の例で互換性のないシグネチャのエラーが発生しないことを確認します。

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

評価

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

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

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