python / python/mypy

`callable()` fails to narrow type to `Callable`

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

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

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

説明

Bug Report

I'm sorry if this is a duplicate; it's possible it's covered by one of the existing issues about type narrowing, but I couldn't find anything that explicitly covers this case.

https://mypy.readthedocs.io/en/stable/type_narrowing.html#type-narrowing-expressions explicitly says that callable(obj) will narrow obj to a callable type. However, in my code this doesn't seem to work; the argument to callable is still left as Any.

To Reproduce

With mypy 1.19.1 and --strict:

from collections.abc import Callable

class A:
    def get_callback(self, name: str) -> Callable[[], bool]:
        callback = getattr(self, name)
        assert callable(callback)
        return callback

Also demonstrated in this playground.

Actual Behavior

t.py:7: error: Returning Any from function declared to return "Callable[[], bool]"  [no-any-return]

Your Environment

  • Mypy version used: 1.19.1
  • Mypy command-line flags: --strict
  • Python version used: 3.13

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

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

はじめの一歩

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

調査の方向性

mypy 1.19.1 と --strict で t.py の再現コードから始め、次に issue にリンクされている型の絞り込み式のドキュメントを読み、callable(obj) に焦点を当ててください。callable のアサーションがどのように処理されるかを追跡し、Callable[[], bool] を返す場合に、その例で no-any-return が報告されなくなっていることを確認してください。

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

評価

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

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

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