我如何创建同时包含threading.Event和multiprocessing.Event的协议?

问题描述 投票:1回答:1

在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无法识别multiprocessing.Eventthreading.Event都实现了我定义的协议:

$ mypy proto.py
proto.py:29: error: Incompatible types in assignment (expression has type "Type[multiprocessing.synchronize.Event]", base class "Base" defined the type as "Type[proto.Event]")
proto.py:31: error: Argument 1 of "foo" is incompatible with supertype "Base"; supertype defines the argument type as "Event"
proto.py:36: error: Incompatible types in assignment (expression has type "Type[threading.Event]", base class "Base" defined the type as "Type[proto.Event]")
proto.py:38: error: Argument 1 of "foo" is incompatible with supertype "Base"; supertype defines the argument type as "Event"
Found 4 errors in 1 file (checked 1 source file)

为什么mypy无法识别我的协议,我该如何解决?

最初我使用的是mypy 0.730。升级到mypy 0.761之后,我只有两个错误,但在我看来仍然可以运行:

$ 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)
python mypy
1个回答
0
投票

这不是Protocol问题。您将foo的签名更改为更严格的变体Base.foo()接受any Event实现,而每个子类仅接受一个具体实现。这违反了Liskov substitution principle,Mypy不允许这样做是正确的。

您必须在此处使用绑定的TypeVarGeneric的组合,因此您可以创建采用不同类型的Base的不同具体子类:

from typing import Generic, Optional, Protocol, Type, TypeVar

# Only things that implement Event will do
T = TypeVar("T", bound=Event)

# Base is Generic, subclasses need to state what exact class
# they use for T; as long as it's an Event implementation, that is.
class Base(Generic[T]):
    flag_class: Type[T]

    def foo(self, e: T) -> None:
        pass

然后不同Event类的以下子类是正确的:

class DerivedOne(Base[multiprocessing.synchronize.Event]):
    flag_class = multiprocessing.synchronize.Event

    def foo(self, e: multiprocessing.synchronize.Event) -> None:
        pass

class DerivedTwo(Base[threading.Event]):
    flag_class = threading.Event

    def foo(self, e: threading.Event) -> None:
        pass

但是使用未实现协议方法的类是错误:

# Mypy flags the following class definition as an error, because a lock
# does not implement the methods of an event.
# error: Type argument "threading.Lock" of "Base" must be a subtype of "proto.Event"
class Wrong(Base[threading.Lock]):
    flag_class = threading.Lock

    def foo(self, e: threading.Lock) -> None:
        pass

混合类型也是错误的:

# Mypy flags 'def foo' as an error because the type it accepts differs from
# the declared type of the Base[...] subclass
# error: Argument 1 of "foo" is incompatible with supertype "Base"; supertype defines the argument type as "Event"
class AlsoWrong(Base[threading.Event]):
    flag_class = threading.Event

    def foo(self, e: multiprocessing.synchronize.Event) -> None:
        pass
© www.soinside.com 2019 - 2024. All rights reserved.