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
class Links(dict): | |
""" An extended dictionary class | |
that handles tuple keys nicely, | |
by ordering the tuple calls """ | |
def __init__(self,info=None,**kwargs): | |
super(Links,self).__init__() | |
if info: | |
if hasattr(info,'iteritems'): | |
for key,value in info.iteritems(): | |
self.__setitem__(key,value) | |
elif iterable(info): | |
for key,value in info: | |
self.__setitem__(key,value) | |
for key,value in kwargs.iteritems(): | |
self.__setitem__(key,value) | |
def order_first_tuple(func): | |
def orderedversion(self,first,*args,**kwargs): | |
assert hasattr(first,"__len__"), "Key must be iterable" | |
assert len(first)==2, "Key must be 2-tuple" | |
ordered_first = tuple(sorted(first)) | |
return func(self,ordered_first,*args,**kwargs) | |
return orderedversion | |
@order_first_tuple | |
def __setitem__(self,key,val): | |
return super(Links,self).__setitem__(key,val) | |
@order_first_tuple | |
def __getitem__(self,*args): | |
return super(Links,self).__getitem__(*args) | |
@order_first_tuple | |
def __delitem__(self,*args): | |
return super(Links,self).__delitem__(*args) | |
@order_first_tuple | |
def __contains__(self,*args): | |
return super(Links,self).__contains__(*args) |
Where I put that code on gist. To pull it off, you see that I subclass dict, and define a decorator that pulls out and sorts the first argument. After that it is just decorating the '__setitem__','__getitem__',and '__delitem__' methods. This lets us do nice things now:
>>> z = Links() >>> z[1,2] = 5 >>> z[4,3] = 10 >>> z {(1, 2): 5, (3, 4): 10} >>> z[2,1] 5 >>> z[1,2] 5 >>> z[2,1] = 11 >>> z {(1, 2): 11, (3, 4): 10} >>> del z[2,1] >>> (3,4) in z True >>> (4,3) in z True >>> z {(3, 4): 10} >>> z[5] = 1 Traceback (most recent call last): File "", line 1, in File "links.py", line 10, in orderedversion assert hasattr(first,"__len__"), "Key must be iterable" AssertionError: Key must be iterable >>> z[4,4,3] = 1 Traceback (most recent call last): File " ", line 1, in File "links.py", line 11, in orderedversion assert len(first)==2, "Key must be 2-tuple" AssertionError: Key must be 2-tuple >>> z {(3, 4): 10}
No comments:
Post a Comment