[Python-Dev] dict.supplement() (was Re: list.shift())
Peter Funk
pf@artcom-gmbh.de
Mon, 20 Mar 2000 19:28:17 +0100 (MET)
I wrote:
> > Note the similarities to {}.update(dict), but update replaces existing
> > entries in self, which is sometimes not desired. I know, that supplement
> > can also simulated with:
>
Fred L. Drake, Jr.:
> Peter,
> I like this!
>
> > tmp = dict.copy()
> > tmp.update(self)
> > self.data = d
>
> I presume you mean "self.data = tmp"; "self.data.update(tmp)" would
> be just a little more robust, at the cost of an additional update.
Ouppss... I should have tested this before posting. But currently I use
the more explicit (and probably slower version) in my code:
class ConfigDict(UserDict.UserDict):
def supplement(self, defaults):
for k, v in defaults.items():
if not self.data.has_key(k):
self.data[k] = v
Works fine so far, although it requires usually an additional copy operation.
Consider another example, where arbitrary instance attributes should be
specified as keyword arguments to the constructor:
>>> class Example:
... _defaults = {'a': 1, 'b': 2}
... _config = _defaults
... def __init__(self, **kw):
... if kw:
... self._config = self._defaults.copy()
... self._config.update(kw)
...
>>> A = Example(a=12345)
>>> A._config
{'b': 2, 'a': 12345}
>>> B = Example(c=3)
>>> B._config
{'b': 2, 'c': 3, 'a': 1}
If 'supplement' were a dictionary builtin method, this would become simply:
kw.supplement(self._defaults)
self._config = kw
Unfortunately this can't be achieved using a wrapper class like UserDict,
since the **kw argument is always a builtin dictionary object.
Regards, Peter
--
Peter Funk, Oldenburger Str.86, 27777 Ganderkesee, Tel: 04222 9502 70, Fax: -60