python键入模块:Mixin [英] python typing module: Mixin

查看:101
本文介绍了python键入模块:Mixin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typing下是否有任何类的行为像mixin?

Is there any class under typing that behaves like a mixin?

例如

from typing import Union
class A:
  pass

class B:
  pass

class C:
  pass

class D(A, B, C):
  pass

# current: ab is A or B, but not both
def f(ab: Union[A, B]):
    pass

# ideal: ab is A and B
def f(ab: Mixin[A, B]):
    pass

f(D())

请注意DAB的实例,也是C的实例.对f的限制太大了(因为f不需要C),因此参数ab不一定是D类型,而是Mixin[A, B]

please notice how D is instance of A and B, but also C. This would be too much of a restriction for f (since f doesn't require C) and thus, the parameter ab is not necessarily of type D but Mixin[A, B]

如果typing模块不提供任何选项,那么还有什么比创建我自己的class AB(A, B)更优雅的了?

If the typing module doesn't provide any option, is there anything more elegant than creating my own class AB(A, B)?

推荐答案

目前看来不可能.

您可以在 python/typing#123 存储库.

PEP-544 上有一个类似的功能,称为 Protocol ,您可以通过合并mixin协议来合并mixin. 有 PEP-544 的实现,称为

There is a similar feature on PEP-544 called Protocol, and you can merge mixins by merging mixin protocols. There is an implementation of PEP-544 called typing_extensions. Maybe you can try that with this library.

这篇关于python键入模块:Mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆