Total Ordering in Python

Level 4236 keystrokes

This uses @total_ordering to generate all comparison methods from __eq__ and __lt__.

Python code

# Import the total_ordering class decorator
1from functools import total_ordering
2
# Fills in <=, > and >= from __eq__ and __lt__
3@total_ordering
4class Num:
# Store the number to compare
5 def __init__(self, val):
6 self.val = val
# == compares the stored values
7 def __eq__(self, other):
8 return self.val == other.val
# < is the only ordering method we write ourselves
9 def __lt__(self, other):
10 return self.val < other.val
11
# >= comes from total_ordering: not (3 < 2), so True
12print(Num(3) >= Num(2))

Output

True
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 14
  • (× 6
  • )× 6
  • .× 5
  • :× 4
  • =× 4
  • ,× 3
  • @× 1
  • <× 1
  • >× 1

More Python examples at level 4

← Python typing practice