4

I am confused about the use of type hints and docstrings. Aren't they duplicate information?

For example:

def my_func(name: str):
    """
    print a name.
    
    Parameters
    ----------
    name : str
       a given name
    """
    print(name)

Isn't the information name: str given twice?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Alex
  • 912
  • 2
  • 7
  • 19
  • Nobody told you that doing this kind of docstring is required – U13-Forward Sep 25 '21 at 02:00
  • You probably don't need to specify the type again in the docstring if the function definition already contains that information, for a concrete example, you can look at the Google style guide (not that you need to follow it or anything just for some inspiration). – Sash Sinha Sep 25 '21 at 02:05
  • @U12-Forward if I google "python docstring" the first a few results have the docstring. If I further search "python docstring numpy" as I am in the scientific community, the first ones all have type hints in the docstring. Yet it seems there's no standard type hint styles in docstring hence very confusing. – Alex Sep 25 '21 at 03:34

1 Answers1

5

Putting the type as a type hint and as part of the docstring would be redundant. It is also prone to human errors since one could easily forget updating one of them, thus effort is constantly needed to keep them both in sync.

The documentation for type hints also mentions it:

Docstrings. There is an existing convention for docstrings, based on the Sphinx notation (:type arg1: description). This is pretty verbose (an extra line per parameter), and not very elegant. We could also make up something new, but the annotation syntax is hard to beat (because it was designed for this very purpose).

But all of this depends on your usecase.

  • If you are using a static-type checker such as MyPy (e.g. it would fail if you passed an int 123 to a variable with type hint str) or an IDE such as PyCharm (e.g. it would highlight inconsistencies between type hint and passed arguments), then you should keep on using type hints. This is the preferable way, as it points out possible errors in the code you've written.
  • If you are using tools such as Sphinx, or Swagger, or something else, note that these tools display your classes and methods along with their docstrings for the purposes of documentation. So if you want to maintain such documentation for clarity to other readers and want to have the types included, then you might want to put the type hint in the docstring as well. But if you think such detail isn't needed as most of the time only the description in the docstring is relevant, then there is no need to add the type hint in the docstring.

In the long run, the more sustainable way is to have those tools (Sphinx, Swagger, etc.) use the type hint as part of the documentation instead of relying solely on the text in the docstring. For sphinx, I found this library sphinx-autodoc-typehints that performs it already.

Allowing you to migrate from this:

def format_unit(value, unit):
    """
    Formats the given value as a human readable string using the given units.

    :param float|int value: a numeric value
    :param str unit: the unit for the value (kg, m, etc.)
    :rtype: str
    """
    return '{} {}'.format(value, unit)

to this:

from typing import Union

def format_unit(value: Union[float, int], unit: str) -> str:
    """
    Formats the given value as a human readable string using the given units.

    :param value: a numeric value
    :param unit: the unit for the value (kg, m, etc.)
    """
    return '{} {}'.format(value, unit)

So, it seems like there are already enhancements on this topic that will make the definition of types more consistent and less redundant.

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
  • 1
    For IDEs, it also helps with intellisense/autocompletion. At least for VS Code, typing the function params will help VS Code suggest methods/attributes on `.`. – Gino Mempin Sep 25 '21 at 02:44
  • Thanks for the explanation. To summarize: use Typing is preferred to giving type hints in docstring. Question: What is [this](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_numpy.html) about? i.e. I thought the numpy style is one of the most popular; is it actually obsolete and my misconception comes from my limited eyesight within the scientific community? – Alex Sep 25 '21 at 03:40
  • @GinoMempin "for IDEs, it also..." which does "it" refer to? Typing? – Alex Sep 25 '21 at 03:43
  • @Alex the link you added is targeted for Sphinx usage, which as I said would display the docstrings in the generated documentation. If you want to follow that convention, then there is no problem, you just have to be consistent. But as already pointed out in the type hint doc, adding the type hint annotation is more flexible as it can be used for static-type checks and is also self-documenting. The answer to your question might be to wait/request/support those documenting tools such as Sphinx to read from the type hint. I updated my answer to show a sample library. – Niel Godfrey Pablo Ponciano Sep 25 '21 at 04:00
  • 1
    @Alex Sorry, "it" refers to type hints. I find typehinting params and vars helps in autocompletion. – Gino Mempin Sep 25 '21 at 05:52