In Python, you cannot directly get the return type of a function at runtime because Python is dynamically typed and functions do not carry explicit return type information unless you use type hints (annotations).
However, if the function f_impl has type annotations, you can inspect its annotated return type using the typing and inspect modules.
How to get the annotated return type of a function
python
from typing import get_type_hints
def example_func() -> int:
return 42
f_impl = example_func
# Get the return type annotation
type_hints = get_type_hints(f_impl)
return_type = type_hints.get('return', None)
print(return_type) # <class 'int'>
get_type_hints returns a dictionary of argument and return type annotations.
The return type is stored under the key 'return'.
If no return annotation is present, it returns None.
What if the function has no annotations?
If the function has no return type annotation, you cannot reliably get the return type without calling the function and inspecting the result:
python
result = f_impl()
print(type(result))
But this requires executing the function, which may not be desirable.
How to cast a variable to the return type?
Python does not have static casting like C++ or Java. You can only convert or coerce a variable to a type by calling the type as a constructor, e.g.:
python
if return_type is not None:
casted_var = return_type(some_var)
else:
casted_var = some_var # fallback if no return type info
But be careful: this only works if the return type is a callable type (like int, str, float, etc.) and the conversion is valid.
Summary
Use typing.get_type_hints(f_impl).get('return') to get the annotated return type.
If no annotation, you cannot get the return type without running the function.
Python casting is done by calling the type, e.g., int(x), not by explicit cast syntax.
Always check if the return type is available and callable before converting.
If you want, I can help you write a utility function that safely tries to cast a variable to the return type of a function! Would you like that?