47

I have class SomeClass with properties. For example id and name:

class SomeClass(object):
    def __init__(self):
        self.__id = None
        self.__name = None

    def get_id(self):
        return self.__id

    def set_id(self, value):
        self.__id = value

    def get_name(self):
        return self.__name

    def set_name(self, value):
        self.__name = value

    id = property(get_id, set_id)
    name = property(get_name, set_name)

What is the easiest way to list properties? I need this for serialization.

tefozi
  • 5,390
  • 5
  • 38
  • 52
  • 1
    Related: [python - Is there a built-in function to print all the current properties and values of an object? - Stack Overflow](https://stackoverflow.com/questions/192109/is-there-a-built-in-function-to-print-all-the-current-properties-and-values-of-a) – user202729 Feb 04 '21 at 00:11

2 Answers2

60
property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)]
Mark Roddy
  • 27,122
  • 19
  • 67
  • 71
40
import inspect

def isprop(v):
  return isinstance(v, property)

propnames = [name for (name, value) in inspect.getmembers(SomeClass, isprop)]

inspect.getmembers gets inherited members as well (and selects members by a predicate, here we coded isprop because it's not among the many predefined ones in module inspect; you could also use a lambda, of course, if you prefer).

darda
  • 3,597
  • 6
  • 36
  • 49
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • FYI you *must* call `getmembers` on a class, not an instance, if you want to get properties. Functions, on the other hand, can be obtained from either. – darda Aug 04 '23 at 20:09