How can I make as "perfect" a subclass of dict
as possible? The end goal is to have a simple dict in which the keys are lowercase.
It would seem that should be some tiny set of primitives I can override to make this work, but all my research and attempts have made it seem like this isn't the case:
- If I override
__getitem__
/__setitem__
, thenget
/set
don't work.- http://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict-and-override-get-set/2390889#2390889
- how do I make them work? Surely I don't need to implement them individually?
- Am I preventing pickling from working, and do I need to implement
__setstate__
etc? - Do I need
repr
,update
and__init__
? - Should I just use mutablemapping (it seems one shouldn't use
UserDict
orDictMixin
):- http://stackoverflow.com/questions/1622722/overriding-set-methods-in-python/1622872#1622872
- if so, how? The docs aren't exactly enlightening.
Here is my first go at it, get()
doesn't work at least, and no doubt there are many minor subtle problems. Damn you Python, you're supposed to make stuff easy.
class arbitrary_dict(dict):
"""A dictionary which applies an arbitrary key-altering function before accessing the keys"""
def __keytransform__(self, key):
return key
# Overrided methods. List from a http://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
# Use dict directly, since super(dict, self) doesn't work. Not sure why, perhaps dict is not a new-style class.
def __getitem__(self, key):
return dict.__getitem__(self, self.__keytransform__(key))
def __setitem__(self, key, value):
return dict.__setitem__(self, self.__keytransform__(key), value)
def __delitem__(self, key):
return dict.__delitem__(self, self.__keytransform__(key))
def __contains__(self, key):
return dict.__contains__(self, self.__keytransform__(key))
class lcdict(arbitrary_dict):
def __keytransform__(self, key):
return str(key).lower()