Search code examples
pythonpython-3.xdocstring

What is the `current` correct format for Python Docstrings according to PEP standards?


I've been looking all over the web for the current standards for Python Docstrings and I've come across different answers for different scenarios. What is the currently most-accepted and wide-spread docstring format that I should use? These are the ones that I've found so far:

Sphinx format (1): :param type name: description

Sphinx format (2): :py:param type name: description

NumPy format: Parameters: __________ param: description

Other formats:

Args: param (type): description

Parameters: param (type): description

I just want to document my code in a standard way that is accepted by almost every IDE (including VS Code and PyCharm) that also conforms to PEP and readthedocs, so I can also enable hover-over with mouse over the code to see description of the arguments.

I'm looking for current standards that are at least backwards compatible with Python 3.6 a since that's the base of the projects I work on.


Solution

  • The most widely accepted and standardized format for Python docstrings is the one defined in the PEP 257 - Docstring Conventions. This format is supported by most IDEs, including VS Code and PyCharm, and is also used by the Sphinx and NumPy documentation tools.

    The PEP 257 format for documenting function parameters is as follows:

    def function_name(param1: type, param2: type) -> return_type:
        """
        Description of the function and its arguments.
    
        Parameters:
        param1 (type): Description of the first parameter.
        param2 (type): Description of the second parameter.
    
        Returns:
        return_type: Description of the return value.
        """
    

    This format is compatible with Python 3.6 and later versions, and is also backward compatible with older versions of Python. It is recommended to follow this format for documenting function arguments in your code to ensure consistency and compatibility with different tools and IDEs.