如何在 python 中使用 jedi 获取 numpy 函数参数的类型(来自文档字符串)

How to get the types of numpy function arguments (from docstrings) using jedi in python

理想情况下,我想要一个如下工作的函数(适用于所有类型的 numpy 函数):

parameter_types('np.random.binomial')

和returns:

{'a: 'int', 'b':'float', 'size':'int'}

我知道 jedi 支持从文档字符串中提取此信息,但我无法让它工作。有没有可能用jedi得到这样的东西?

中所述,最好的办法是安装 numpydoc 及其要求。

import numpydoc
import numpy as np

doc = numpydoc.docscrape.NumpyDocString(np.random.binomial.__doc__)

然后可以对其进行检查

In [45]: doc['Parameters']
Out[45]: 
[('n',
  'int or array_like of ints',
  ['Parameter of the distribution, >= 0. Floats are also accepted,',
   'but they will be truncated to integers.']),
 ('p',
  'float or array_like of floats',
  ['Parameter of the distribution, >= 0 and <=1.']),
 ('size',
  'int or tuple of ints, optional',
  ['Output shape.  If the given shape is, e.g., ``(m, n, k)``, then',
   '``m * n * k`` samples are drawn.  If size is ``None`` (default),',
   'a single value is returned if ``n`` and ``p`` are both scalars.',
   'Otherwise, ``np.broadcast(n, p).size`` samples are drawn.'])]

请注意,您必须进行一些后处理,例如将元组列表转换为字典。

In [46]: {t[0]: t[1] for t in doc['Parameters']}
Out[46]: 
{'n': 'int or array_like of ints',
 'p': 'float or array_like of floats',
 'size': 'int or tuple of ints, optional'}