键入 NamedTuple 作为 class 以在 PyCharm 中包含参数提示

Typing NamedTuple as a class to include argument hints in PyCharm

编辑:Type[X] 确实对 class 本身进行类型提示。 repl 现在也有这样的例子。 PyCharm 只是不使用 class 中的 __init__ 信息在别处键入提示初始化。如果有人知道为什么会这样,我会接受这个答案。以下问题现在仅供参考:

假设我有以下代码:

from typing import NamedTuple, Type

class SubTuple(NamedTuple):
  a: str
  b: int

def get_tuple_type() -> Type[SubTuple]:
  return SubTuple

test_tuple = get_tuple_type()
test_tuple_instance = test_tuple('test', 1)

有没有一种方法可以输入提示,这样 PyCharm 就会给我参数提示?现在它给了我这个:

这没什么用。可笑的是,它确实知道参数,因为当我输入:

test_tuple.

它推荐 SubTuple 中的所有字段。当我去创建一个东西的实例时,它不会向我推荐它们。

此外,https://repl.it/repls/BurdensomeInnocentKnowledge只是为了让您看到上面的代码确实有效。 repl IDE 也不知道如何处理这个东西,并建议我在 class 本身上调用 .a 和 .b,这让我相信这可能只是一个普遍问题我在 Python?

中尝试做的事情

编辑:我正在使用 Python 3.7;更新代码以包含我尝试过的内容。它具有相同的结果。也会更新repl。

这是 PyCharm 的静态类型检查器中的一个错误,有一些关于 NamedTuple on JetBrains bugtracker. The most up-to-date thread on the NamedTuple datatype is PY-18246. Fixes have been rolled out during 2020 but this specific case of correctly inferring the NamedTuple members after typing a class object 的公开错误既未报告也未解决。

警告也发生了变化,如果你用 PyCharm 2020.3.3 Pro 尝试相同的代码,你会得到不同的提示。

我尝试用 Mypy 检查代码,它可以正常工作,没有任何警告。如果您尝试通过更改类型导致错误:

variable = test_tuple(1, 'test')

Mypy 警告并正确提示您:

error: Argument 1 to "SubTuple" has incompatible type "int"; expected "str"
error: Argument 2 to "SubTuple" has incompatible type "str"; expected "int"
Found 2 errors in 1 file (checked 1 source file)

Is there a way to type hint so that PyCharm will give me argument hints?

您已经按照 PEP 484 的建议正确键入提示。如果您使用 Mypy 静态类型检查器,它就可以工作,至于 PyCharm,这是等待错误修复的问题。您的类型提示没有任何问题,在这种情况下不应更改。