在运行时检查函数的注释时,可以得到 class
为给定的参数进行注释。例如:
>>> import inspect
>>> inspect.signature(f).parameters['a'].annotation
<class 'int'>
通过 f.__annotations__
可以实现同样的效果.
但是,出于饶恕读者的原因,我希望获得可读文本格式的注释。例如:a: int
将被检索为 int
,而不是 <class 'int'>
。
假设文本作为 eval
的输入应该是合法的。 .
我知道我能做到:
>>> str(inspect.signature(f).parameters['a'])
'a:int'
然后使用.split
处理这个字符串等等。但我想知道是否有更好的方法。
最佳答案
每个参数对象的annotation
属性都是一个类对象,因此可以简单地使用类对象的__name__
属性来获取字符串形式的类名:
import inspect
def f(a: int):
pass
print(inspect.signature(f).parameters['a'].annotation.__name__)
输出:
int
但正如 @chepner 指出的,如果是前向引用,annotation
属性可以是一个字符串,因此如果您希望代码是通用的,则必须考虑到这一点。例如:
class A:
def f(self, a: 'A'):
pass
annotation = inspect.signature(A.f).parameters['a'].annotation
print(annotation.__name__ if isinstance(annotation, type) else annotation)
输出:
A
关于python - 获取 'readable'格式的函数注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54562827/