如何在 NamedTuple 中键入函数属性
我有一段像
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
I have a piece of code like
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 complains:
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)
Why would it expect "Callable[[Config], int]"
?
I'm using Python-3.8, and mypy==0.800
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望该字段的类型是int的函数或
str
的函数,您可以这样做这描述了两个函数类型的并集。
然而,这不是一个有用的类型。如果 Python 有交集类型,则这相当于
And
int & str 是空类型。不存在同时为
int
和str
的值。所以这是一类永远不能被调用的函数。并且isinstance
在这里不会为您提供帮助,因为您无法对Callable
声明的参数类型进行类型检查。正如评论中提到的,您可以这样做
,但这是接受 int 或 string 的函数类型,而不是选择性地仅接受两者之一的函数类型。
If you want the type of that field to be either a function of an
int
or a function of astr
, you can doThis describes the union of two function types.
However, this is not a useful type. If Python had intersection types, this would be equivalent to
And
int & str
is, well, the empty type. There are no values which are bothint
andstr
at the same time. So this is a type of functions that can never be called. Andisinstance
won't help you here since you can't typecheck the declared argument types of aCallable
.As mentioned in the comments, you can do
but this is the type of functions that accept either an int or a string, not the type of functions that accept only one of the two selectively.