Python:获取“ typing.List”的类型

blu*_*ote 5 python

我已经将函数的参数注释为

import typing

def f(x: typing.List[MyType]):
    ...
Run Code Online (Sandbox Code Playgroud)

通过检查参数实参,我得到的类型,正确地x将typing.GenericMeta其实例打印为typing.List[MyType]

如何从该对象获取List和MyType?

L3v*_*han 7

如果你想得到MyType,你可以在下面找到它.__args__:

import typing

def f(x: typing.List[MyType]):
    ...

print(f.__annotations__["x"].__args__[0])  # prints <class '__main__.MyType'>
Run Code Online (Sandbox Code Playgroud)

List(即typing.List)可从 访问.__base__,实际列表类来自.__orig_bases__:

print(f.__annotations__["x"].__base__)  # prints typing.List[float]
print(f.__annotations__["x"].__orig_bases__[0])  # prints <class 'list'>
Run Code Online (Sandbox Code Playgroud)

  • 我不知道,我只是尝试了 `dir`。 (2认同)