-3

I'm not a python programmer so hence coming here..

I'm aware cmp has been depreciated in python3, I'm trying to migrate this python 2 code to python3, I would appreciate some help.

def get_datalink_points( drivers ):
points = []
for driver in drivers:
    points += driver.points

def compare_datalink_target( a, b ):
    target_a = target_b = ''
    if a.datalink is not None:
        target_a = a.datalink.target
    if b.datalink is not None:
        target_b = b.datalink.target
    return cmp( target_a, target_b )

return sorted( points, cmp = compare_datalink_target )

This code currently generates the following Error:

Exception Type:     TypeError
Exception Value:    'cmp' is an invalid keyword argument for sort()

Thanks for any help.

1 Answers1

3

The equivalent sorted() call that works in Python 3 is:

return sorted( points, key=lambda x: x.datalink.target if x.datalink is not None else '' )
CryptoFool
  • 21,719
  • 5
  • 26
  • 44
  • That's not equivalent without the `is not None` part if `datalink` can take falsy values that aren't `None`. Granted, an unlikely scenario, but worth noting. – ShadowRanger Sep 20 '20 at 16:10
  • I thought of that, but if such a falsy value were to come along, then the original code is going to throw an exception as that value won't be something with a `target` attribute. I assume that the OPs code isn't crashing as currently written, so the simpler check should be adequate. Since I did say "equivalent", I guess I shouldn't have taken that liberty, so I changed the answer per your suggestion. Thanks. – CryptoFool Sep 20 '20 at 16:16