[英]How do I get a function's full name and arguments as string from a list of function objects in Python?
正如标题所说,我对 python 模块中的所有函数列表作为字符串感兴趣。 到目前为止,我有一个 function 对象及其可能的 arguments 的列表。
例如,使用 NumPy
from inspect import getmembers, isfunction
import numpy
functions_list = getmembers(numpy, isfunction)
functions_list = [x[1] for x in functions_list] #functions_list = [str(x[1]).split(' ')[1] for x in functions_list]
functions_list[:4]
Output:
[<function numpy.__dir__()>,
<function numpy.__getattr__(attr)>,
<function numpy.core.function_base.add_newdoc(place, obj, doc, warn_on_python=True)>,
<function numpy.alen(a)>]
如果我尝试列表理解并将 function object 解析为带有 str(x) 的字符串,如下所示:
functions_list = [str(x[1]) for x in functions_list]
Output:
['<function __dir__ at 0x000001C9D44AF310>',
'<function __getattr__ at 0x000001C9D40BFD30>',
'<function add_newdoc at 0x000001C9D42C0C10>',
'<function alen at 0x000001C9D42610D0>']
同样适用于:
str(functions_list)
repr(functions_list)
我想要类似的东西:
['numpy.__dir__()',
'numpy.__getattr__(attr)',
'numpy.core.function_base.add_newdoc(place, obj, doc, warn_on_python=True)',
'numpy.alen(a)']
我该如何存档? 我知道这里有很多类似的问题,我查找了其中的一些,但我找不到可以帮助我的东西。
虽然它并不完美,但使用inspect.signature
怎么样?
from inspect import getmembers, isfunction, signature
import numpy
def explain(m):
try:
return f"{m[0]}{signature(m[1])}"
except ValueError:
return f"{m[0]}(???)" # some functions don't provide a signature
print(*(explain(m) for m in getmembers(numpy, isfunction)), sep='\n')
# __dir__()
# __getattr__(attr)
# add_newdoc(place, obj, doc, warn_on_python=True)
# alen(a)
# all(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)
可能有更好的方法来做到这一点,但您可以自己从f.__module__
、 f.__name__
和function 签名中拼凑起来。
import numpy as np
from inspect import signature
f = np.core.function_base.add_newdoc
print(f'{f.__module__}.{f.__name__}{signature(f)}')
Output:
numpy.core.function_base.add_newdoc(place, obj, doc, warn_on_python=True)
但这不适用于不提供签名的函数,例如np.where()
。 请参阅j1-lee 对此的回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.