47

What is the docstring convention when a function doesn't return anything?

For example:

def f(x):
    """Prints the element given as input

    Args:
        x: any element
    Returns:
    """
    print "your input is %s" % x
    return

What should I add after Returns: in the docstring? Nothing as it is now?

Ricky Robinson
  • 21,798
  • 42
  • 129
  • 185

2 Answers2

57

You should use None, as that is what your function actually returns:

"""Prints the element given as input

Args:
    x: any element
Returns:
    None
"""

All functions in Python return something. If you do not explicitly return a value, then they will return None by default:

>>> def func():
...     return
...
>>> print func()
None
>>>
  • 1
    I don't understand exactly. Do you mean if it is OK to just do `return` instead of `return None`? Yes, that is fine. Adding the `None` in that case is redundant. It should be considered understood that Python functions return `None` if you do not return a value. –  Jan 05 '15 at 16:58
  • 6
    If you mean "is it wrong to omit 'Returns:' entirely from your docstring if you don't have any explicit return statements?", I tentatively say "no". [PEP 257](https://www.python.org/dev/peps/pep-0257/) says to describe the return value "if applicable", so you could argue that you don't have to describe it if it doesn't matter. – Kevin Jan 05 '15 at 17:00
  • 1
    @keyser - In addition to what Kevin said, the OP could be doing this for code analysis tools. That, or he has to follow some convention set by his superiors (ugh. I hate those ;) –  Jan 05 '15 at 17:01
  • @iCodez Yup, definitely :p Though they're there to prevent arguments :p. My main curiosity was mainly what PEP/people say/do. Also, thanks Kevin – keyser Jan 05 '15 at 17:41
1

You can simply omit it. And for simplicity and reduced noise you probably should omit it.

The docstring style you used is "Google Style" and the style guide says this about the Returns section:

If the function only returns None, this section is not required.

https://google.github.io/styleguide/pyguide.html#doc-function-returns

bugmenot123
  • 1,069
  • 1
  • 18
  • 33