Writing docstrings - specifying functions arguments and returns

Suppose I have a function, say:

>>> def foo(a):
        return a+1

I want to write a documentation string for it.

what is the convention in specifying in the docstring that it takes a and returns a+1?


Asked by: Rafael657 | Posted: 30-11-2021






Answer 1

The idea of a docstring is to give the user a basic overview of what's going in and coming out without telling them too much about how that happens. In this case:

def foo(a):
    """Take a number a and return its value incremented by 1."""
    return a + 1

For a less trivial example, I like the one in Dive Into Python's section on documenting functions:

def build_connection_string(params):
    """Build a connection string from a dictionary of parameters.

    Return string."""

Obviously, a more complicated function requires a bigger docstring. Just make sure the docstring is talking about what's happening (what's getting passed in, what's being returned) instead of how that's happening (implementation details should not be included).

Answered by: David611 | Posted: 01-01-2022



Answer 2

PEP 257 should help!

Answered by: Emma644 | Posted: 01-01-2022



Answer 3

For Python conventions (about this and other topics), I'd suggest first trying the Python Enhancement Proposals.

Python PEP 257 suggests for one line docstrings to specify your function like so:

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

but not like this:

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

because the latter example can be divined through other means.

Only glanced through them but the links from the PEP look to go to other PEP's that get into the nitty-gritty of docstrings.

As a general note I'd browse through the PEPs if you haven't yet as there are some interesting topics about Python design decisions and philosophy.

Answered by: Chelsea762 | Posted: 01-01-2022



Answer 4

I personally like the style the builtins use.

>>> help(len)

len(...)

len(object) -> integer

Return the number of items of a sequence or mapping.

Answered by: Byron333 | Posted: 01-01-2022



Similar questions

python - Is there a way to keep docstrings separate from the functions they document?

I'm working on a module with many small functions but whose docstrings tend to be quite long. The docstrings make working on the module irritating as I have to constantly scroll over a long docstring to find a little bit of actual code. Is there a way to keep docstrings separate from the functions they document? I'd really like to be able to specify the docstrings at the end of the file away from the code or, even...


Adding docstrings to python functions pulled from dll using ctypes

I'm trying to create a bunch of python functions from a windows dll, and would like to have docstrings attached to each new function. My current code: import ctypes lib=ctypes.WinDLL('example.dll') VCS_OpenDevice=lib['VCS_OpenDevice'] VCS_OpenDevice.restype=ctypes.c_double When i run this script in my interpreter and try to use the function, I get the 'no docstring' message. ...


In python, how to print the docstrings of all functions defined in an imported module, without the functions that the imported module itself imported?

The following code prints each function's docstring from an imported module. However, the results incude some functions that were not defined within the module, but rather, were imported by the module. import inspect import my_module all_functions = inspect.getmembers(my_module, inspect.isfunction) for i in all_functions: print i[0] # print function name ...


python - Is it possible to bulk-add docstrings to all the functions in PyCharm?

I have a python project that many of the functions and classes missing docstrings. I know that PyCharm can automatically add docstrings by the Insert documentation string stub command using intention action. However, for large number of methods and functions, it is tedious. Is there a method to bulk add docstrings to all the functions at once? then I will fill what is necessary manually. If not in PyCharm,...


python - Link to See Also functions in Sphinx docstrings

When I'm writing docstrings for my python packages, I just cannot make the functions appear in See Also section linkable, especially for the functions that belongs to other modules, could some one help me to fix this issue, thanks! BTW, I'm following the numpy docstring rules, and all the API docs is generated from sphinx-autogen, below is a basic example: In module mod1


python - Docstrings for data?

Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion? class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!"""


syntax error - python docstrings

ok so I decided to learn python (perl, c, c++, java, objective-c, ruby and a bit of erlang and scala under my belt). and I keep on getting the following error when I try executing this: Tue Jul 21{stevenhirsch@steven-hirschs-macbook-pro-2}/projects/python:-->./apache_logs.py File "./apache_logs.py", line 17 print __doc__ ^ SyntaxError: invalid syntax #!/usr/local/bin/python """...


Python decorator handling docstrings

I have a problem using docstrings with decorators. Given the following example: def decorator(f): def _decorator(): print 'decorator active' f() return _decorator @decorator def foo(): '''the magic foo function''' print 'this is function foo' help(foo) Now the help doesn't show me the docstring of foo as expected, it shows: Hel...


Are Python docstrings and comments stored in memory when a module is loaded?

Are Python docstrings and comments stored in memory when a module is loaded? I've wondered if this is true, because I usually document my code well; may this affect memory usage? Usually every Python object has a __doc__ method. Are those docstrings read from the file, or processed otherwise? I've done searches here in the forums, Google and...


How to fold long docstrings in python source code in VIM?

Does anybody know of a method, or perhaps a plugin, that will automatically fold long docstrings in Python? I have docstrings in my code that span several pages, so it is troublesome to keep paging through them. The other tricky part is that there is embedded python testing code in the docstrings, so that might make parsing them difficult. Note that I only need to automatically fold the entire docstr...


python - Using shorter textwidth in comments and docstrings

From the mighty PEP 8: [P]lease limit all lines to a maximum of 79 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended. When editing Python code in Vim, I set my textwidth to 79, and Vim au...


python - Is there a way to keep docstrings separate from the functions they document?

I'm working on a module with many small functions but whose docstrings tend to be quite long. The docstrings make working on the module irritating as I have to constantly scroll over a long docstring to find a little bit of actual code. Is there a way to keep docstrings separate from the functions they document? I'd really like to be able to specify the docstrings at the end of the file away from the code or, even...


How do I change Emacs's font face for Python docstrings?

I'm just starting to learn Python and use Emacs as my editor. Currently, Emacs uses the same color for normal strings (single quotes) and docstrings (triple quotes). I want docstrings to be a different color, so I used the 'Options->Customize Emacs' menu option to change 'font-lock-doc-face' to a new color and saved the changes. However, Emacs continues to keep docstrings the same color as normal strings. Changing the ...


python - Put docstrings on special methods?

I'm trying to decide what information to put in the class docstring and what to put in the __init__ method docstring. Up until now I've been putting an overview of the class and how to work with it in the class docstring, while stuff directly related to initialization (argument details etc.) I put in the __init__ docstring. Today I started wondering if this was the right way of doing it, s...


static analysis - How to calculate lines of code, comments and docstrings for a Python module?

Is there a tool or snippet that produces the following output in some form: lines_of_code = 98 lines_of_comments = 24 lines_of_documentation = 11 NOTE 1: I will then try to feed this data to Jenkins to graph. NOTE 2: I am aware that CLOC co...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top