最适合定义复杂类型:CustomType(TypedDict) 或 CustomType = NewType(...)

问题描述 投票:0回答:1
from typing import TypedDict

class CustomType(TypedDict):
    id: str
    path: str
    targets: list[str]

from typing import NewType

CustomType = NewType("CustomType", dict[str, str, list[str]])

看起来无论哪种情况我都可以在类型提示中使用

CustomType

def method(arg: CustomType) -> None:
    print(arg)

我觉得 TypedDict 方法更好,因为它更明确并且包含更多信息。

但如果我的目标只是为复杂数据类型提供类型提示,则不确定哪个更好。

python types type-hinting
1个回答
1
投票

dict[str, str, list[str]]
首先不是有效的静态类型,因为如果您针对第二个代码片段运行它,mypy 会告诉您。输出:

main.py:3: error: "dict" expects 2 type arguments, but 3 given  [type-arg]
Found 1 error in 1 file (checked 1 source file)

dict
采用键类型和值类型,而不是未指定命名键的 3 个单独的值类型。如果您想为具有特定键名称和这些键的特定值类型的字典编写注释,
typing.TypedDict
就是这样做的方法。

使用

TypedDict

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