繁体   English   中英

从类型提示中获取原始 Python 类型

[英]Get original Python type from type hint

我正在使用现代 Python 类型提示,如Tuple[int,...] 在某个地方,我需要从给定的类型提示变量中获取原始 Python 类型( tuplelist ...)。 例如:

t = Tuple[int,...]

# Get tuple from t

简单的情况: Type[type, ...]

import typing
from typing import Tuple, Optional
t = Tuple[int,...]

typing.get_origin(t)
>>> tuple

typing.get_args(t)
>>> (int, Ellipsis)

可选和嵌套: Optional[Type[type, ...]]

由于Optional[T]相当于Union[T, None]返回就像一个Union 嵌套类型以相同的方式递归检索。

t = Optional[Tuple[int,...]]

typing.get_origin(t)
>>> typing.Union

typing.get_args(t)
>>> (typing.Tuple[int, ...], NoneType)

typing.get_origin(typing.get_args(t)[0])
>>> tuple

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM