python / python/typing

Relaxing usage of `type` with `typing.Protocol` in typing spec

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

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

topic: typing spec
主要言語
Python
スター
1.8k
フォーク
302
平均マージ
23時間
マージ済み PR(30日)
8

説明

Some time ago I opened a thread on the Python discourse about implementing an AbstractType semantic that would allow functions to receive non-instantiable types so to try and conform a bit the situation presented in the the thread.

Consider the snippet:

from abc import abstractmethod
from typing import runtime_checkable, Protocol, TypeVar, TypeGuard

@runtime_checkable
class MyProtocol(Protocol):
    @abstractmethod
    def my_method(self) -> str:
        ...

class MyClass:
    def my_method(self) -> str:
        return "Hello from MyClass!"
    
class MyOtherClass:
    def another_method(self) -> str:
        return "Hello from MyOtherClass!"
    

P = TypeVar('P', bound=MyProtocol)
    
def check_protocol(obj: object, protocol: type[P]) -> TypeGuard[P]:
    return isinstance(obj, protocol)

# Example usage
my_obj = MyClass()
my_other_obj = MyOtherClass()
if check_protocol(my_obj, MyProtocol):
    print(my_obj.my_method())
if check_protocol(my_other_obj, MyProtocol):
    print(my_other_obj.my_method())
else:
    print("Object does not implement MyProtocol.")

Output:

Hello from MyClass!
my_obj does not implement MyOtherClass protocol.

At runtime, this works as intended. At type checking time, mypy complains that check_protocol cannot accept a non-instantiable type, while pyright and ty are accepting this behavior.

According to the typing specification, mypy is technically correct (the best kind of correct), but this code is perfectly acceptable. There are other examples referenced in python/mypy#4717 (which is the 3rd most upvoted issue by 👍 by the way).

I was hoping for more discussion points presented in the thread but not many replied. I didn't want to monopolize it, so I'm trying my luck here.

@JelleZijlstra (sorry for the ping) did point out that it might be worthwhile to change the spec to allow this behavior but I'm guessing there should be some discussion on how to deal with it first. Jelle suggested: "If you want it to be instantiable, use Callable[] instead."

I do agree it makes sense, but this snippet:

from typing import Protocol

class MyProtocol(Protocol):
    def method(self) -> str:
        ...
print(callable(MyProtocol)) # prints True

confuses me.

So my point is: could the spec allow for type to accept non-instantiable types, since it seems to be a pretty common pattern? Is there a way to effectively deal with the separation between instantiable and non-instantiable types?

I tried adding the "typing spec" label but couldn't. At any rate, thank you for the consideration.

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

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

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

調査の方向性

typing 仕様に関する議論とリンク先の Python Discourse スレッドから始め、その後、mypy、pyright、ty について説明されている動作を比較してください。関連する例については mypy#4717 を確認してください。type[P] がインスタンス化できない Protocol 型を受け入れてよいかについて合意に達し、その結果のルールを文書化できれば完了です。

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

評価

技術スタック
python
領域
documentation
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
静か
明瞭さ
説明が足りない
初心者へのやさしさ
35/100

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

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