Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: retrieve all properties of a class instance that uses the @property annotation

Is there an easy way to retrieve all properties of a class instance that use @property or property methods?

I have seen examples that use vars but that does not work a class like:

class Test(object):
   CONSTANT='SKIP ME'

   def __init__(self):
       self.my = "my"
       self.__wrapper = {Test.CONSTANT : "wrapped value"}

   @property
   def wrapped_value(self):
       return self.__wrapper[Test.CONSTANT]

Desired output would be dictionary with key/value.

dict = {"my":  "my", 
        "wrapped_value": "wrapped value",
        "__wrapper" : <dict>
}

As an added plus is there a way to get it to skip class level variables?

like image 733
Nix Avatar asked Jan 19 '23 12:01

Nix


1 Answers

A simple solution would be this:

instance = Test()
dict((p, getattr(instance, p))
     for p in dir(instance)
     if p not in dir(Test) or isinstance(getattr(Test, p), property))

It yields:

{'_Test__wrapper': {'SKIP ME': 'wrapped value'}, 'wrapped_value': 'wrapped value', 'my': 'my'}
like image 184
Gabi Purcaru Avatar answered Jan 31 '23 09:01

Gabi Purcaru