How to use cmp() in Python 3?

How to use cmp() in Python 3?

As mentioned in the comments, cmp doesnt exist in Python 3. If you really want it, you could define it yourself:

def cmp(a, b):
    return (a > b) - (a < b) 

which is taken from the original Whats New In Python 3.0. Its pretty rare — though not unheard of — that its really needed, though, so you might want to think about whether its actually the best way to do whatever it is youre up to.

In Python 3.x you can import operator and use operator modules eq(), lt(), etc… instead of cmp()

How to use cmp() in Python 3?

When the sign is needed, probably safest alternative is using math.copysign:

import math
ang = -2
# alternative for cmp(ang, 0):
math.copysign(1, ang)

# Result: -1

In particular if ang is of np.float64 type because of depreciation of the – operator.
Example:

import numpy as np

def cmp_0(a, b):
    return (a > b) - (a < b)

ang = np.float64(-2)
cmp_0(ang, 0)

# Result:
# DeprecationWarning: numpy boolean subtract, the `-` operator, is deprecated, 
# use the bitwise_xor, the `^` operator, or the logical_xor function instead.

instead one could use:

def cmp_0(a, b):
    return bool(a > b) - bool(a < b)

ang = np.float64(-2)
cmp(ang, 0)
# Result: -1

Leave a Reply

Your email address will not be published. Required fields are marked *