Search code examples
pythonc#comparecompareto

How can I compare integers in python the same way CompareTo() in C# does?


As far as I know, in .NET Framework there is a method Int32.CompareTo(), which returns 0 if the numbers are equal, -1 if the number in the parenthesis is higher, otherwise 1. Is there an existing method for this, in python with the same return values, or do I have to write one myself?


Solution

  • Maybe in some third-party library, but no, in "vanilla" Python 3.x there is no method to do that, though code to achieve something similar should be as simple as this:

    def compare_to(val1: int, val2: int) -> int:
        if val1 > val2:
            return 1
        elif val1 < val2:
            return -1
        elif val1 == val2:
            return 0
    

    Or, for something closer to what you described using a custom subclass of int:

    class Int32(int):
        def compare_to(self, value: int):
            if self > value:
                return 1
            elif self < value:
                return -1
            elif self == value:
                return 0