4 ms·
You really, really, really shouldn't do this under any circumstances, though. If you find yourself messing with __dict__ you're down a hole, if you find yoursel
by jsmthrowaway 10y ago
You really, really, really shouldn't do this under any circumstances, though. If you find yourself messing with __dict__ you're down a hole, if you find yourself mutating it you're down an even deeper hole, if you find yourself calling locals() you probably forgot your shovel, and I'd hope that for all of that you'd have a better reason than minimizing code (that's way less readable, for example). I immediately get suspicious when I read code that interacts with __dict__ and I'm only sympathetic if you're cooking a metaclass or something equally arcane.
__slots__ also makes __dict__ nonexistent.
- chc 10y agoWell, yeah, but you could implement it without __dict__ just by doing something like: for attr, val in locals().items(): setattr(self, attr, val) It still feels pretty un-Pythonic either way.
- jsmthrowaway 10y agoBecause it is. There is zero reason to be clever here. Yeah, you have to be explicit in __init__. We are all used to it. The "a," "b," "c" examples are disingenuous though because you're often validating, enforcing types, converting, deriving other attributes... __init__ is documentation. I read it to understand what's going on.