title: Lambda-function comparison in python
body: <p>In python you cannot directly compare functions created by lambda expressions:</p>
  
  <pre><code>&gt;&gt;&gt; (lambda x: x+2) == (lambda x: x+2)
  False
  </code></pre>
  
  <p>I made a routine to hash the disassembly.</p>
  
  <pre><code>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])
  </code></pre>
  
  <p>The usage is:</p>
  
  <pre><code>&gt;&gt;&gt;&gt; get_lambda_hash(lambda x: x+2) == get_lambda_hash(lambda x: x+1)
  False
  
  &gt;&gt;&gt;&gt; get_lambda_hash(lambda x: x+2) == get_lambda_hash(lambda x: x+2)
  True
  </code></pre>
  
  <p>Is there any more elegant solution for this problem?</p>