如何解决在python中将类型作为参数的复杂注释
作为一个玩具示例,考虑一个函数,它采用两种类型 A
、B
并在对象 A(B)
上返回。对此的标准示例是 A = defaultdict
和 B
,例如int
。我怎样才能注释这样的东西?我得到的最接近的是
from collections import defaultdict
from typing import TypeVar,Type,Protocol
Val = TypeVar('Val')
class InitableMapping(Protocol[Val]):
"""
A Protocol that enforces a MutableMapping with a special __init__
"""
def __init__(self,value_type: Type[Val]):
...
def __getitem__(self,item: int) -> Val:
...
def __setitem__(self,key: int,value: Val) -> None:
...
# more methods
M = TypeVar('M',bound=InitableMapping)
def build_mapping(mapping_type: Type[M],value_type: Type[Val]) -> InitableMapping[Val]:
return mapping_type(value_type)
foo = build_mapping(defaultdict,int)
print(foo.default_factory) # "InitableMapping[int]" has no attribute "default_factory"
我将 MyPy 输出放在评论中的位置。
显然,返回注释 InitableMapping[Val]
太宽泛了,但 M[int,Val]
不起作用。
很高兴能在这方面提供任何帮助:) 事实上,即使是关于要查找的内容的一些关键字也会很棒 - 我很难想出一个描述性的问题标题......
更新:一个更现实的例子可能是这样的
class MyClass(Generic[M,Val]):
def __init__(self,load: Callable[[],M[int,Val]]) -> None:
self.data = load()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。