Reputation: 122
With Crystal, I can compare two numbers using the <==>
operator. Example:
p! 1 <=> 1
Running this prints:
1 <=> 1 # => 0
The zero signifies that both numbers are equal. If the value is higher, it would return a positive number. If the value is lower, it returns a negative number. I'd like to know if such an operator exists with Python. Trying to use the <==>
operator gives a syntax error:
>>> 1 <==> 1
File "<stdin>", line 1
1 <==> 1
^
SyntaxError: invalid syntax
I can obviously use something like this:
if 1 == 1:
#equal
elif 1 < 1:
#less than
else:
#greater than
But I think it would be simpler to use a universal operator for comparing.
Upvotes: 0
Views: 1184
Reputation: 18792
To compare numbers and find out if they're greater or smaller in one go, you may be able to just use subtraction!
>>> 1-1
0
>>> 1-5
-4
However, if you wanted rich comparison, define __lt__
on a custom object
class Foo():
def __init__(self, name, primary, secondary):
self.name = name
self.primary = primary
self.secondary = secondary
def __str__(self):
return self.name
def __repr__(self):
return f"Foo({self})"
def __lt__(self, other):
base = self.primary * 100 + self.secondary
comparison = other.primary * 100 + other.secondary
return base < comparison
>>> a = Foo("some A", 3,4)
>>> b = Foo("some other B", 2, 99)
>>> test = (a,b)
>>> test
(Foo(some A), Foo(some other B))
>>> sorted(test)
[Foo(some other B), Foo(some A)]
Upvotes: 0
Reputation: 780673
Even if you had such an operator, you still end up with the 3-way if
:
if a <=> b == 0:
# equal
elif a <=> b < 0:
# less than
else:
# greater than
so it doesn't really buy you much. It does mean you can avoid writing the comparison expression if it's complex:
compare = a <=> b
if compare == 0:
...
But that was apparently not useful enough for the Python designers to keep the built-in cmp()
function that was in Python 2.x.
If you really want it, there are a number of implementations in How to use cmp() in Python 3?
Upvotes: 2