【发布时间】:2021-09-13 01:08:42
【问题描述】:
我有以下设置:
from typing import List
a = List[int]
foo(a) == int
我可以使用什么foo 来从List 中获取int?
【问题讨论】:
标签: python-3.x type-hinting python-typing type-annotation
我有以下设置:
from typing import List
a = List[int]
foo(a) == int
我可以使用什么foo 来从List 中获取int?
【问题讨论】:
标签: python-3.x type-hinting python-typing type-annotation
您可以使用属性__args__ 来取出int。
from typing import List
a = List[int]
print(a.__args__[0])
结果:<class 'int'>
【讨论】:
typing.get_args 将是一种更安全的方法,因为__args__ 属性是一个未记录的实现细节。 docs.python.org/3/library/typing.html#typing.get_args