In python you cannot directly compare functions created by lambda expressions:
>>> (lambda x: x+2) == (lambda x: x+2)
False
I made a routine to hash the disassembly.
import sys
import dis
import hashlib
import contextlib
def get_lambda_hash(l, hasher=lambda x: hashlib.sha256(x).hexdigest()):
@contextlib.contextmanager
def capture():
from cStringIO import StringIO
oldout, olderr = sys.stdout, sys.stderr
try:
out=[StringIO(), StringIO()]
sys.stdout, sys.stderr = out
yield out
finally:
sys.stdout, sys.stderr = oldout, olderr
out[0] = out[0].getvalue()
out[1] = out[1].getvalue()
with capture() as out:
dis.dis(l)
return hasher(out[0])
The usage is:
>>>> get_lambda_hash(lambda x: x+2) == get_lambda_hash(lambda x: x+1)
False
>>>> get_lambda_hash(lambda x: x+2) == get_lambda_hash(lambda x: x+2)
True
Is there any more elegant solution for this problem?