I consider __dict__ an implementation detail
Almost all Python objects implement their namespace as a Python
dictionary, which they expose as their __dict__ member. You can do
interesting things by playing around with this dictionary directly,
for example adding bulk name/value mappings to an object by just doing
something like obj.__dict__.update(pairs).
I don't like doing this, because I consider __dict__ to be an
implementation detail, or at least fairly magical, and thus I feel that
I shouldn't be playing around with it; I prefer to get the same results
with more general higher-level things like setattr. Seeing code that
uses __dict__ makes me vaguely twitchy.
In some sense __dict__ isn't merely an implementation detail, because it is sufficiently well documented (and necessary for things like __setattr__) that it will be sticking around. In another sense it is, because not all objects have a __dict__ (and even when they have one, not all of their attributes necessarily show up there), so you can't assume that you can use it to fish around in an arbitrary object. If you do anyways, you're making assumptions about how other code implements its objects that may come to bite you someday.
(The most obvious case of objects without a __dict__ is instances of classes that use __slots__.)
I'm aware that this is just a personal twitch, and possibly a silly one at that. A lot of Python programmers are perfectly happy to use __dict__, and I've committed worse hacks in my own code without thinking too hard.
|
|