1

I would like to know how to convert a python object from a dictionary (using python3 btw). I realize that this question has been asked (and answered) already (here). However, in my case the object is given entirely in terms of @property values, for example:

class Test: 
    @property  
    def value(self): 
        return 1.0       

Regarding conversion to a dictionary: The __dict__ dictionary of the Test class is empty, and consequently, the vars function does not work as expected:

>>> vars(Test()) 
{}

Still, I can use gettattr(Test(), 'value'), to obtain 1.0, so the value is present.

Note: The reason I am coming up with this apparently contrived example is that I am trying to convert a cython cdef class (containing parameters) to a dictionary. The recommended way to wrap c structures with properties using cython is indeed based on properties.

hfhc2
  • 4,182
  • 2
  • 27
  • 56
  • It sounds like you are trying to re-implement serialization, which is a difficult problem with plenty of corner cases, but one that has been largely solved. Why not use pickle? Otherwise you can try some `getattr`+`dir` solution, but you cannot easily go beyond "what all the values were and function with no arguments returned at time X" – Cireo May 21 '19 at 15:34

3 Answers3

0

Maybe you could abuse that:

In [10]: type(Test().__class__.__dict__['value']) is property                   
Out[10]: True

So you check the class of the object and if it has attribute of type property.

Here is how I would do it:

t = Test() 
dictionary = {attr_name: getattr(t, attr_name)  
              for attr_name, method in t.__class__.__dict__.items()  
              if isinstance(method, property)} 
0

I think you could use dir:

a = Test()
dir(a)

Output:

['__doc__', '__module__', 'value']

So you could maybe do something like:

d = {}
for attr in dir(a):
    if not attr.startswith("__"):
        d[attr] = getattr(a, attr)

Output:

d = {'value': 1.0}
Zionsof
  • 1,196
  • 11
  • 23
0

It is even worse that that. You could imagine to build an instance __dict__ at init time, but that would not solve anything, except for read_only constant properties. Because the value in the dict will be a copy of the property at the time it was taken, and will not reflect future changes.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252