Friday, 15 May 2015

hash - Hashing python functions across different sessions -



hash - Hashing python functions across different sessions -

i want generate hash based on parameters of function (for quick automated caching). hash should consistent between different sessions.

let's assume have next functions:

def generate_hash(dictionary): homecoming hashlib.sha224(str(dictionary.items())).hexdigest() def foo(a,b,c): homecoming generate_hash(locals())

which fine long arguments str representation consistent across sessions. problem pass function arguments , looks not.

for example, next phone call homecoming different result across sessions.

foo(1,2,np.sum)

any workaround?

seems figured out myself:

16 def generate_hash(dictionary): 17 args = [] 18 key,item in dictionary.iteritems(): 19 if isinstance(item,functools.partial): 20 args.append((key,item.func.__module__,item.func.__name__, 21 generate_hash(item.keywords))) 22 elif inspect.isfunction(item): 23 args.append((key,item.__module__,item.__name__)) 24 else: 25 args.append((key,item)) 26 homecoming hashlib.sha224(str(args)).hexdigest()

which works consistenly partial functions:

foo('a','1',np.average) -> 1631c5fd0050fd01cb7a7ee9666d366b35c1415cb4181c7220ead043 foo('a',1,functools.partial(np.average,axis=0)) -> 692227d3b52b0cdcd4ed2204650cb207c1ab6f274a09977c711d35d5 foo('a',1,functools.partial(np.average,axis=1)) -> ba1e0b01f2e12ef1c9ca2e3bf5235aaadcbe4ab29d9c977e1ee6e799

python hash

No comments:

Post a Comment