繁体   English   中英

Python 3 协议 - 是否可以在方法中要求特定的参数,但也允许额外的参数?

[英]Python 3 Protocols - is it possible to require specific arguments in method, but allow extra arguments as well?

我正在尝试键入提示协议以包含少量类似的 API 接口。 我想让某些方法灵活并允许额外的参数和关键字参数,因为不同的实现有不同的“奖励”参数,但它们都在签名的前半部分共享一组公共参数。

这很尴尬,因为我试图为一些我不直接控制的类编写兼容性,所以我无法编辑实现签名。


from typing import Protocol

class ExampleProtocol(Protocol):
    def test(self, important_arg:str, *args, **kwargs):
        pass

class ExampleImplementation:
    def test(self, important_arg:str):
        pass

class ExampleImplementation2:
    def test(self, important_arg:str, unnessary_arg:bool):
        pass

implementation: ExampleProtocol = ExampleImplementation()
implementation2: ExampleProtocol = ExampleImplementation2()

Pylance给了我这个:

"ExampleImplementation" is incompatible with protocol "ExampleProtocol"
    "test" is an incompatible type
      Type "(important_arg: str) -> None" cannot be assigned to type "(important_arg: str, *args: Unknown, **kwargs: Unknown) -> None"
        Parameter "**kwargs" has no corresponding parameter

在这种情况下是否可以输入提示,还是只需要使用任何? python 是否允许暗示具有一些重要参数的“动态”签名?

这里的简短回答是“否”,主要是因为您的ExampleImplementation方法test (或ExampleImplementation2 )具有ExampleProtocol允许的参数子集。 也就是说, ExampleProtocol接受了一些参数集, ExampleImplementation会中断这些参数——超过第一个参数的任何参数。

在不知道您要确切了解的内容的情况下,您只能手动过滤*agrs**kwargs参数以获取您关心的参数。 前者可能很困难,因为它们没有命名,它们只是位置。

也就是说,您要使用的类型提示是Optional 它本身并不能解决您的问题,但它是一种声明“这是无或属于 x 类型”的类型。 例如:

def f(a: Optional[bool]) -> None:
    # a is either None or a boolean value

我认为Any在这里对你没有任何帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM