如何在 python 中使用绝地获取 numpy 函数参数的类型(来自文档字符串) [英] How to get the types of numpy function arguments (from docstrings) using jedi in python

查看:28
本文介绍了如何在 python 中使用绝地获取 numpy 函数参数的类型(来自文档字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

理想情况下,我想要一个功能如下(适用于各种 numpy 函数):

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

parameter_types('np.random.binomial')

并返回:

{'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?

推荐答案

此答案中所示,您最好的选择是安装 numpydoc 及其要求.

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__)

然后可以检查

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

这篇关于如何在 python 中使用绝地获取 numpy 函数参数的类型(来自文档字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆