[Python-Dev] Proposal: defaultdict

Raymond Hettinger raymond.hettinger at verizon.net
Sun Feb 19 07:33:42 CET 2006


[Martin v. Löwis]
> If you have a default value, you cannot ultimately del a key. This
> sequence is *not* a basic mapping invariant.

You believe that key deletion is not basic to mappings?


> This kind of invariant doesn't take into account
> that there might be a default value.

Precisely.  Therefore, a defaultdict subclass violates the Liskov Substitution 
Principle.

Of course, the __del__ followed __contains__ sequence is not the only invariant 
that is thrown-off.  There are plenty of examples.  Here's one that is 
absolutely basic to the method's contract:

    k, v = dd.popitem()
    assert k not in dd

Any code that was expecting a dictionary and uses popitem() as a means of 
looping over and consuming entries will fail.

No one should kid themselves that a default dictionary is a drop-in substitute. 
Much of the dict's API has an ambiguous meaning when applied to defaultdicts.

If all keys are in-theory predefined, what is the meaning of len(dd)?

Should dd.items() include any entries where the value is equal to the default or 
should the collection never store those?  If the former, then how do you access 
the entries without looping over the whole contents?  If the latter, then do you 
worry that "dd[v]=k" does not imply "(k,v) in dd.items()"?


Raymond 



More information about the Python-Dev mailing list