19 Feb
2006
19 Feb
'06
6:05 a.m.
Raymond Hettinger wrote: >>>Also, I think has_key/in should return True if there is a default. > * if __contains__ always returns True, then it is a useless feature (since > scripts containing a line such as "if k in dd" can always eliminate that line > without affecting the algorithm). If you mean "if __contains__ always returns True for a default dict, then it is a useless feature", I disagree. The code using "if k in dd" cannot be eliminated if you don't know that you have a default dict. > * if defaultdicts are supposed to be drop-in dict substitutes, then having > __contains__ always return True will violate basic dict invariants: > del d[some_key] > assert some_key not in d If you have a default value, you cannot ultimately del a key. This sequence is *not* a basic mapping invariant. If it was, then it would be also an invariant that, after del d[some_key], d[some_key] will raise a KeyError. This kind of invariant doesn't take into account that there might be a default value. Regards, Martin