当参数可以具有从特定基类型派生的任何类型时,如何注释抽象方法的参数类型?

How do I annotate the type of a parameter of an abstractmethod, when the parameter can have any type derived from a specific base type?

当参数可以具有从特定基类型派生的任何类型时,如何注释抽象方法的函数参数的类型?

示例:

import abc
import attr

@attr.s(auto_attribs=True)
class BaseConfig(abc.ABC):
    option_base: str

@attr.s(auto_attribs=True)
class ConfigA(BaseConfig):
    option_a: str

@attr.s(auto_attribs=True)
class ConfigB(BaseConfig):
    option_b: bool


class Base(abc.ABC):
    @abc.abstractmethod
    def do_something(self, config: BaseConfig):
        pass

class ClassA(Base):
    def do_something(self, config: ConfigA):
        # test.py:27: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig"
        print("option_a: " + config.option_a)

class ClassB(Base):
    def do_something(self, config: ConfigB):
        # test.py:33: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig"
        print("option_b: " + str(config.option_b))

conf_a = ConfigA(option_a="value_a", option_base="value_base")
conf_b = ConfigB(option_b=True, option_base="value_base")
object_a = ClassA()
object_b = ClassB()
object_a.do_something(conf_a)
object_b.do_something(conf_b)

当用 mypy 解析这个时,我得到

test.py:27: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig"
test.py:33: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig"

我需要如何更改 Base.do_something() 的签名,以便 mypy 不报告任何错误,同时仍然强制执行,抽象方法 do_something 的函数参数派生自基础配置?

TLDR:制作基础class Generic 并参数化配置类型:

C = TypeVar('C', bound=BaseConfig)

class Base(abc.ABC, Generic[C]):
    @abc.abstractmethod
    def do_something(self, config: C):
        pass

原始的 class 层次结构声明 ClassA 可以在 Base 有效的任何地方使用。当我们假设某个变量 obj: Base 时,这会导致冲突:

  • 我们可以分配 obj = ClassA() 因为 ClassA "is a" Base class.
  • 我们可以使用 obj.do_something(BaseConfig()) 因为 obj "is a" Base 实例。

但是,ClassA.do_something(config: ConfigA) 说我们不能同时,这与类型等价相矛盾。


相反,我们需要区分“接受ConfigABase”、“接受ConfigBBase”等等。这是通过使用配置的类型变量参数化 Base 来完成的。

from typing import Generic, TypeVar

C = TypeVar('C', bound=BaseConfig)      # C "is some" BaseConfig type

class Base(abc.ABC, Generic[C]):        # class takes type variable ...
    @abc.abstractmethod
    def do_something(self, config: C):  # ... and uses it in method signature
        pass

这使我们可以同时拥有通用和具体的 Base 变体 - 例如,Base[ConfigA] 是“Base 接受 ConfigA”。由此,子classes可以导出为采用适当的配置:

class ClassA(Base[ConfigA]):        # set type variable to ConfigA
    def do_something(self, config: ConfigA):
        print("option_a: " + config.option_a)