2

In Javascript the coder can comment functions as follows using the @param and {string} options.

Python has a docstring, but reading the https://www.python.org/dev/peps/pep-0257/ Docstring Conventions i cannot see the equivalent to js.

Here is an example of a commented JS function:

/**
 * generate a random matrix
 * @param {number} n the height of the matrix
 * @param {number} m the width of the matrix
 */
function generateRandomMatrix(n, m) {
    mtrx = []
    for (let i = 0; i < n; i++) {
        mtrx.push([])
        for (let j = 0; j < m; j++) {
            mtrx[i].push(Math.round(Math.random()*10))
        }
    }
    return mtrx
}

What would be the python equivalent of the above comment (if such exists) ? In particular the @param and {number} features....

D.L
  • 4,339
  • 5
  • 22
  • 45

5 Answers5

1

Comments about arguments for functions in Python should also be included in docstrings, and then you can use Sphinx to automatically generate documentation. Sphinx was originally created for the Python documentation itself.

By default, Sphinx takes in the following format of docstring (see here):

:param [ParamName]: [ParamDescription], defaults to [DefaultParamVal]
:type [ParamName]: [ParamType](, optional)
...
:raises [ErrorType]: [ErrorDescription]
...
:return: [ReturnDescription]
:rtype: [ReturnType]

But you can use the Napoleon extension for Sphinx to read the much more readable (and therefore Pythonic) Google Style Docstrings:

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.
    """
Peter Prescott
  • 768
  • 8
  • 16
  • this is very good (in fact closest), but needs an extension [Napoleon extension for Sphinx] so went with a different answer as the preferred for now. – D.L Nov 06 '19 at 07:15
  • There's no need for an extension to write your docstrings like this, only to get Sphinx's autodocumentation to recognise the implications of what you're writing. @florian-bernard has given you an example using [NumPy style](https://www.sphinx-doc.org/en/1.5/ext/example_numpy.html#example-numpy), which you will also need the Napoleon extension for if you want Sphinx to write your documentation. – Peter Prescott Nov 08 '19 at 10:47
  • Of course, if you don't want Sphinx to write your documentation there's not yet an agreed Python standard. But since ["There should be one-- and preferably only one --obvious way to do it"](https://www.python.org/dev/peps/pep-0020/), I suspect there will be a standard at some point... – Peter Prescott Nov 08 '19 at 10:50
  • The method that i ticked is the closest in syntax. This does not require any extensions. Have tested in VS code (popular editor) and displays nicely when calling functions help (hover over function name). – D.L Nov 10 '19 at 09:17
1

In python you will comment like this in the docstring.

def generate_random_matrix(n, m):
    """generate a random matrix

     Parameters
     -----------------
     n : int
         the height of the matrix
     m : int 
         the width of the matrix

     Returns
     ----------
     An array with shape (n, m)
    """
    pass

There is several guideline have a look to this anwser.

Florian Bernard
  • 2,561
  • 1
  • 9
  • 22
0

You can write something like this in Python:

def get_full_name(first_name, last_name):
    """
    Construct full name from last name and first name

    :param first_name: first name of Person 
    :param last_name: last name of Person
    :return: concatenation of first and last name of Person
    """
    return first_name + last_name

Pycharm has a very good integration with python docstrings and can do much of manual work for you. There are a lot of possible formats. The example above shows probably more prevalent format that is used by Sphinx to generate documentation.

Take a look at this good description: What is the standard Python docstring format?

funnydman
  • 9,083
  • 4
  • 40
  • 55
  • docstring dictates that need space between top line and the other lines. The point is to replicate (or improve on) what exists in js. – D.L Nov 06 '19 at 07:16
0

Yes. They're called docstrings. See https://www.python.org/dev/peps/pep-0257/

def foo(bar: int, baz: int) -> int:
    """
    Add two numbers

    :param bar: explain bar
    :param baz: explain baz
    :return: int
    """
    return bar + baz
PartialOrder
  • 2,870
  • 3
  • 36
  • 44
0

Python has two types of comments. One for snippets, or single line comments (#) and another for multiple.

What you require would be the second one:

def pyhton_function(parameter1):
"""
This type of comment is preferable for longer text and function description.

Function returns double the parameter 1 received

"""
return parameter1

Might be worthy of note that anything inside " " cannot be a comment. i.e:

print("#this is not a comment")
  • This is correct. However, does not address the question which is to replicate the format of JS commenting. – D.L Nov 08 '19 at 08:20