5 ms·
I'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 sour
by ericfrederich 9y ago
I'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