我正在使用现代Python类型提示,比如Tuple[int,...]
。有些地方需要从给定的类型提示变量中获取原始的Python类型(tuple
、list
等)。例如:
t = Tuple[int,...]
# Get tuple from t
我正在使用现代Python类型提示,比如Tuple[int,...]
。有些地方需要从给定的类型提示变量中获取原始的Python类型(tuple
、list
等)。例如:
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
Tuple[int, float]
中获取tuple
的便捷方式肯定会很有用。 - user2357112repr(t)
这样的低劣选项。 - user2357112__extra__
属性。如果存在,它的工作方式如下:List[int].__extra__ == list
。目前,这无法适用于所有类型(例如不适用于Tuple
)。请注意,这是一个未记录的内部功能,并且可能会在没有警告的情况下被破坏 ;-) 同时,您永远不应该修改__extra__
,否则可能会导致事情变得非常糟糕。 - ivanl