maurizio nardò
maurizio nardò

Reputation: 63

How to massage numpy function arguments

Unluckily it is not possible to get numpy function arguments with inspect because they are not python code. However from the manual we can easily retrieve descriptions like

 uniform([low, high, size])
 triangular(left, mode, right[, size])

For purposes of linking to Excel, it would suffice to convert them to

 uniform(low=None, high=None, size=None)
 triangular(left, mode, right, size=None)

I'm sure this conversion can be automated, but my knowledge of string handling in Python is scarce and any suggestion on how to do it would be welcome.

Upvotes: 0

Views: 304

Answers (1)

xnx
xnx

Reputation: 25548

Ideally, you would use inspect to do this (and I suggest you look at this module) but a quick and somewhat dirty approach would be to parse the docstrings of the methods you want. This gives most of the method prototypes in the format you want (depending on how the docstrings are written), and you could then clean up the others manually:

import numpy as np

for method_name, method in np.random.__dict__.items():
    try:
        docstring_lines = method.__doc__.split('\n')
    except (AttributeError,):
        continue
    if len(docstring_lines) == 0:
        continue
    for line in docstring_lines:
        if method_name in line:
            print(line.strip())
            break

e.g.

power(a, size=None)
get_state()
multivariate_normal(mean, cov[, size])       # <-- NB needs cleaning up
gamma(shape, scale=1.0, size=None)
random_sample(size=None)
random_sample(size=None)
standard_cauchy(size=None)
choice(a, size=None, replace=True, p=None)
...

Upvotes: 1

Related Questions