3 ms·
This seems to be missing my biggest gripe: adding new attributes to classes outside of `__init__()` or `__slots__`. Sadly I have to deal with code that does thi
by xvedejas 5y ago
This seems to be missing my biggest gripe: adding new attributes to classes outside of `__init__()` or `__slots__`. Sadly I have to deal with code that does this with some frequency. Sometimes the attribute is added and accessed outside of instance methods entirely, ad-hoc by some caller. The result is total spaghetti. It becomes impossible to really know what the "interface" of the class is when you have to consider this, plus multiple inheritance, plus metaclasses, and then on top of that someone decided to hijack `__getattr__`. If I have to comb through the entire codebase to understand one class, that's a huge antipattern.
To avoid this, a lot of the new Python code I write is full of dataclasses. I do feel like I'm leaving a little bit of power on the table, but at least I can understand the code at a glance.
- hermitdev 5y ago> This seems to be missing my biggest gripe: adding new attributes to classes outside of `__init__()` or `__slots__`. You don't strictly need to use dataclasses to accomplish this. Yes, you get stronger guarantees with dataclasses (such as runtime checks, and these come with a runtime cost), but you can declare your members the same and use a properly configured linter that will tell you if you're assigning members from places you shouldn't. Personally, I tend use dataclasses more for plain old data types. As soon as one starts needing/wanting to control __init__, I find the utility of dataclasses drops precipitously. But, I do still annotate my (public) members with proper types, trying to avoid `Any` as much as possible.