Check equality of two functions in python

I want to make two functions equal to each other, for example:

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 can I do it? I know that I could override eq and ne if fa, fb, fc are instances of some class. But here eq is not in the dir (fa) directory and adds that the list is not working. I figured out a workaround, like using a cache, for example,

 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 = {} 

Thus, there is a guarantee that there is only one function for the same signature value (sort of like singleton). But I'm really looking for some simpler solutions.

+4
source share
3 answers

Cannot override __eq__ implementation for functions (tested using 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' 
+2
source

If you turned your functions into instances of some class that overrides __call__() , as well as comparison operators, it will be very easy for you to achieve the semantics you want.

+6
source

I do not think that's possible.

But overriding __call__ seems like a good solution to me.

0
source

Source: https://habr.com/ru/post/1414835/


All Articles