获得NumPy数组对象的签名

时间:2018-01-31 18:23:31

标签: python arrays numpy inspect method-signature

我在我正在创建的python编辑器中实现上下文帮助。

我想获得类和方法的方法'参数,但我也想要对象的方法。

对于NumPy数组,如果我执行类似的操作:

import numpy as np
import inspect
_members = inspect.getmembers(np)
for _member in _members:
    _params = str(inspect.signature(_member[1]))

没有问题。但是,当我做这样的事情时:

import numpy as np
import inspect
ar = np.array([1,2,3,4])
_members = inspect.getmembers(type(ar))
for _member in _members:
    _params = str(inspect.signature(_member[1]))

尝试获取签名时出错。每个_member[1]看起来像这样:

<method 'copy' of 'numpy.ndarray' objects>

我的问题:是解开签名的方法吗?如果那是不可能的,是否有解决方法来获取方法参数?

这不仅考虑np.array。我想得到任何类或对象的方法和参数。

1 个答案:

答案 0 :(得分:1)

您可以使用numpydoc模块获得大多数但可能不是所有签名:

>>> import numpy as np
>>> import inspect
>>> import numpydoc
>>> from pprint import pprint
>>> 
# inspect doesn't work
>>> inspect.signature(np.ndarray.transpose)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/paul/local/lib/python3.6/inspect.py", line 3002, in signature
    return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  File "/home/paul/local/lib/python3.6/inspect.py", line 2752, in from_callable
    follow_wrapper_chains=follow_wrapped)
  File "/home/paul/local/lib/python3.6/inspect.py", line 2231, in _signature_from_callable
    skip_bound_arg=skip_bound_arg)
  File "/home/paul/local/lib/python3.6/inspect.py", line 2061, in _signature_from_builtin
    raise ValueError("no signature found for builtin {!r}".format(func))
ValueError: no signature found for builtin <method 'transpose' of 'numpy.ndarray' objects>
>>> 
>>> info = numpydoc.docscrape.FunctionDoc(np.ndarray.transpose)
>>> info['Signature']
'a.transpose(*axes)'
>>> pprint(info['Parameters'])
[('axes',
  'None, tuple of ints, or `n` ints',
  ['',
   '* None or no argument: reverses the order of the axes.',
   '',
   "* tuple of ints: `i` in the `j`-th place in the tuple means `a`'s",
   "  `i`-th axis becomes `a.transpose()`'s `j`-th axis.",
   '',
   '* `n` ints: same as an n-tuple of the same ints (this form is',
   '  intended simply as a "convenience" alternative to the tuple form)'])]
>>> 
>>> info = numpydoc.docscrape.FunctionDoc(np.ndarray.std)
>>> info['Signature']
'a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False)'
# sometimes info is incomplete
>>> pprint(info['Parameters'])
[]