1

I am trying to list the settable properties of a class.

Using 2 answers: list properies of class and know if properies is settable.

For this class it work.

class A(object):
    def __init__(self):
        self._var_a = 1
        self._var_b = 2

    @property
    def var_a(self):
        return self._var_a
    @var_a.setter
    def var_a(self, value):
        self._var_a = value

    @property
    def var_b(self):
        return self._var_b

    @property
    def settable_property(self):
        settable_properties = {}
        for name, value in self.__class__.__dict__.iteritems():
            if isinstance(value, property) and value.fset is not None:
                settable_properties[name] = value
        return settable_properties

a = A()
a.settable_property 

I get {'var_a': property_object}.

But for a child class:

class B(A):
    def __init__(self):
        self._var_c = 1
        super(B, self).__init__()

    @property
    def var_c(self):
        return self._var_c
    @var_c.setter
    def var_c(self, value):
        self._var_c = value

b = B()
b.settable_property

I only get {'var_c': property_object}. I expected {'var_c': property_object, 'var_a': property_object}

I know it's due to self.class.dict return only the dict of the class and not of all the parent class. class namespace

So my question is their a way to get a equivalent of dict of the class and all it's parent?

I tried using dir(self), it do get me the name of the all the property but it doesn't give me the property objects. And using getattr(self, 'property_name') return the .fget() value of the property and not the property object.

vars(B) also return only {'var_b': property object}

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Yassine Faris
  • 951
  • 6
  • 26

1 Answers1

1

Found a solution using inspect.getmembers

def settable_property(self):
    settable_properties = {}
    for name, value in inspect.getmembers(self.__class__):
        if isinstance(value, property) and value.fset is not None:
            settable_properties[name] = value
    return settable_properties

An other solution using dir and getattr:

def settable_property(self):
    settable_properties = {}
    for name in dir(self.__class__:
        value = getattr(self.__class__, name)  # getattr on class not instance
        if isinstance(value, property) and value.fset is not None:
            # WARNING this property object is not bound to an instance
            # if you want to use it either pass the instance like:
            #     value.fget(self)
            # or bind the function to the instance: 
            #      value = value.fget.__get__(self, self.__class__)

            settable_properties[name] = value 
    return settable_properties
Yassine Faris
  • 951
  • 6
  • 26