I have a function that can only return a
, b
or c
, all of them are of type T
. And I want to include this fact in the signature because of the special meaning they carry in the context of the function. How do 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 returns those specific values.
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments