Search code examples
pythonpython-attrs

Changing an attribute of a frozen class in attrs


import attr
@attr.s(slots=True, frozen=True)
class C:
    url = attr.ib(type=str)
    x = attr.ib()
    y = attr.ib()
    z = attr.ib(default=10)
    
    @y.default
    def _any_name_except_a_name_of_an_attribute(self):
        return self.x + 1
    
    @url.validator
    def map_url(self, attribute, value):
        if value == "apple":
            self.url = "mango"

print(C(x=4,y=5, url="apple"))

I was hoping to find a way to change the url when its initialized to a particular value, without loosing the frozen property of the class, would that be possible anyway?


Solution

  • Changing the passed-in value is what a converter is for:

    url = attr.ib(type=str, converter=lambda x: 'mango' if x=='apple' else x)