attrs
attrs copied to clipboard
Extended properties
It would be a cool feature to have properties that participate in asdict method.
@attr.s
class SomeClass:
@attr.property(asdict=True)
def some_dynamic_attr(self):
return True
print(asdict(SomeClass()))
>> {'some_dynamic_attr': True}
This seems out of scope to me… as it's a start at extensible serialization, which isn't what attrs
is trying to provide.
I've been thinking about how to add first-class property support in attrs before, because I keep running into this limitation myself. Haven't come up with anything useful so far though...
@andvikt Try this https://github.com/pwwang/attr_property ?
This would be a huge advantage of attrs
over dataclass
, as we can see in this open issue.
To give a minimum reproducible snippet of the problem, see this example:
from attrs import define
@define
class Vehicle:
wheels: int = 4
@property
def wheels(self) -> int:
print("getting wheels")
return self._wheels
@wheels.setter
def wheels(self, wheels: int):
print("setting wheels to", wheels)
self._wheels = wheels
v = Vehicle()
print(v.wheels) # -> should print 4
# prints <property object at 0x...>
The corresponding regular class with regular __init__
don't have any problem
class Vehicle:
def __init__(self, wheels:int = 4) -> None:
self.wheels = wheels
@property
def wheels(self) -> int:
print("getting wheels")
return self._wheels
@wheels.setter
def wheels(self, wheels: int):
print("setting wheels to", wheels)
self._wheels = wheels
v = Vehicle()
print(v.wheels)
# prints 4
I know that happens because of this limitation. I do not know how one would solve this.
This workaround may give a hint.
Can't say if #353 is related