numpytypespython-jedi

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


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?


Solution

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