为List TypeError的自定义子类设置typehint:“type”对象不可下标

2024-10-02 16:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过typehinting指定返回的List子类的元素

from typing import Union, List, Tuple, Optional, NewType
from jira import JIRA
from jira.client import ResultList
from jira.resources import Issue

def search(...) -> ResultList[Issue]: # using 'List[Issue]:' or 'ResultList:' as return type hint work
    ...

但是,我正在运行此错误:

TypeError: 'type' object is not subscriptable

我用NewType试过运气,但没能让它按预期运行。当不指定子类ResultList[Issue]并改用List[Issue]时,它会起作用。另外,当不通过简单地使用ResultList来提及元素类型时,它是有效的

其他信息:

ResultList Code

Issue Code


Tags: fromimport元素typingtypejiracodeissue
1条回答
网友
1楼 · 发布于 2024-10-02 16:24:01

你应该看看这些:

说明:
list打字。list是完全不同的东西
为了使用generic,您必须继承自typing.generic
如果您使用第三方libs代码并且无法更改结果列表,则存根是一种解决方案
基本上,您需要在*.pyi文件中为ResultList类定义存根,如下所示:

from typing import Generic, TypeVar, Iterable

T = TypeVar('T')

class ResultList(list, Generic[T]):
    def __init__(
        self, iterable: Iterable[T] = ..., _startAt: int = ..., _maxResults: int = ..., _total: int = ..., _isLast: bool = ...
    ) -> None:
        ...
    ...

之后,您可以按如下方式使用as键入:

from unittest import TestSuite

from res import ResultList


class SomeClass:
    pass


def foo() -> 'ResultList[int]':
    return ResultList(iterable=[SomeClass()])


if __name__ == '__main__':
    a: 'ResultList[str]' = foo()
# pycharm will highlight "unexpected type error"

别忘了连接pycharm中的存根,如链接中所示

相关问题 更多 >