Dictionary Enhancement?
Rich Harkins
rharkins at thinkronize.com
Thu Oct 31 10:32:20 EST 2002
On Thu, 2002-10-31 at 10:06, John Hunter wrote:
> >>>>> "Rich" == Rich Harkins <rich at worldsinfinite.com> writes:
>
> Rich> I was wondering if anyone else had been wanting to enhance
> Rich> Python dictionaries such that instead of raising KeyError in
> Rich> the case of errors that another method on the dictionary
> Rich> object, say __makeitem__ would be called to try to
> Rich> auto-generate an appropriate value. That __makeitem__
> Rich> method would then either raise KeyError itself or return the
> Rich> value to insert into the dictionary and return through
> Rich> __getitem__.
>
> As of python 2.2, you can subclass built in types, so you are free to
> enhance dict anyway you like.
>
> Here is an example that uses makeitem to cube the argument, and raises
> a KeyError if it can't
>
> # requires python2.2
> class mydict(dict):
>
> def __makeitem__(self, key):
> try: val = key**3
> except: raise KeyError
> else: return self.setdefault(key, val)
>
> def __getitem__(self, key):
> return self.get(key, self.__makeitem__(key))
>
> m = mydict()
>
> print m[2] # this is ok
> m[3] = 10 # so is this
>
> m['John'] = 33
> #print m['Bill'] this raises a key error
>
>
> print m
>
> Is this what you are looking for?
>
Not quite - __makeitem__ will be called (and its value generated)
whether it needs to be or not - this is my basic objection to
setdefault() as an approach. I did reply to myself with an example
Python class but I guess I would really like to see this become either a
default built-in behavior or a separate, but built-in, C type to manage
this sort of thing. The pure Python version will have poor performance
characteristics if __getitem__ is called frequently.
Rich
More information about the Python-list
mailing list