public
Last active

  • Download Gist
HashableFunc.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.