Copperfield Copperfield - 2 months ago 9
Python Question

what is correct way of type hint a function that return only a specific set of values?

I have a function that can only return

a
,
b
or
c
all of them are of type
T
but I want to make part of its signature this fact because of the special meaning they carry in the context of the function, how I do that?

currently I use this

def fun(...) -> "a or b or c":
#briefly explain the meaning of a, b and c in its docstring


is that the correct one?

I know that I can do this

def fun(...) -> T:
#briefly explain the meaning of a, b and c in its docstring


but as I said I want to express in the signature that the function only return those specific values

Answer

You can't specify that your function returns only a subset of a type's values using type hinting alone. As the name implies, type hinting is all about types not values.

However, you can create a new enum.Enum subtype that only has the values you're going to return and use it in the function. Then you can type hint that you're returning the enum type.

import enum

class cmp_results(enum.IntEnum):
    less = -1
    equal = 0
    greater = 1

def my_cmp_function(x, y) -> cmp_results:
    if x < y: return cmp_results.less
    elif x == y: return cmp_results.equal
    else: return cmp_results.greater

This may be overkill. Just hinting int as the return type (and documenting the specific values) is probably good enough.