[英]How to create custom types using typing module?
我正在嘗試在 Python 3.7 打字模塊上創建自定義類型。 新類型(比如Struct
)應該與類型tuple
相同。 在 Python3.6 中,我可以通過Typing.GenericMeta
和typing.TupleMeta
來做同樣的事情。
隨着 Python3.7 中更新的類型模塊, GenericMeta
和TupleMeta
不存在,並且我想子類化的特殊 class 是不可能的。 例如_VariadicGenericAlias
。
我真正想要的是類似於:
Struct = _VariadicGenericAlias(tuple, (), , inst=False, special=True)
和
assert _origin(Struct[int, str]) == Struct
筆記:
def _origin(typ: Any) -> Any:
"""Get the original (the bare) typing class.
Get the unsubscripted version of a type. Supports generic types, Union,
Callable, and Tuple. Returns None for unsupported types. Examples::
get_origin(int) == None
get_origin(ClassVar[int]) == None
get_origin(Generic) == Generic
get_origin(Generic[T]) == Generic
get_origin(Union[T, int]) == Union
get_origin(List[Tuple[T, T]][int]) == list
"""
if isinstance(typ, _GenericAlias):
return typ.__origin__ if typ.__origin__ is not ClassVar else None
if typ is Generic:
return Generic
return None
想出了對我有用的解決方案。 使用了隱藏在 _GenericAlias 中的“名稱”參數:
Struct = _VariadicGenericAlias(tuple, (), , inst=False, special=True, name="Struct")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.