问题描述
我想知道如何输入提示:
def f(d,n):
return {(n,key): d[key] for key in d}
dd = {
1.0: 10.2,2.0: 11.8,"T1": 300,"T2": 300,}
nn = "Name"
f(d = dd,n = nn)
# returns:
# {('Name',1.0): 10.2,# ('Name',2.0): 11.8,'T1'): 300,'T2'): 300}
我尝试了以下方法:
def f(
d : Mapping[Union[str,float],n : str) -> Dict[Tuple[str,float]:
return {(n,n = nn)
给出错误:
main.py:6: error: Key expression in dictionary comprehension has incompatible type "Tuple[str,Union[str,float]]"; expected type "Tuple[str,float]"
main.py:17: error: Argument "d" to "f" has incompatible type "Dict[object,float]"; expected "Mapping[Union[str,float]"
Found 2 errors in 1 file (checked 1 source file)
我不知道如何解决这个问题。
解决方法
我建议以不同的方式解决问题。与其尝试指定特定类型,因为您的函数并不真正依赖键是字符串或浮点数,不如像这样使其通用:
T1 = TypeVar("T1")
T2 = TypeVar("T2")
T3 = TypeVar("T3")
def f(d: Mapping[T1,T2],n: T3) -> Dict[Tuple[T3,T1],T2]:
return {(n,key): d[key] for key in d}
这通过了 mypy
检查:
Success: no issues found in 1 source file
现在变得更容易理解了,因为您不再推断什么应该是 Union
,什么不应该。如果 mypy
看到 T1
需要是特定情况下的 Union
,它会自行推断。
但要回答您的实际问题:
main.py:6: error: Key expression in dictionary comprehension has incompatible type "Tuple[str,Union[str,float]]"; expected type "Tuple[str,float]"
此错误发生在您的代码中,因为您的元组的第二个元素(键)是 float
,而输入键是 Union[str,float]
。您试图将潜在的 str
强制转换为 float
。
main.py:17: error: Argument "d" to "f" has incompatible type "Dict[object,float]"; expected "Mapping[Union[str,float],float]"
这是上述错误的扩展,展示了当元组的第二个元素的类型改变时整个返回类型如何改变。解决您的问题将消除这两个问题。