Skip to content Skip to sidebar Skip to footer

Formatting Python Docstrings For Dicts

What's the recommended way of adding a docstring for a dictionary parameter? I can see multiple line docstring examples here. I need to document the input arguments to a function i

Solution 1:

I generally use the Google docstring style, so a dictionary parameter would look like:

deffunc(a_dict):
    """Some function to do something to a dictionary.

    Args:
      a_dict (dict of str: int): Some mapping, I guess?

    """
    ...

A function that takes **kwargs (note: this is not quite the same as having a dictionary parameter), would look like:

deffunc(**kwargs):
    """Some function to do stuff to arbitrary keyword arguments.

    Args:
        **kwargs: Arbitrary keyword arguments.

    Keyword Args:
        <kwarg_name> int: A description
        <kwarg_name_2> str: Another description
        <...>

    """
    ...

If there are specific parameters that should be present (e.g. your key1), they should be separate, not rolled into **kwargs.


In Python 3.x, you can also use function annotations:

deffunc(a_dict: dict):
    """Some function to do something to a dictionary."""
    ...

From Python 3.5, you can be even more explicit using typing:

from typing import Mapping

deffunc(a_dict: Mapping[str, int]):
    """Some function to do something to a dictionary."""
    ...

Solution 2:

For those using PyCharm: You can configure your default docstring formats in:

Preferences -> Tools -> Python Integrated Tools -> Docstrings

as of version 2019 the allowed options are: Plain, Epytext, reStructuredText, NumPy, Google. This functionality will automatically add a docstring skeleton once you've typed three double quotes " and hit enter.

Post a Comment for "Formatting Python Docstrings For Dicts"