OrenIshShalom
OrenIshShalom

Reputation: 7162

frozen data class with non trivial constructor

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

Upvotes: 0

Views: 202

Answers (1)

Shaukat
Shaukat

Reputation: 91

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.

Upvotes: 3

Related Questions