Search code examples
pythonconstructorimmutabilitypython-attrs

frozen data class with non trivial constructor


  • I'm trying to define a frozen data class with a non-trivial constructor
  • That is, the constructor needs to "tweak" the input before it initializes the corresponding data member:
from attrs import frozen

@frozen(init=False)
class Person:

    name: str

    def __init__(self, raw_name: str) -> None:
        
        if ":" in raw_name:
            self.name = raw_name[raw_name.find(":") + 1:]
        else:
            self.name = raw_name

p = Person("Oren:IshShalom")

When I check the documentation, I see that

If a class is frozen, you cannot modify self in attrs_post_init or a self-written init. You can circumvent that limitation by using object.setattr(self, "attribute_name", value).

But I'm not really sure how to do what they suggest


Solution

  • Replace

    self.name = raw_name[raw_name.find(":") + 1:]
    

    with

    object.__setattr__(self, "name", raw_name[raw_name.find(":") + 1:])
    

    This works on my end.