attrs icon indicating copy to clipboard operation
attrs copied to clipboard

Extended properties

Open andvikt opened this issue 5 years ago • 4 comments

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}

andvikt avatar May 28 '19 18:05 andvikt

This seems out of scope to me… as it's a start at extensible serialization, which isn't what attrs is trying to provide.

wsanchez avatar May 28 '19 20:05 wsanchez

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...

hynek avatar Jun 22 '19 09:06 hynek

@andvikt Try this https://github.com/pwwang/attr_property ?

pwwang avatar Dec 16 '19 05:12 pwwang

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

Diogo-Rossi avatar Apr 01 '22 06:04 Diogo-Rossi