如何在 NamedTuple 中键入函数属性

发布于 2025-01-16 08:24:10 字数 751 浏览 2 评论 0原文

我有一段像

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

葬花如无物 2025-01-23 08:24:10

如果您希望该字段的类型是int的函数或str的函数,您可以

class Config(NamedTuple):
    func: Callable[[int], int] | Callable[[str], int]

这样做这描述了两个函数类型的并集。

然而,这不是一个有用的类型。如果 Python 有交集类型,则这相当于

Callable[[int & str], int]

And int & str 是空类型。不存在同时为 intstr 的值。所以这是一类永远不能被调用的函数。并且 isinstance 在这里不会为您提供帮助,因为您无法对 Callable 声明的参数类型进行类型检查。

正如评论中提到的,您可以这样做

Callable[[int | str], int]

,但这是接受 int 或 string 的函数类型,而不是选择性地仅接受两者之一的函数类型。

If you want the type of that field to be either a function of an int or a function of a str, you can do

class Config(NamedTuple):
    func: Callable[[int], int] | Callable[[str], int]

This describes the union of two function types.

However, this is not a useful type. If Python had intersection types, this would be equivalent to

Callable[[int & str], int]

And int & str is, well, the empty type. There are no values which are both int and str at the same time. So this is a type of functions that can never be called. And isinstance won't help you here since you can't typecheck the declared argument types of a Callable.

As mentioned in the comments, you can do

Callable[[int | str], int]

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文