For 1.6 make UserDict use __setitem__ and __getitem__ in other methods?

Hamish Lawson hamish_lawson at yahoo.co.uk
Mon Apr 3 18:29:23 EDT 2000


Consider the code below which defines a dictionary class whose
keys are case-insensitive.


    import UserDict, string

    class CaselessDict(UserDict):

        def __setitem__(self, key, value):
            self.data[string.lower(key)] = value

        def __getitem__(self, key):
            return self.data[string.lower(key)]

    d = CaselessDict()
    d['Joe'] = "Rhubarb"
    print d['JOE']                  # prints "Rhubarb"
    print d.has_key('JOE')          # prints 0 i.e.
    print d.get('JOE', None)        # prints None


An element set as 'Joe' can be fetched as 'JOE'. However as it
stands the semantics of has_key('JOE') and get('JOE') are
broken, since those methods don't think that a 'JOE' element
exists. This arises because in the parent UserDict class, these
methods access the self.data attribute.

Of course the author of CaselessDict could provide definitions
for has_key() and get(), but somehow this seems a bit inelegant
to me; I feel that the behaviour of has_key() and get() (and
maybe other methods) should follow on from whatever behaviour
has been defined for __getitem__ in the derived class. I propose
that for Python 1.6, UserDict's methods are rewritten to do
this. Is there any reason why this would be a bad idea? Below
I've provided rewritten versions of has_key() and get() to get
started.

    def has_key(self, key):
        try:
            self[key]
            return 1
        except KeyError:
            return 0

    def get(self, key, failobj=None):
        try:
            return self[key]
        except KeyError:
            return failobj


Hamish Lawson


* Sent from RemarQ http://www.remarq.com The Internet's Discussion Network *
The fastest and easiest way to search and participate in Usenet - Free!




More information about the Python-list mailing list