Last active
November 8, 2017 08:15
-
-
Save jn0/0aa002de1c719922eb81dd9e7e546019 to your computer and use it in GitHub Desktop.
Sometimes you want a better `dict` in Python...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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