TypeError: 'cmp' is an invalid keyword argument for this function

ewilulu picture ewilulu · Feb 13, 2015 · Viewed 10.3k times · Source

I'm using Python3, but the script is not compatible with this version and I hit some errors. Now I have problem with cmp parameter. Here is the code

def my_cmp(x,y):
    counter = lambda x, items: reduce(lambda a,b:a+b, [list(x).count(xx) for xx in items])
    tmp =  cmp(counter(x, [2,3,4,5]), counter(y, [2,3,4,5]))
    return tmp if tmp!=0 else cmp(len(x),len(y)) 

for i, t in enumerate([tmp[0] for tmp in sorted(zip(tracks, self.mapping[idx][track_selection[-1]].iloc[0]), cmp=my_cmp, key=lambda x:x[1])]):
    img[i,:len(t)] = t

I would really appreciate any help how to deal with this error in Python3.

Answer

user3506100 picture user3506100 · Oct 10, 2019

from python documentation

In Python 2.7, the functools.cmp_to_key() function was added to the functools module.

The function available in python 3 too.

Just wrap your cmp function with cmp_to_key

from functools import cmp_to_key

...

...key=cmp_to_key(my_cmp)...