Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get @property methods in asdict?

I have something like:

from attr import attrs, attrib

@attrs
class Foo():
    max_count = attrib()
    @property
    def get_max_plus_one(self):
         return self.max_count + 1

Now when I do:

f = Foo(max_count=2)
f.get_max_plus_one =>3

I want to convert this to dict:

{'max_count':2, 'get_max_plus_one': 3}

When I used attr.asdict(f) I do not get the @property. I get only {'max_count':2}.

What is the cleanest way to achieve the above?

like image 440
suprita shankar Avatar asked Aug 07 '18 19:08

suprita shankar


2 Answers

In general, you would have to iterate over the classes attributes and check for instances of property and then call the properties __get__ method using the instance. So, something like:

In [16]: class A:
    ...:     @property
    ...:     def x(self):
    ...:         return 42
    ...:     @property
    ...:     def y(self):
    ...:         return 'foo'
    ...:

In [17]: a = A()

In [18]: vars(a)
Out[18]: {}

In [19]: a.x
Out[19]: 42

In [20]: a.y
Out[20]: 'foo'

In [21]: {n:p.__get__(a) for n, p in vars(A).items() if isinstance(p, property)}
Out[21]: {'x': 42, 'y': 'foo'}
like image 156
juanpa.arrivillaga Avatar answered Sep 25 '22 11:09

juanpa.arrivillaga


I’m afraid that isn’t supported by attrs at the moment. You may want to follow/comment on https://github.com/python-attrs/attrs/issues/353 which may give you what you want eventually.

like image 43
hynek Avatar answered Sep 25 '22 11:09

hynek