Search code examples
pythonintrospectioninspect

get source code for method with @property decorator python


Suppose I have a class MyClass that has a property created with the @property decorator, like this:

class MyClass(object):
    @property
    def foo(self):
        if whatever:
            return True
        else:
            return False

Suppose I want to use the python inspect module to get the source code that defines the property. I know how to do this for methods (inspect.getsource) but I don't know how to do this for property objects. Anyone know how to do this?


Solution

  • Access the underlying getter function through the property's fget attribute:

    print(inspect.getsource(MyClass.foo.fget))
    

    If it has a setter or deleter, you can access those through fset and fdel:

    print(inspect.getsource(MyClass.foo.fset))
    print(inspect.getsource(MyClass.foo.fdel))