[英]Test equality of two functions in python
I want to make two functions equal to each other, like this: 我想让两个函数彼此相等,如下所示:
def fn_maker(fn_signature):
def _fn():
pass
_fn.signature = fn_signature
return _fn
# test equality of two function instances based on the equality of their signature values
>>> fa = fn_maker(1)
>>> fb = fn_maker(1)
>>> fc = fn_maker(2)
>>> fa == fb # should be True, same signature values
True
>>> fa == fc # should be False, different signature values
False
How should I do it? 我该怎么办? I know I could probably override
eq
and ne
if fa, fb, fc are instances of some class. 我知道如果fa,fb,fc是某些类的实例,我可能会覆盖
eq
和ne
。 But here eq is not in dir(fa) and adding it the list doesnt work. 但这里的eq不在dir(fa)中并且添加它,列表不起作用。 I figured out some workaround like using a cache, eg,
我想出了一些像使用缓存的解决方法,例如,
def fn_maker(fn_signature):
if fn_signature in fn_maker.cache:
return fn_maker.cache[fn_signature]
def _fn():
pass
_fn.signature = fn_signature
fn_maker.cache[fn_signature] = _fn
return _fn
fn_maker.cache = {}
By this way there is a guarantee that there is only one function for the same signature value (kinda like a singleton). 通过这种方式可以保证只有一个函数用于相同的签名值(有点像单例)。 But I am really looking for some neater solutions.
但我真的在寻找一些更整洁的解决方案。
如果将函数转换为覆盖__call__()
以及比较运算符的某些类的实例,则可以非常轻松地实现所需的语义。
It is not possible to override the __eq__
implementation for functions (tested with Python 2.7) 无法覆盖
__eq__
实现(使用Python 2.7测试)
>>> def f():
... pass
...
>>> class A(object):
... pass
...
>>> a = A()
>>> a == f
False
>>> setattr(A, '__eq__', lambda x,y: True)
>>> a == f
True
>>> setattr(f.__class__, '__eq__', lambda x,y: True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'function'
I don't think it's possible. 我不认为这是可能的。
But overriding __call__
seems a nice solution to me. 但重写
__call__
似乎是一个很好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.