Python Union 可以递归包含自己吗?
Python can Union recursively contain itself?
是否可以创建一个类型,该类型是其中一项引用该类型的联合?
请参阅以下示例用例。这失败了,因为 Serialized
尚未声明。
from typing import List, Dict, Union
class MyClass:
# (...)
Serialized = Union[Dict[str, Serialized], List[Serialized], str, int, float, bool]
def serialize(self) -> Serialized:
...
根据PEP 484 which defines the type hints, you can use what they call forward references到尚未定义的引用类型。
所以你可以这样做:
from typing import Union, Dict, List
class MyClass:
# (...)
Serialized = Union[Dict[str, 'Serialized'], List['Serialized'], str, int, float, bool]
def serialize(self) -> Serialized:
...
是否可以创建一个类型,该类型是其中一项引用该类型的联合?
请参阅以下示例用例。这失败了,因为 Serialized
尚未声明。
from typing import List, Dict, Union
class MyClass:
# (...)
Serialized = Union[Dict[str, Serialized], List[Serialized], str, int, float, bool]
def serialize(self) -> Serialized:
...
根据PEP 484 which defines the type hints, you can use what they call forward references到尚未定义的引用类型。
所以你可以这样做:
from typing import Union, Dict, List
class MyClass:
# (...)
Serialized = Union[Dict[str, 'Serialized'], List['Serialized'], str, int, float, bool]
def serialize(self) -> Serialized:
...