Created
September 20, 2012 05:05
-
-
Save tobyodavies/3754066 to your computer and use it in GitHub Desktop.
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 HashableFunc(object): | |
""" | |
This class acts as a decorator to make a function persistently hashable | |
""" | |
relevant_attr_names = ['co_argcount', 'co_cellvars', 'co_code', 'co_consts', | |
'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', | |
'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', | |
'co_varnames'] | |
def relevent_attrs(self): | |
return tuple(getattr(func.__code__,s) for s in relevant_attr_names) | |
def __init__(self, func): | |
self.func = func | |
def __hash__(self): | |
return hash(self.relevant_attrs()) | |
def __call__(self, *args, **kwargs): | |
return self.func(*args, **kwargs) | |
def __eq__(self, other): | |
return self.relevant_attrs() == other.relevant_attrs | |
@HashableFunc | |
def fib(a): | |
if a <= 1: | |
return 1 | |
return fib(a-1) + fib(a-2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment