Python: Dynamically access type annotation of a property

Viewed 489

Given the following class:

class Test:
    def __init__(self, test_prop: str):
        self.__test_prop = test_prop
    @property
    def test_prop(self) -> str:
        return self.__test_prop

How can I dynamically access the type annotation of test_prop either from the class or an instance?

The following does not work:

t1 = Test('a')
import inspect
inspect.signature(t1.test_prop)
# TypeError: 'a' is not a callable object
1 Answers

You need to get the property object itself, without doing the dynamic lookup. The inspect module has a function, inspect.getattr_static for that. Then we can use signature to get the signature of the fget attribute of that object. That's where property objects store the function they use to do the dynamic lookup.

from inspect import getattr_static, signature

print(signature(getattr_static(t1, 'test_prop').fget))
# (self) -> str

The other two functions of a property are stored in the attributes fset and fdel

Related