Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm answering my own question, since I eventually decided that I really <em>do</em> want to subclass Dict, rather than creating a new mapping class, and UserDict still defers to the underlying Dict object in some cases, rather than using the provided <code>__setitem__</code>.</p> <p>After reading and re-reading the Python 2.6.4 source (mostly <code>Objects/dictobject.c</code>, but I grepped eveywhere else to see where the various methods are used,) my understanding is that the following code <em>is</em> sufficient to have my __setitem__ called every time that the object is changed, and to otherwise behave exactly as a Python Dict:</p> <p>Peter Hansen's suggestion got me to look more carefully at <code>dictobject.c</code>, and I realised that the update method in my original answer could be simplified a bit, since the built-in dictionary constructor simply calls the built-in update method anyway. So the second update in my answer has been added to the code below (by some helpful person ;-).</p> <pre><code>class MyUpdateDict(dict): def __init__(self, *args, **kwargs): self.update(*args, **kwargs) def __setitem__(self, key, value): # optional processing here super(MyUpdateDict, self).__setitem__(key, value) def update(self, *args, **kwargs): if args: if len(args) &gt; 1: raise TypeError("update expected at most 1 arguments, " "got %d" % len(args)) other = dict(args[0]) for key in other: self[key] = other[key] for key in kwargs: self[key] = kwargs[key] def setdefault(self, key, value=None): if key not in self: self[key] = value return self[key] </code></pre> <p>I've tested it with this code:</p> <pre><code>def test_updates(dictish): dictish['abc'] = 123 dictish.update({'def': 234}) dictish.update(red=1, blue=2) dictish.update([('orange', 3), ('green',4)]) dictish.update({'hello': 'kitty'}, black='white') dictish.update({'yellow': 5}, yellow=6) dictish.setdefault('brown',7) dictish.setdefault('pink') try: dictish.update({'gold': 8}, [('purple', 9)], silver=10) except TypeError: pass else: raise RunTimeException("Error did not occur as planned") python_dict = dict([('b',2),('c',3)],a=1) test_updates(python_dict) my_dict = MyUpdateDict([('b',2),('c',3)],a=1) test_updates(my_dict) </code></pre> <p>and it passes. All other implementations I've tried have failed at some point. I'll still accept any answers that show me that I've missed something, but otherwise, I'm ticking the checkmark beside this one in a couple of days, and calling it the right answer :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload