[Python-ideas] Make dict customisation easier

Laurie Clark-Michalek lclarkmichalek at gmail.com
Sun Jun 17 00:28:50 CEST 2012


Hi,

A few weeks ago, a guy was on #python, looking to customise a dictionary to
be case insensitive (he was assuming string keys). His naive implementation
looked something like this:

    class CaseInsensitiveDict(dict):
        def __getitem__(self, key):
            return dict.__getitem__(self, key.lower())

        def __setitem__(self, key, item):
            dict.__setitem__(self, key.lower(), item)

However he was dismayed to find that this didn't work with other methods
that dict uses:

>>> d = CaseInsensitiveDict()
>>> d['a'] = 3
>>> d
{'a': 3}
>>> d['A']
3
>>> d.get('A', "No key found")
'No key found'

Eventually he was directed to dir(dict), and he seemed to accept that he
would have to wrap most of the methods of the dict builtin. This seemed
like the worse solution to me, and I couldn't see any real reason why
python couldn't either defer to user implemented __getitem__ and
__setitem__, or provide an alternative dict implementation that did allow
easy customisation.

I realise that python dicts are fairly high performance structures, and
that checking for a custom implementation might have an unacceptable impact
for a solution to what might be seen as a minor problem. Still, I think it
is worth the effort to clean up what seems to me to be a slight wart on a
very fundamental type in python.

Thanks,

Laurie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120616/e6b7eb8b/attachment.html>


More information about the Python-ideas mailing list