Python 声明变量时打字不起作用

Python typing not working when declaring a variable

我正在使用 python 3.6,并且想使用打字,因为它很好,你会得到更好的 linting 并且你可以在运行时之前捕获错误,并且自动完成也可用。

我有这个方法:

def add_to_dynamic_dict(filenames_by_satustag: Dict[str, List[str]], status_tag: str, filename: str) -> Dict[str, List[str]]:

所以在调用它之前我创建了一个这样的字典:

filenames_by_satustag = Dict[str, List[str]]

但是当运行我得到的脚本

TypeError: typing.Dict[str, typing.List[str]] is not a generic class

在那条线上。

但是根据文档是正确的:

https://docs.python.org/3.6/library/typing.html(26.1.1 类型别名,第二集团)

我做错了什么?

谢谢。

我认为您对类型别名感到困惑。您声明的方法需要第一个参数,您将其称为 filenames_by_satustag,类型为 Dict[str, List[str]]。但是,如果我没记错的话,您可以使用具有 value Dict[str, List[str]] 的变量 filenames_by_satustag 来调用您的方法。因此,它的类型是Dict[str, List[str]]的类型,即typing._GenericAlias。如果您想创建一个名为 filenames_by_satustag 的新类型,您应该执行以下操作:

filenames_by_satustag = Dict[str, List[str]]

# The function return can also be replaced by filenames_bu_satustag
def add_to_dynamic_dict(some_variable: filenames_by_satustag, status_tag: str, filename: str) -> Dict[str, List[str]]:

但是,如果您想要的不是创建类型别名,而只是创建变量 filenames_by_satustag,您可以这样做:

filenames_by_satustag: Dict[str, List[str]] = {}