TypeError; Must use key word argument or key function in python 3.x
TypeError; Must use key word argument or key function in python 3.x
Looks like the problem is in this line.
self.__working_arr[num].sort( key = lambda a,b: cmp(a.weights, b.weights) )
The key
callable should take only one argument. Try:
self.__working_arr[num].sort(key = lambda a: a.weights)
The exact same error message appears if you try to pass the key parameter as a positional parameter.
Wrong:
sort(lst, myKeyFunction)
Correct:
sort(lst, key=myKeyFunction)
Python 3.6.6
TypeError; Must use key word argument or key function in python 3.x
Following on from the answer by @Kevin – and more specifically the comment/question by @featuresky:
Using functools.cmp_to_key and reimplementing cmp (as noted in the porting guide) I have a hacky workaround for a scenario where 2 elements can be compared via lambda form. To use the OP as an example; instead of:
self.__working_arr[num].sort( key = lambda a,b: cmp(a.weights, b.weights) )
You can use this:
from functools import cmp_to_key
[...]
def cmp(x, y): return (x > y) - (x < y)
self.__working_arr[num].sort(key=cmp_to_key(lambda a,b: cmp(a.weights, b.weights)))
Admittedly, Im somewhat new to python myself and dont really have a good handle on python2. Im sure the code could be rewritten in a much better/cleaner way and Id certainly love to hear a proper way to do this.
OTOH in my case this was a handy hack for a old python2 script (updated to python3) that I dont have time/energy to properly understand and rewrite right now.
Beyond the fact that it works, I would certainly not recommend wide usage of this hack! But I figured that it was worth sharing.