python 中的 Lambda 函数比较

Lambda-function comparison in python

在 python 中,您不能直接比较由 lambda 表达式创建的函数:

>>> (lambda x: x+2) == (lambda x: x+2)
False

我做了一个散列反汇编的例程。

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])

用法是:

>>>> 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

这个问题有没有更优雅的解决方案?

如果您坚持执行这种疯狂的行为,请比较每个字节码和常量。

>>> import operator
>>> coco = operator.attrgetter('co_code', 'co_consts')
>>> coco((lambda x: x+2).__code__) == coco((lambda x: x+2).__code__)
True
>>> coco((lambda x: x+2).__code__) == coco((lambda x: x+1).__code__)
False
>>> def foo(y):
...   return y + 2
... 
>>> coco((lambda x: x+2).__code__) == coco(foo.__code__)
True