In the thread
the package attrs was mentioned as an alternative to @dataclass.
I’ve had a look at it, and it looks very promising. But it’s also a lot to wrap my head around.
Without rambling too much about slots vs dicts, automatic type checking and private attributes:
How do you use attrs? I’m looking for any techniques or tricks which you feel make your life easier or your code better ![]()
Edit after trying to read through the attrs docs:
Its
impossible!
I read
attrs.frozen(same_as_define )
Behaves the same as
attrs.definebut sets frozen=True and on_setattr=None.New in version 20.1.0.
so I try to find out what on_setattr does. All my searches eventually get back to
https://www.attrs.org/en/stable/api.html#attrs.define
where I couldn’t find the information I was looking for. So it pointed me on towards
https://www.attrs.org/en/stable/api-attr.html#attr.s
where I find
on_setattr (
callable, or a list of callables, orNone, orattrs.setters.NO_OP) –A callable that is run whenever the user attempts to set an attribute (either by assignment like
i.x = 42or by usingsetattrlikesetattr(i, "x", 42)). It receives the same arguments as validators: the instance, the attribute that is being modified, and the new value.If no exception is raised, the attribute is set to the return value of the callable.
If a list of callables is passed, they’re automatically wrapped in an
attrs.setters.pipe.
Which is still cryptic. Does this mean I can use on_setattr to get type checking when attributes are set? If so, how? If not, what else does this mean?
And to add to all that, I don’t appear to be able to read the source code on github.
None of which is any of your faults of course. So forgive my ranting. But it does add to my desire to see some good example code.