Python 中 typedef 的等价物

Ore*_*lom 22 python user-defined-types

定义(非类)类型的Python方法是什么:

typedef Dict[Union[int, str], Set[str]] RecordType
Run Code Online (Sandbox Code Playgroud)

Gri*_*mar 23

就这么简单就可以了吗?

from typing import Dict, Union, Set

RecordType = Dict[Union[int, str], Set[str]]


def my_func(rec: RecordType):
    pass


my_func({1: {'2'}})
my_func({1: {2}})
Run Code Online (Sandbox Code Playgroud)

此代码将在第二次调用 时从 IDE 生成警告my_func,但在第一次调用时不会。正如@sahasrara62 所示,更多信息请参见https://docs.python.org/3/library/stdtypes.html#types-genericalias

Python 3.9开始,首选语法是:

from typing import Union

RecordType = dict[Union[int, str], set[str]]
Run Code Online (Sandbox Code Playgroud)

内置类型可以直接用于类型提示,不再需要添加的导入。

Python 3.10开始,首选语法是

RecordType = dict[int | str, set[str]]
Run Code Online (Sandbox Code Playgroud)

运算符是创建类型联合的更简单方法,并且不再需要|导入。Union

从Python 3.12开始,首选语法是

type RecordType = dict[int | str, set[str]]
Run Code Online (Sandbox Code Playgroud)

type关键字明确表明这是一个类型别名。


Ore*_*lom 8

如果用户寻找不同的标称 typedef:

from typing import Dict, Union, Set, NewType

RecordType = Dict[Union[int, str], Set[str]]
DistinctRecordType = NewType("DistinctRecordType", Dict[Union[int, str], Set[str]])

def foo(rec: RecordType):
    pass

def bar(rec: DistinctRecordType):
    pass

foo({1: {"2"}})
bar(DistinctRecordType({1: {"2"}}))
bar({1: {"2"}}) # <--- this will cause a type error
Run Code Online (Sandbox Code Playgroud)

此片段演示了只有显式转换才可以。

$ mypy main.py
main.py:14: error: Argument 1 to "bar" has incompatible type "Dict[int, Set[str]]"; expected "DistinctRecordType"
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)