[英]How can I make the return-type of a function taking a sequence as input dependent on that sequences types?
我正在开发一个能够执行 SNMP 集操作的库。 有一个 function 具有如下签名:
def multiset(ip: str, community: str, oids: List[str], values: List[SnmpValue]) -> List[SnmpValue]:
...
这对真实签名略有改动,以更好地说明打字问题。 在正常操作中,function 将返回设置为相同类型列表的值。 在这个例子中看起来是多余的,但在实际代码中有一个用例(错误检测),但这会使这个打字问题有点过于复杂。
核心是我有一个function,它接受一个值序列并返回一个相同类型的序列。 这些类型仅在调用 function 的行上才真正可见。
说明这一点的另一种方法是下面的代码示例:
from typing import Generic, TypeVar, Union, List
TSupportedTypes = Union[int, str]
T = TypeVar('T', bound=TSupportedTypes)
class Wrapper(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def process(data: List[Wrapper[TSupportedTypes]]) -> List[TSupportedTypes]:
output = []
for item in data:
output.append(item.value)
return output
processed = process([Wrapper(1), Wrapper('foo')])
# Is it possible to make this work without an "isinstance" check?
processed[1].startswith('f')
在最后一次,类型检查器只知道列表中的每个值要么是int
要么是str
。 在这种情况下,类型仅在调用process
时才知道。
在上述情况下,类型检查器抱怨int
没有属性startswith
,但代码仍然可以工作。
有没有办法告诉类型检查器从process
function 返回的任何内容与进入它的内容相同?
目前我使用健康剂量的Any
提示,但这破坏了这段代码中类型检查的很大一部分,我真的很想知道这是否有效。
问题不在于process
,甚至不在于Wrapper
。 问题是列表类型被认为是同质容器类型。
List[X]
表示列表中的每个元素都是同一个 X 的一个实例。
即使您的示例的这个简化版本也没有类型检查:
from typing import Union, List
TSupportedTypes = Union[int, str]
processed: List[TSupportedTypes] = [1, 'foo']
# Is it possible to make this work without an "isinstance" check?
processed[1].startswith('f')
您可以看到,对于该程序中的特定值, processed[1].startswith
是安全的,但如果您只查看类型- 这是 mypy 所做的 - 那么就无法知道这一点。 根据处理的类型processed[1]
可以是 str 或 int。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.