且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“协议不能与isinstance()一起使用" - 为什么不?

更新时间:2023-09-06 09:22:22

这是PEP 484(typing模块的PEP)中给出的所有推理:

This is all of the reasoning given in PEP 484, the PEP for the typing module:

因为类型化.Callable双重职责代替了collections.abc.Callable,isinstance(x,类型.Callable)是通过推迟到`isinstance(x,collections.abc.Callable)来实现的.但是,不支持isinstance(x,键入.Callable [...]).

Because typing.Callable does double-duty as a replacement for collections.abc.Callable , isinstance(x, typing.Callable) is implemented by deferring to `isinstance(x, collections.abc.Callable) . However, isinstance(x, typing.Callable[...]) is not supported.

协议也称为magic method.这些是大多数python协议(完整列表此处):

A protocol is also known as a magic method. These are most of the python protocols (full list here):

>>> dir(object)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__']

我没有找到typing不支持isinstance的明确原因. issubclass起作用的原因是isinstance使用了typing不允许的__class_协议,而issubclass使用了允许的__subclasshook__协议.我相信原因是该功能已经在collections.abc.Callable中进行了编码,并且他们不想在typing模块中对其进行重新编码.

I have not found any clear reason for why typing does not support isinstance. The reason that issubclass works is that isinstance uses the __class_ protocol which is not allowed in typing, while issubclass uses the __subclasshook__ protocol which is allowed. I believe the reason is that the functionality was already coded in collections.abc.Callable and they did not want to recode it in the typing module.