python typing module: Mixin

我与影子孤独终老i 提交于 2019-11-27 04:36:48

问题


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

For example

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())

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]

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


回答1:


It seem to be impossible for now.

You can find a discussion about "Intersection" type in python/typing#123 repository.

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.



来源:https://stackoverflow.com/questions/44912576/python-typing-module-mixin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!