Skip to content
Advertisement

How to type hint a function’s optional return parameter?

How do I type hint an optional output parameter:

def myfunc(
        x: float, 
        return_y: bool = False
        ) -> float, Optional[float] : # !!! WRONG !!!

    # ... code here
    #
    # y and z are floats

    if return_y:
        return z, y

    return z

— edit

This seem to work:
-> Tuple[float, Union[None, float]] :

but that is so ugly and seems to overwhelm the fact that typically it will only return a simple float. Is that the correct way to do this?

See answer below for correct way.

— edit 2

This question was flagged as duplicate of that question. However, that question is about Union return type, while this question is about Optional return type.


Note: this design is not a good practice and should be avoided in favour of a consistent return type. Still, in case it has to be done, by optional output parameter it is meant a parameter that may not be returned depending on an input argument’s flag.

Advertisement

Answer

Since Python 3.10 and PEP 604 you now can use | instead of Union.

The return type would be float | Tuple[float, float]


The right type hint would be:

from typing import Tuple, Union


def myfunc(x: float, return_y: bool = False) -> Union[float, Tuple[float, float]]:
    z = 1.5

    if return_y:
        y = 2.0
        return z, y

    return z

However, it is usually not a good practice to have these kinds of return. Either return something like Tuple[float, Optional[float]] or write multiple functions, it will be much easier to handle later on.

More about return statement consistency:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement