How to compare wrapped functions with functools.partial?

If I define my function as follows:

def myfunc(arg1, arg2): pass 

then myfunc == myfunc will return True

But functools.partial(myfunc, arg2=1) == functools.partial(myfunc, arg2=1) will return False .

For unittest purpose, is there an easy way to check if a partial function is expected?

+5
source share
1 answer

Check if the func , args and keywords attributes match:

 p1.func == p2.func and p1.args == p2.args and p1.keywords == p2.keywords 

where p1 and p2 are partial() objects:

 >>> from functools import partial >>> def myfunc(arg1, arg2): ... pass ... >>> partial(myfunc, arg2=1).func == partial(myfunc, arg2=1).func True >>> partial(myfunc, arg2=1).args == partial(myfunc, arg2=1).args True >>> partial(myfunc, arg2=1).keywords == partial(myfunc, arg2=1).keywords True 

An error was discovered in Python trackers to add equality testing to partial objects, which is essentially the case, but the reason was rejected that the lack of the __eq__ method obscures the behavior of functions that are also equal only if their id() matches.

+8
source

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


All Articles