如何使用Python定义一个(非类)类型,例如:
typedef Dict[Union[int, str], Set[str]] RecordType
如何使用Python定义一个(非类)类型,例如:
typedef Dict[Union[int, str], Set[str]] RecordType
这只是简单地完成它吗?
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
如果用户正在寻找一个独特的命名类型定义:
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)