Home > Net >  Annotating python function that returns two different values
Annotating python function that returns two different values

Time:07-15

I have learned about python type hints and annotations, I know how to annotate a function that returns single value. In some cases we need to return different type of values, how to annotate in this situations.

def findElement(values: tuple, toFind):
    """Search for a value in the tuple and returns it index value."""
    for value in values:
        if value == toFind:
            return values.index(value)

    return "Requested value not found in the tuple.."

In the above program, If the requested value is present inside the tuple the function returns the index position of the value. If the requested value isn't present in the tuple the function returns some meaningful message. In this type of situation how to annotate this function.

I Have tried the following

def findElement(values: tuple, toFind) int or str:
    """Search for a value in the tuple and returns it index value."""
    for value in values:
        if value == toFind:
            return values.index(value)

    return "Requested value not found in the tuple.."

int or str

CodePudding user response:

Have a look on the library called typing. It supports type hints and is quite powerful. According to the documentation:

Union[X, Y] is equivalent to X | Y and means either X or Y.

from typing import Union

def findElement(values: tuple, toFind) -> Union[int, str]:
    """Search for a value in the tuple and returns it index value."""
    for value in values:
        if value == toFind:
            return values.index(value)

    return "Requested value not found in the tuple.."

As mentioned by @HughMungus (thank you) in the comments, you can also use the | operator in python 3.10. This would look like this:

def findElement(values: tuple, toFind) -> int | str:
    """Search for a value in the tuple and returns it index value."""
    for value in values:
        if value == toFind:
            return values.index(value)

    return "Requested value not found in the tuple.."
  • Related