Python 相当于 typedef
Python equivalent for typedef
定义(非class)类型的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}})
此代码将在您的 IDE 第二次调用 my_func
时生成警告,但不会在第一次调用时生成。正如@sahasrara62 所指出的,这里有更多内容 https://docs.python.org/3/library/stdtypes.html#types-genericalias
如果用户寻找 distinct 标称类型定义:
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)
定义(非class)类型的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}})
此代码将在您的 IDE 第二次调用 my_func
时生成警告,但不会在第一次调用时生成。正如@sahasrara62 所指出的,这里有更多内容 https://docs.python.org/3/library/stdtypes.html#types-genericalias
如果用户寻找 distinct 标称类型定义:
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)