简体   繁体   English

如何注释一个由多个鸭子类型组合而成的类型?

[英]How to annotate a type that is a combination of multiple duck-types?

Let's say I want to annotate the parameter to a function, and it should satisfy both typing.Sized and typing.Hashable (any other 2+ types could apply, I just picked these two for the sake of example).假设我想将参数注释为 function,它应该同时满足typing.Sizedtyping.Hashable (任何其他 2+ 类型都可以应用,我只是为了举例而选择了这两个)。 How would I annotate this?我将如何注释这个?

Given that one can combine types as an "or" using Sized | Hashable鉴于可以使用Sized | Hashable将类型组合为“或”。 Sized | Hashable , I would expect something like: Sized & Hashable or Sized + Hashable to work, but unfortunately it doesn't (at the time of writing on Python 3.10). Sized | Hashable ,我希望类似: Sized & HashableSized + Hashable可以工作,但不幸的是它不起作用(在 Python 3.10 上撰写本文时)。

Is this supported at all, and if so with what syntax?这是否完全受支持,如果支持,使用什么语法?

Sized & Hashable is a reasonable guess, but unfortunately intersection types are not supported. Sized & Hashable是一个合理的猜测,但不幸的是不支持交集类型。

You'll have to define your own subclass that inherits from both:您必须定义自己的继承自两者的子类:

class SizedHashable(Sized, Hashable):
    pass

There seems to be some effort being made to support intersection types, but I can't find any updates beyond this brief mention.似乎正在努力支持交叉点类型,但除了这个简短的提及之外,我找不到任何更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM