PEP 257 return type update

PEP 257 currently says:

  • The one-line docstring should NOT be a “signature” reiterating the
    function/method parameters (which can be obtained by introspection).
    Don’t do::

    def function(a, b):
        """function(a, b) -> list"""
    

    This type of docstring is only appropriate for C functions (such as
    built-ins), where introspection is not possible. However, the
    nature of the return value cannot be determined by introspection,
    so it should be mentioned. The preferred form for such a docstring
    would be something like::

    def function(a, b):
        """Do X and return a list."""
    

    (Of course “Do X” should be replaced by a useful description!)

Which is now anachronistic. Could we change it to something like:

  • The one-line docstring should NOT be a “signature” reiterating the
    function/method parameters (which can be obtained by introspection).
    Don’t do::

    def function(a, b):
        """function(a, b) -> list"""
    

    Use PEP 484 Type Hints <https://peps.python.org/pep-0484/>:

    def function(a:T, b:U)->list:
        """Do X."""
    

    where T and U are the types of a and b. (Of course “Do X” should be
    replaced by a useful description!)

2 Likes

Type hints are optional and should remain so. The docstring should really say a list of what, where what is typically not something that can easily be included in the type hint. I would actually say that the one line should be “Return a list of blobs” If the something done needs to be specified, the docstring should have more lines.

3 Likes

Imo docstrings should not state something already obvious. If the return type is expressable in the current type system, and the minimum required version is >= 3.6 (introduction of typehints iirc), then you should not ever discuss the types of parameters or the Return-Type in the docstrings, unless it’s controversial, special or something similar.

That means that imo typehints should be enough (at least in most cases).

1 Like

How about?

  • The one-line docstring should NOT be a “signature” reiterating the
    function/method parameters (which can be obtained by introspection).
    Don’t do::
def function(a, b):
    """function(a, b) -> list"""

The preferred form for such a docstring would be something like:

    """Do X and return Y."""

(Of course “Do X and return Y” should be replaced by a useful description!)