Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docstring format for input numpy arrays with mandatory datatype and dimensions

Tags:

python

numpy

For the sake of example, assume that I have a function that takes two numpy arrays as input parameters. The first array must be 2-dimensional and contain only floats. The second array must be 1-dimensional and contain only booleans.

Thus far I haven't really been able to find an existing convention for specifying input array datatype and dimensions in the docstring. One possible format (taking numpy docstring conventions as a basis) that I thought of was this:

def example_function(arr1, arr2):
    """This is an example function.

    Parameters
    ----------
    arr1 : ndarray(dtype=float, ndim=2)
        Array containing some kind of data.
    arr2 : ndarray(dtype=bool, ndim=1)
        Array containing some kind of mask.

   """

Can this be considered a 'correct' docstring format? (i.e. does it not break any rules of existing docstring conventions?)

like image 621
Xukrao Avatar asked Jan 08 '17 12:01

Xukrao


People also ask

What is the method used to get the dimensions of NumPy array?

len() is the Python built-in function that returns the number of elements in a list or the number of characters in a string. For numpy. ndarray , len() returns the size of the first dimension. Equivalent to shape[0] and also equal to size only for one-dimensional arrays.

What is docstring format?

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings.

What is docstring format in Python?

Python documentation string or commonly known as docstring, is a string literal, and it is used in the class, module, function, or method definition. Docstrings are accessible from the doc attribute (__doc__) for any of the Python objects and also with the built-in help() function.

What is the default data type of NumPy array?

The default data type: float_ . The 24 built-in array scalar type objects all convert to an associated data-type object.


1 Answers

Dimension and item types are extra information about your arrays which are function arguments. Thus based on documentation you need a style like follows:

"""
x : type
    Description of parameter `x`.
"""

Which in this case should be like:

"""
Parameters
----------
arr1 : ndarray
    2D array containing data with `float` type.
arr2 : ndarray
    1D mask array(containing data with boolean type).
"""

And note that if you want to make more clarifications you better to describe the data types and dimensions in your function description part as well.

like image 74
Mazdak Avatar answered Sep 24 '22 13:09

Mazdak