5

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?

Marc
  • 3,386
  • 8
  • 44
  • 68

1 Answers1

8

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))
user2357112
  • 260,549
  • 28
  • 431
  • 505