I'm looking for a way to extract the return type annotation of a property from a class, e.g.:
class Test:
@property
def foo(self) -> int:
return 1
print(return_type_extract(Test, 'foo')) # <class 'int'>
For standard methods this can be done like so:
import inspect
class Test:
def foo(self) -> int:
return 1
def return_type_extract(cls: type, method_name: str) -> type:
method = getattr(cls, method_name)
return inspect.signature(method).return_annotation
print(return_type_extract(Test, 'foo')) # <class 'int'>
This method however does not work for the @property decorator, as it raises an error inside inspect.signature. I've looked at an equivalent for properties in the inspect library, but so far no luck.
If the retrieved attribute is a property object, we can access its getter method (
.fget) to get the underlying function. Then we useget_type_hints()to extract the return type annotation from the underlying function.Like this :