Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify multiple return types in a function docstring in Python?

I am aware of the syntax used to build a docstring for Google style such as:

def function_with_types_in_docstring(param1, param2):
    """Example function with types documented in the docstring.

    `PEP 484`_ type annotations are supported. If attribute, parameter, and
    return types are annotated according to `PEP 484`_, they do not need to be
    included in the docstring:

    Args:
        param1 (int): The first parameter.
        param2 (str): The second parameter.

    Returns:
        bool: The return value. True for success, False otherwise.

    """

However, what if I have a function that can return multiple types depending on which branch of the code is executed? What would be a proper way to document this?

An example is below. What should be put into the Returns part?

def foo(x, y):
    """Dummy function.

    Args:
        x (int): integer
        y (int): integer

    Returns:
        list/dict: either list or a dict depending on...

    """
    if x > y:
        return [1, 2, 3]
    if x < y:
        return {1:2}

There is an example that shows two different possible return types:

def add2(a, b):
    """Add numbers or concatenate strings.

    Args:
      a (int/str): String or integer to be added
      b (int/str): String or integer to be added

    Returns:
      int/str: Result
    """
    pass

However, I wonder what would be the best way to provide both types AND description so that Napoleon would support it native and it would also be easy to read the docs.

Is using the int/str: %description% is the only way to handle multiple return types?

    Returns:
      int/str: integer if a > b and a string otherwise
like image 756
Alex Tereshenkov Avatar asked Feb 06 '19 11:02

Alex Tereshenkov


People also ask

Can a Python function have multiple return types?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

What is multiline docstring in Python?

Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. The summary line may be used by automatic indexing tools; it is important that it fits on one line and is separated from the rest of the docstring by a blank line.

What is the difference between a __ docstring __ and a comment?

Use comments to explain how code works. Comments are great for leaving notes for people working on your program. Docstrings provide documentation about functions, classes, and modules. Use docstrings to teach other developers how to use your program.

How are function docstrings specified?

It's specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, the docstring should describe what the function does, not how. What should a docstring look like? The doc string line should begin with a capital letter and end with a period.


2 Answers

If you want to use annotations to specify return types of different type depending of result of function, you can do it this way:

from typing import Type, Dict, Optional

def function(self) -> Optional[dict, str]:
    if self.result:
        return self.result
    else:
        return "Empty result"

Here you can find more info

like image 53
Juan Sánchez Avatar answered Oct 27 '22 19:10

Juan Sánchez


As mentioned above but use Union instead. (Optional is used if unsure whether to return the datatype, Union is for the case where one of the two datatypes is sure to be returned.)

from typing import Type, Dict, Union

def function(self) -> Union[dict, str]:
    if self.result:
        return self.result
    else:
        return "Empty result"
like image 43
Ricardo Del Rio Avatar answered Oct 27 '22 19:10

Ricardo Del Rio