[Python-Dev] PEP 455: TransformDict
Steven D'Aprano
steve at pearwood.info
Tue Oct 8 05:13:30 CEST 2013
On Mon, Oct 07, 2013 at 06:17:09PM -0700, Mark Janssen wrote:
> Sorry I missed the original discussion, but isn't this a simple case
> of putting a decorator around the getitem method (to transform the
> input key) and a single line in the body of the setitem method, making
> this very easy adaptation of the existing dict class?
Not really. We can try what you suggest to implement a case insensitive
dict (decorator is not needed):
py> class CaseInsensitiveDict(dict):
... def __getitem__(self, key):
... key = key.casefold() # use .lower() before Python 3.3
... return super().__getitem__(key)
... def __setitem__(self, key, value):
... key = key.casefold()
... super().__setitem__(key, value)
...
py> d = CaseInsensitiveDict()
py> d['X'] = 42
py> d
{'x': 42}
Well, that's not exactly what I was hoping for... I was hoping that the
dict would preserve case, rather than just convert it. But that's only
the start of the problem:
py> d['X'] # this works
42
py> d.pop('X') # expecting 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'X'
So no, it isn't just a matter of a trivial wrapper around __getitem__,
__setitem__ and __delitem__.
Check the bug tracker for more detail:
http://bugs.python.org/issue18986
--
Steven
More information about the Python-Dev
mailing list