Python - 如何将泛型类类型与函数返回类型结合使用

问题描述 投票:0回答:1

为什么这个类型提示不起作用

from typing import Generic, TypeVar
from dataclasses import dataclass


V = TypeVar('V', int, str)


@dataclass
class Test(Generic[V]):
    a: V


class Base(Generic[V]):
    def test(self) -> Test[V]:
        t = '1'
        return Test[V](t) 


b = Base[str]()
b.test()

mypy
显示

test.py:16: error: Argument 1 to "Test" has incompatible type "str"; expected "int"  [arg-type]

我的期望是创建具有指定类型

Base
的实例
str
,它用于
V
,当它转换为
test()
时,它应该在
Test[str](t)

返回值中兼容
python typing
1个回答
0
投票

我的期望是创建具有指定类型

Base
的实例
str
,它用于
V
,当它转换为
test()
时,它应该在
Test[str](t)

返回值中兼容

您的

b = Base[str]()
行对
class Base(Generic[V]):
的定义没有任何追溯作用 -
Base.test
的定义只是未通过类型检查,因为
t
str
(通过
t = '1'
),所以返回的是什么是
Test[str]
而不是通用
Test[V]
- 它不是返回“混合”类型的方法(请参阅
typing.AnyStr
作为示例,那里的文档对此有讨论)。将该分配更改为
t = 1
b = Base[int]()
,mypy 会抱怨相反的情况:

error: Argument 1 to "Test" has incompatible type "int"; expected "str"  [arg-type]

使用

pyright
实际上会给出更好的错误消息:

  /tmp/so_78174062.py:16:24 - error: Argument of type "Literal['1']"
  cannot be assigned to parameter "a" of type "V@Base" in function "__init__"
    Type "Literal['1']" cannot be assigned to type "V@Base" (reportArgumentType)

这清楚地强调了这是两种不同的类型,而测试方法真正应该具有此签名:

    def test(self) -> Test[str]:
        t = '1'
        return Test[str](t)

以上将正确键入检查。

© www.soinside.com 2019 - 2024. All rights reserved.