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

≯℡__Kan透↙ 提交于 2021-02-11 09:39:13

问题


Ideally I would like a function which works as follows (for all kinds of numpy functions):

parameter_types('np.random.binomial')

and returns:

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

I understand that jedi has some support for extracting this information from docstrings, but I cannot make it work. Is it possible to get something like this using jedi?


回答1:


As found in this answer, your best bet is to install numpydoc and its requirements.

import numpydoc
import numpy as np

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

wich can then be inspected

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.'])]

Note that you'll have to do some postprocessing such as converting the list of tuples to a dictionary.

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'}


来源:https://stackoverflow.com/questions/42848057/how-to-get-the-types-of-numpy-function-arguments-from-docstrings-using-jedi-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!