Python中相当于typedef的内容

21

如何使用Python定义一个(非类)类型,例如:

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

你想在什么上下文中定义一个新类型,以便你可以在类型提示中使用它? - Grismar
GenericAlias - sahasrara62
2个回答

20

这只是简单地完成它吗?

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}})

这段代码在第二次调用my_func时会在您的IDE中生成警告,但在第一次调用时不会。 参见@sahasrara62指出的更多信息:https://docs.python.org/3/library/stdtypes.html#types-genericalias


我喜欢Python的语法优雅且易于理解。 - undefined

8

如果用户正在寻找一个独特的命名类型定义:

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

这段代码演示只有显式转换才可行。
$ 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接