[英]How does isinstance work for List?
I'm trying to understand how Python's type annotations work (eg List
and Dict
- not list
or dict
). 我试图理解Python的类型注释是如何工作的(例如
List
和Dict
- not list
or dict
)。 Specifically I'm interested in how isinstance(list(), List)
works, so that I can create my own custom annotations. 具体来说,我对
isinstance(list(), List)
如何工作感兴趣,这样我就可以创建自己的自定义注释。
I see that List
is defined as: 我看到
List
被定义为:
class List(list, MutableSequence[T], extra=list):
. . .
I'm familiar with metaclass = xxx
but I can't find any documentation on this extra = xxx
. 我熟悉
metaclass = xxx
但我找不到有关此extra = xxx
任何文档。 Is this a keyword or just an argument, and if so, where does it come from and does it do what I'm after? 这是一个关键字还是一个参数,如果是这样的话,它来自哪里,它会做我想要的事情? Is it even relevant for
isinstance
? 是否与
isinstance
相关?
The isinstance()
and issubclass()
have hooks in object.__instancecheck__()
and object.__subclasscheck__()
that the typing
generics also use. isinstance()
和issubclass()
在object.__instancecheck__()
和object.__subclasscheck__()
中有挂钩 , typing
泛型也使用。
If you want to provide your own generics, you really want to study the typing
module source code , specifically how GenericMeta
and Generic
are used to define the other Generic types like List
; 如果你想提供自己的泛型,你真的想学习
typing
模块源代码 ,特别是如何使用GenericMeta
和Generic
来定义其他通用类型,如List
; mostly such checks are delegated to abc.ABCMeta.__subclasshook__
. 大多数此类检查都委托给
abc.ABCMeta.__subclasshook__
。 You can define your own ABC with such a hook, then define a Generic that subclasses it. 您可以使用这样的钩子定义自己的ABC,然后定义一个子类化它的Generic。
It is the GenericMeta
metaclass here that also gives the extra
keyword argument meaning. 这里的
GenericMeta
元类也给出了extra
关键字参数含义。 Such internals are still sparsely documented because the typing
implementation is still in flux, the module is still provisional . 这样的内部结构仍然很少被记录,因为
typing
实现仍在不断变化,该模块仍然是临时的 。 The extra
argument is stored as __extra__
and is used in a custom __subclasshook__
implementation ; extra
参数存储为__extra__
,用于自定义__subclasshook__
实现 ; for extra=list
it simply comes down to translating isinstance(something, List)
to isinstance(something, list)
. 对于
extra=list
它简单地归结为将isinstance(something, List)
为isinstance(something, list)
。
Note that support for run-time checks is deliberately limited; 请注意,对运行时检查的支持是故意限制的; static type checkers will not actually run those hooks.
静态类型检查器实际上不会运行这些钩子。 See the structural subtyping discussion in the mypy tracker for further discussion on how the developers are thinking about how to provide better support for complex custom classes that may or may not implement enough methods to be deemed a mapping or a sequence or similar.
请参阅mypy跟踪器中的结构子类型讨论 ,以进一步讨论开发人员如何考虑如何为复杂的自定义类提供更好的支持,这些自定义类可能会或可能不会实现足以被视为映射或序列或类似的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.