3 ms·
I just discovered attrs(http://www.attrs.org/en/stable/ http://www.attrs.org/en/stable/). On paper it looks great, seems to reduce boilerplate, has support for
by abhirag 9y ago
I just discovered attrs(http://www.attrs.org/en/stable/ http://www.attrs.org/en/stable/). On paper it looks great, seems to reduce boilerplate, has support for immutability and slots too and claims to have no runtime overhead. If anybody here has experience using it, would love to hear from you. Is it as good as it looks on paper? Do you recommend using it?
- ericfrederich 9y agoI've been using it here and there in place of named tuples and data-only classes. It is very convenient. I had a project where I had to connect to a data source and serialize some data. When I needed to add an attribute all I had to do was add it to two places: the class itself, and the @classmethod constructor. So in this case I got the serialization for free, but that's all I was using. In reality I also got __repr__, __cmp__, etc, etc for free too, I just wasn't using it. Serialization was free because attr.asdict() knows which attributes are attr.ib() attributes. @attr.s() class Foo: bar = attr.ib() spam = attr.ib() eggs = attr.ib() # added this line @classmethod def from_something_else(cls, x): return cls( bar=x.bar.name, spam=x.spam, eggs=x.get_eggs().blah(), # and this line ) with open('blah.json', 'w') as fout: json.dump(fout, attr.asdict(o)) # got serialization for free