[Tutor] Problems with deleting dictionary keys.

dman dsh8290@rit.edu
Mon, 13 Aug 2001 22:45:19 -0400


On Tue, Aug 14, 2001 at 02:07:30AM +0100, Allan Crooks wrote:
| On 13 Aug 2001, at 14:51, dman wrote:
| 
| <snip>
| 
| > The problem is probably that you are destroying the key while at the
| > same time "creating" it.
| 
| OK, let me rewrite a different version of the code (and some 
| different test output):

Ok.

[...]
 
| I have the slightly unpleasant feeling that using deletion in the 
| setitem method isn't a good idea, but I can't think how else to get 
| around it.

Exactly!

| >  Notice also that in your __setitem__ method
| > you never actually set any items.
| 
| I was just using that for demonstration purposes more than 
| anything. :)

Ok.

| > I think you want something similar to UserDict :
| 
| <snip>
| 
| Is there really any need to? Since we've got the base 'dictionary' 
| type, I thought it made UserDict redundant.

The difference is that dicts are a 'type' and UserDict is a 'class'.
This means that you can inherit from UserDict in your class, but you
can't inherit from a dict.  The last I heard Guido was really working
on some stuff to make types and classes the same and allow inheriting
from a type.

| But having said that, using UserDict instead of dictionary does 
| work.... :)

Are you using aggregation or inheritance?  I think, given the snippet
you showed, that you want to create your own kind of dictionary which
would be easiest with inheritance so you would only need to implement
your special behavior and not the entire functionality of a
dictionary.

| > The proper way to delete a dictionary key is with the 'del' keyword :
| 
| Which is what the:
| 
| del self[key]
| 
| line is there for. 

I am not sure, but I am wondering if you aren't getting yourself into
some sort of nasty recursion or piece of python internal sanity
checking or something when you try and delete a key inside of
__setitem__.  The (python) source will tell for sure, though, ;-).

| But does this mean a dictionary (or rather a subclass of dictionary)
| cannot handle deleting items from itself?

No.  The code snippet from UserDict shows how to do it.  __setitem__
should *set* items, not destroy them.  __delitem__ can (should)
destroy the items you no longer want.

See http://www.python.org/doc/current/ref/sequence-types.html#l2h-134
more more (though terse) information regarding the __setitem__,
__delitem__ and __getitem__ methods.

HTH,
-D