2

Is there a way to programmatically lookup the names of all @property decorated methods in a class using the inspect module?

Greg Smethells
  • 410
  • 4
  • 17
  • This appears to be the first question of its kind? http://stackoverflow.com/search?q=%40cached_property+inspect – Greg Smethells Jan 06 '16 at 20:41
  • I've scoured the web and the docs and I do not see a way to do it. – Greg Smethells Jan 06 '16 at 20:41
  • I wager that @AlexMartelli will get first post. – Greg Smethells Jan 06 '16 at 21:01
  • While I don't think there's an `inspect` function to do this automatically, you could quite easily write your own code iterating over the class's attributes: `[name for name, obj in vars(some_class).items() if isinstance(obj, property)]`. This might not work for other decorators though, if they don't create objects of some easy to recognize type. – Blckknght Jan 06 '16 at 21:39

1 Answers1

3

My version:

import inspect


class A(object):
    @property 
    def name():
        return "Masnun"


def method_with_property(klass):
    props = []

    for x in inspect.getmembers(klass):

        if isinstance(x[1], property):
            props.append(x[0])

    return props

print method_with_property(A)

Another version from another thread:

import inspect

def methodsWithDecorator(cls, decoratorName):
    sourcelines = inspect.getsourcelines(cls)[0]
    for i,line in enumerate(sourcelines):
        line = line.strip()
        if line.split('(')[0].strip() == '@'+decoratorName: # leaving a bit out
            nextLine = sourcelines[i+1]
            name = nextLine.split('def')[1].split('(')[0].strip()
            yield(name)

class A(object):
    @property 
    def name():
        return "Masnun"



print list(methodsWithDecorator(A, 'property'))

The code of methodsWithDecorator is taken from the accepted answer on this thread: Howto get all methods of a python class with given decorator

Community
  • 1
  • 1
masnun
  • 11,635
  • 4
  • 39
  • 50