Int*_*rer 7 python type-hinting mypy python-typing
我通常使用unittest.mock.Mock的wraps功能来创建功能齐全的间谍对象。
这是一个运行时运行良好的示例:
from threading import Event
from typing import Union
from unittest.mock import Mock
spy_event: Union[Mock, Event] = Mock(wraps=Event())
spy_event.set()
assert spy_event.is_set()
# How can I type hint so this error doesn't show up from mypy?
spy_event.set.assert_called_once_with() # error: Item "function" of
# "Union[Any, Callable[[], None]]" has no attribute "assert_called_once_with"
Run Code Online (Sandbox Code Playgroud)
您可以看到,Union[Mock, Event]类型提示不起作用。
如何正确输入提示包裹在 a 中的对象Mock?
版本
Python==3.8.6
mypy==0.812
Run Code Online (Sandbox Code Playgroud)
spy_event只是一个Mock. 将其注释为Mock:
spy_event: Mock = Mock(wraps=Event())
Run Code Online (Sandbox Code Playgroud)
我不知道你为什么这么做Union——你可能误解了它的Union意思。