Unapiedra
Unapiedra

Reputation: 16217

Hashing a Python function

def funcA(x):
    return x

Is funcA.__code__.__hash__() a suitable way to check whether funcA has changed?

I know that funcA.__hash__() won't work as it the same as id(funcA) / 16. I checked and this isn't true for __code__.__hash__(). I also tested the behaviour in a ipython terminal and it seemed to hold. But is this guaranteed to work?

Why

I would like to have a way of comparing an old version of function to a new version of the same function.

I'm trying to create a decorator for disk-based/long-term caching. Thus I need a way to identify if a function has changed. I also need to look at the call graph to check that none of the called functions have changed but that is not part of this question.

Requirements:

One alternative would be to hash the text inside the file that contains the given function.

Upvotes: 2

Views: 276

Answers (1)

Unapiedra
Unapiedra

Reputation: 16217

  1. Yes, it seems that func_a.__code__.__hash__() is unique to the specific functionality of the code. I could not find where this is implemented, or where it is __code__.__hash__() defined.

  2. The perfect way would be to use func_a.__code__.co_code.__hash__() because co_code has the byte code as a string. Note that in this case, the function name is not part of the hash and two functions with the same code but names func_a and func_b will have the same hash.

    hash(func_a.__code__.co_code)
    

Source.

Upvotes: 1

Related Questions