Python 泛型:无法分配给声明类型“T@func”

发布于 2025-01-17 18:07:06 字数 878 浏览 4 评论 0 原文

我正在尝试将通用键入介绍给我的功能,但是正在遇到一个钢铁错误:

Expression of type "A" cannot be assigned to declared type "T@func"
  Type "A" cannot be assigned to type "T@func"

我在代码中的问题将问题减少到了这个简化的版本:

from typing import TypeVar, Union, List


class A:
    def __init__(self, arg: str) -> None:
        self.arg = arg


class B:
    def __init__(self, arg: int) -> None:
        self.arg = arg


T = TypeVar("T", A, B)


def getA() -> A:
    return A("a")


def getB() -> B:
    return B(1)


def func(arg: T) -> T:
    out: T
    if isinstance(arg, A):
        out = getA()
    elif isinstance(arg, B):
        out = getB()

    return out


print(func(A("a")))

错误发生在两个 out = geta() out = getB()

Pyright无法在此处准确推断类型吗?我是犯错吗?

I'm trying to introduce Generic typing to a function of mine, but am getting a pylance error of:

Expression of type "A" cannot be assigned to declared type "T@func"
  Type "A" cannot be assigned to type "T@func"

I've reduce my problem in my code to this simplified version:

from typing import TypeVar, Union, List


class A:
    def __init__(self, arg: str) -> None:
        self.arg = arg


class B:
    def __init__(self, arg: int) -> None:
        self.arg = arg


T = TypeVar("T", A, B)


def getA() -> A:
    return A("a")


def getB() -> B:
    return B(1)


def func(arg: T) -> T:
    out: T
    if isinstance(arg, A):
        out = getA()
    elif isinstance(arg, B):
        out = getB()

    return out


print(func(A("a")))

The error occurs at both out = getA() and out = getB()

is pyright not able to accurately infer types here? Am I making a mistake?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

ㄟ。诗瑗 2025-01-24 18:07:06

当您将 t 绑定到 func 通过 arg bunc 时,您说的是 t arg arg 的类型/代码>在 func 中。当您声明 out t 时,您说的是 out 始终与 arg arg 的类型相同。因此,通过将 geta 的结果调节到 ,您将自己知道的东西分配给 a ,但是 out 必须是 b 如果 arg b

为避免类型错误,您只需写 func 像这样:

def func(arg: T) -> T:
    if isinstance(arg, A):
        return getA()
    if isinstance(arg, B):
        return getB()

在您的条件下,您实际上将 arg 的类型范围缩小到 a 和 b ,因此,如果您在条件中返回,则知道您正在返回 t ,即与 arg arg 相同的类型。

When you bind T to func via arg, you are saying T is the type of arg in func. When you declare out as a T, you are saying out will always be the same type as arg. So by assinging the result of getA to out, you are assigning something you know is an A to a T, but out must be a B if arg is a B.

To avoid the type errors, you can just write func like this:

def func(arg: T) -> T:
    if isinstance(arg, A):
        return getA()
    if isinstance(arg, B):
        return getB()

Within your conditions, you actually have narrowed the type of arg to A and B, so if you return inside the conditions, you know you are returning a T, i.e. the same type as arg.

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