Skip to content

Instantly share code, notes, and snippets.

@jn0
Last active November 8, 2017 08:15
Show Gist options
  • Save jn0/0aa002de1c719922eb81dd9e7e546019 to your computer and use it in GitHub Desktop.
Save jn0/0aa002de1c719922eb81dd9e7e546019 to your computer and use it in GitHub Desktop.
Sometimes you want a better `dict` in Python...
import __builtin__
class HashableDict(__builtin__.dict):
'''and with .attr capability'''
def __init__(self, *av, **kw):
return __builtin__.dict.__init__(self, *av, **kw)
@staticmethod
def dict__hash(d):
return hash(tuple(sorted([
(HashableDict.dict__hash(k) if type(k) is dict else k,
HashableDict.dict__hash(v) if type(v) is dict else v)
for k, v in d.items()])))
def __hash__(self):
return self.dict__hash(self)
def __eq__(self, other):
return self.__hash__() == self.dict__hash(other)
def __getattr__(self, attr):
if attr in self:
return self.get(attr)
raise KeyError, attr
#end class HashableDict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment