我有一段代码
from typing import Callable, NamedTuple, TypeVar
def f1(x: int) -> int:
return x
def f2(y: str) -> int:
return len(y)
T = TypeVar("T", int, str)
class Config(NamedTuple):
func: Callable[[T], int]
c1 = Config(func=f1)
c2 = Config(func=f2)Mypy抱怨:
toy.py:19:18: error: Argument "func" to "Config" has incompatible type "Callable[[int], int]"; expected "Callable[[Config], int]"
toy.py:20:18: error: Argument "func" to "Config" has incompatible type "Callable[[str], int]"; expected "Callable[[Config], int]"
Found 2 errors in 1 file (checked 1 source file)为什么它会期望"Callable[[Config], int]"
我使用Python-3.8和mypy==0.800
发布于 2022-03-22 21:34:12
如果希望该字段的类型是int的函数或str的函数,则可以这样做。
class Config(NamedTuple):
func: Callable[[int], int] | Callable[[str], int]这描述了两种函数类型的联合。
但是,这不是一种有用的类型。如果Python有交集类型,这将相当于
Callable[[int & str], int]而int & str是,嗯,空类型。不存在同时为int和str的值。因此,这是一种永远无法调用的函数类型。isinstance不会在这里帮助您,因为您不能键入Callable声明的参数类型。
正如注释中提到的,您可以
Callable[[int | str], int]但这是接受int或字符串的函数类型,而不是只接受这两个函数中的一个的函数类型。
https://stackoverflow.com/questions/71579055
复制相似问题