【发布时间】:2018-10-23 10:51:19
【问题描述】:
我希望 mypy 验证一个变量是某个基类的子类,并且它也有一个特定的 mixin。 Union 仅验证该值是否属于一种类型。我需要检查该值是否是两种类型。
在示例中,我创建了一个关键字“All”来展示我正在寻找的行为:
from typing import All
class Base ( object ):
pass
class Mixin ( object ):
pass
def assert_all ( x ):
# type: ( All[Base,Mixin] ) -> None
assert isinstance ( x, Base ) and isinstance ( x, Mixin )
class Child ( Mixin, Base ):
pass
assert_all ( Child() )
try:
assert_all ( Base() ) # !!! mypy should complain here
except AssertionError:
pass
else:
raise AssertionError ( 'assert inside of assert_all() should have fired' )
try:
assert_all ( Mixin() ) # !!! mypy should complain here, too
except AssertionError:
pass
else:
raise AssertionError ( 'assert inside of assert_all() should have fired' )
如果它有帮助,我需要它的原因是我有自己的用 Python 实现的 win32 包装器。我的 Base 类是基本的 Window 类。我需要的 Mixin 是 ControlHost,它向 Window 类添加了特定的窗口样式和功能来管理拥有的孩子,这是基本窗口不需要的东西。在创建子控件(例如 ComboBox)时,如果我提供给它的父窗口没有两个超类,我希望 mypy 将我叫出来。
此外,由于父类型的更改,我在从 Control.init() 调用 Window.init() 时遇到问题。这是说明问题的简短伪代码:
class Window:
def __init__ ( self, parent, .... ):
# type: ( Optional[Window], .... )
class Control ( Window ):
def __init__ ( self, parent, .... ):
# type: ( Optional[ControlHost], .... )
我的解决方法看起来像这样,但它不允许 mypy 捕获类型违规:
class Control ( Control_mixin, Window ):
....
def __init__ ( self, parent=None ):
# type: ( Optional[ControlHost] ) -> None
self.initStyle |= winapi.WS_CHILD|winapi.WS_CLIPSIBLINGS
assert isinstance ( parent, Window )
super ( Control, self ).__init__ ( cast ( Window, parent ) )
【问题讨论】:
标签: mypy