How to get property return type annotation?

43 views Asked by At

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.

1

There are 1 answers

3
TheHungryCub On BEST ANSWER

If the retrieved attribute is a property object, we can access its getter method (.fget) to get the underlying function. Then we use get_type_hints() to extract the return type annotation from the underlying function.

Like this :

from typing import get_type_hints

class Test:
    @property
    def foo(self) -> int:
        return 1

def return_type_extract(cls: object, property_name: str) -> type:
    property_obj = getattr(cls, property_name)
    if isinstance(property_obj, property):
        property_obj = property_obj.fget
    return get_type_hints(property_obj).get('return')

print(return_type_extract(Test, 'foo'))  # <class 'int'>