【问题标题】:What is the difference between dict[[int], int] and dict[int, int]?dict[[int], int] 和 dict[int, int] 有什么区别?
【发布时间】:2022-01-29 09:48:46
【问题描述】:

我有以下代码:

from typing import *

Args = ParamSpec('Args')
ReturnType = TypeVar('ReturnType')
TestSet = Dict[Args, ReturnType]
ComplexTestSet = Dict[Args, Tuple[bool, Exception | None, ReturnType | None]]

# Some stuff

def test_func_simple(func: Callable[[Args], ReturnType], test_cases: TestSet) -> ComplexTestSet:
    pass # Some stuff

# Some stuff

if __name__ == "__main__":
    print(test_func_simple(f, {
        1: 1,
        2: 4,
        3: 9
    }))

代码运行良好并产生正确的输出,但 PyCharm 以黄色突出显示测试用例字典,并显示消息“预期类型 'dict[[int], int]' (matched generic type 'dict[ParamSpec("Args “),ReturnType]'),得到'dict [int,int]'”。我似乎无法弄清楚为什么它期望 dict[[int], int] 而不是 dict[int, int] 甚至 dict[[int], int] 实际匹配的内容。文档中似乎没有任何类似的东西出现,我尝试过的也没有与之匹配。有人能解释一下为什么会出现 dict[[int], int] 以及这到底是什么意思吗?

【问题讨论】:

  • ParamSpec 不打算这样使用。 PyCharm 被误用弄糊涂了。

标签: python pycharm type-hinting python-typing


【解决方案1】:

正如 user2357112 所指出的,它支持 Monica,这是由于不正确使用 ParamSpec。正确的代码是将 ParamSpec 替换为 TypeVar。

【讨论】:

  • 我想接受这个答案是正确的,因为我的问题在评论中得到了回答,但我不能 2 天。
猜你喜欢
  • 2017-02-23
  • 2014-10-20
  • 1970-01-01
  • 2020-05-05
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
相关资源
最近更新 更多