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?
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'}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With