Dictionary Enhancement? (Take 2)

Rich Harkins rich at worldsinfinite.com
Thu Oct 31 16:08:00 CET 2002


On Thu, 2002-10-31 at 09:12, Rich Harkins wrote:
> I was wondering if anyone else had been wanting to enhance Python
> dictionaries such that instead of raising KeyError in the case of
errors
> that another method on the dictionary object, say __makeitem__ would
be
> called to try to auto-generate an appropriate value.  That
__makeitem__
> method would then either raise KeyError itself or return the value to
> insert into the dictionary and return through __getitem__.
> 
> I scanned the PEP's but didn't see anything similar.
> 
> Rich
> 

Since I'm already getting replies about setdefault() I'd better post
some Python code describing what I'm talking about:

class SuperDict(dict):
    """
    A dictionary that calls a member method __makeitem__ when
    a KeyError would normally be generated by __getitem__.  This
    allows for auto-generation of dictionary entities.
    """

    def __getitem__(self,name):
        try:
            return dict.__getitem__(self,name)
        except KeyError:
            obj=self.__makeitem__(self,name)
            self[name]=obj
            return obj

    def get(self,name,default):
        try:
            return self[name]
        except KeyError:
            return default

    def __makeitem__(self,name):
        # Create an object automatically from name or raise KeyError
        # Default is to raise KeyError
        raise KeyError,name

There are two advantages to this over setdefault():

1) The subclass knows what to create as child keys (useful for directory
listing dictionaries where the values sometimes shouldn't exist until
they're demanded).  In cases where this is useful the logic for the
created child values is only known to the subclass and should *not* be
replicated throughout the "client" code.

2) Calling setdefault() *creates* the to-be-assigned value regardless of
whether the value is put in the dictionary or not.  I only want to
create the subvalue if and only if the key doesn't exist.

I probably should have posted that the first time, sorry about the
confusion.

Rich





More information about the Python-list mailing list