get_return_type¶
-
privex.helpers.common.
get_return_type
(f: callable) → Optional[Union[type, object, callable]][source]¶ Extract the return type for a function/method. Note that this only works with functions/methods which have their return type annotated, e.g.
def somefunc(x: int) -> float: return x * 2.1
Attention
If you want to extract a function/method return type and have any Generic
typing
types simplified down to their native Python base types (important to be able to compare withisinstance()
etc.), then you should useextract_type()
instead (handles raw types, objects, and function pointers)Example 1 - Extracting a generic return type from a function:
>>> def list_wrap(v: T) -> List[T]: ... return [v] ... >>> rt = get_return_type(list_wrap) typing.List[~T] >>> rt._name # We can get the string type name via _name 'List' >>> l = rt.__args__[0] # We can access the types inside of the [] via .__args__ ~T >>> l.__name__ # Get the name of 'l' - the type inside of the [] 'T'
Example 2 - What happens if you use this on a function/method with no return type annotation?
The answer is: nothing - it will simply return
None
if the function/method has no return type annotation:>>> def hello(x): ... return x * 5 >>> repr(get_return_type(hello)) 'None'