Reputation: 16217
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?
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:
hash()
is randomized on each start of a new instance. Although it also says that "HASH RANDOMIZATION IS DISABLED BY DEFAULT". Ideally, I'd like a function that does is stable even with randomization enabled.def funcA: pass
and def funcB: pass
, i.e. when only the name of the function changes. Probably not necessary.One alternative would be to hash the text inside the file that contains the given function.
Upvotes: 2
Views: 276
Reputation: 16217
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.
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)
Upvotes: 1