Is there any official way, using Python's type hinting system, to indicate that a function returns an equivalent or identical value to its input?
I know that type hints are typically not concerned with values, but it would be useful to have value typing for the specific case of "function returns its input or something ==
to its input".
What I'm hoping for is something like a TypeVar
, but which also contains information reflecting on the signature of the annotated function (with at least some official support in e.g. PyCharm/MyPy/etc.), similar to this:
Identity:
from typing import Identity
# Identity[0] indicates "returns the positional argument at index 0".
# Identity['foo'] would indicate "returns the kwarg named 'foo'".
def foo(arg1, arg2) -> Identity[0]:
return arg1
foo(object()) # Passes type checking
foo(1) # Fails type checking, as "is" identity won't work on all ints
Equivalence:
from typing import Equivalent
def foo(arg1: int) -> Equivalent[0]:
return (arg1 - 1) + 1
Equivalent
is largely a no-op, other than validating that its parameters make sense given the function signature.
Does such a thing exist? If not, is it feasible or misguided?
TypeVar
doesn't quite do what is needed here; it can indicate that the output type is the same as the input type, but doesn't concern itself with values.
I understand that value-constraining type systems are complex and not supported in Python, but am wondering if an exception has been made for the specific case of equal/identical return values.
Python does not have dependent types, unfortunately.
I find that super frustrating at times. I mean, one cannot even properly type the identity function...