sublcassing dict without losing functionality

Peter Otten __peter__ at web.de
Tue Nov 2 00:56:43 CET 2004


Steven Bethard wrote:

> simple.  Modifying and using UserDict would give me some 60+ lines of code

Not tested beyond what you see:

>>> import UserDict as userdict
>>> class Dict(userdict.DictMixin, dict):
...     def __setitem__(self, key, value):
...             if key in self: raise ValueError("key already exists")
...             super(Dict, self).__setitem__(key, value)
...     def __init__(self, other=None, **kw):
...             super(Dict, self).__init__()
...             self.update(other, **kw)
...
>>> d = Dict({"one": 1}, one=2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 7, in __init__
  File "UserDict.py", line 155, in update
    self.update(kwargs)
  File "UserDict.py", line 147, in update
    self[k] = v
  File "<stdin>", line 3, in __setitem__
ValueError: key already exists
>>> d["one"] = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in __setitem__
ValueError: key already exists
>>>

Peter




More information about the Python-list mailing list