【发布时间】:2020-01-16 16:51:14
【问题描述】:
在 Python 标准库中,multiprocessing.Event 被明确声明为threading.Event 的克隆并具有相同的接口。我想注释变量和参数,以便它们可以接受这些类中的任何一个,mypy 会对它们进行类型检查。我尝试创建一个协议(我使用了multiprocessing.synchronize.Event,因为这是multiprocessing.Event 返回的实际类)。
import multiprocessing
import threading
from typing import Optional, Type, Protocol
class Event(Protocol):
def wait(self, timeout: Optional[float]) -> bool:
...
def set(self) -> None:
...
def clear(self) -> None:
...
def is_set(self) -> bool:
...
class Base:
flag_class: Type[Event]
def foo(self, e: Event):
pass
class DerivedOne(Base):
flag_class = multiprocessing.synchronize.Event
def foo(self, e: multiprocessing.synchronize.Event):
pass
class DerivedTwo(Base):
flag_class = threading.Event
def foo(self, e: threading.Event):
pass
但是,mypy(版本 0.761)无法识别 multiprocessing.Event 和 threading.Event 都实现了我定义的协议:
$ mypy proto.py
proto.py:31: error: Argument 1 of "foo" is incompatible with supertype "Base"; supertype defines the argument type as "Event"
proto.py:38: error: Argument 1 of "foo" is incompatible with supertype "Base"; supertype defines the argument type as "Event"
Found 2 errors in 1 file (checked 1 source file)
为什么mypy 无法识别我的协议,我该如何解决?
【问题讨论】:
标签: python type-hinting mypy