Skip to content

Commit

Permalink
Make 'FormattableColumn' comparable
Browse files Browse the repository at this point in the history
Implement the '__lt__' magic method, thus providing the minimal set of
rich comparison methods necessary to support sorting. This will allows
users using these formatters for the more basic types (i.e. not dicts)
to sort their output using the standard '--sort-column' option.

Change-Id: I08e1f1bc75fa6452f19dfb9d221c1daec194d58d
Signed-off-by: Stephen Finucane <sfinucan@redhat.com>
  • Loading branch information
stephenfin committed Jan 29, 2021
1 parent 4f45f9a commit c1c9910
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions cliff/columns.py
Expand Up @@ -26,6 +26,11 @@ def __eq__(self, other):
self.__class__ == other.__class__ and self._value == other._value
)

def __lt__(self, other):
return (
self.__class__ == other.__class__ and self._value < other._value
)

@abc.abstractmethod
def human_readable(self):
"""Return a basic human readable version of the data."""
Expand Down
13 changes: 13 additions & 0 deletions cliff/tests/test_columns.py
Expand Up @@ -33,3 +33,16 @@ def test_faux_column_human(self):
u"I made this string myself: ['list', 'of', 'values']",
c.human_readable(),
)

def test_sorting(self):
cols = [
FauxColumn('foo'),
FauxColumn('bar'),
FauxColumn('baz'),
FauxColumn('foo'),
]
cols.sort()
self.assertEqual(
['bar', 'baz', 'foo', 'foo'],
[c.machine_readable() for c in cols],
)
@@ -0,0 +1,9 @@
---
features:
- |
Instances of ``cliff.columns.FormattableColumn`` are now comparable. This
allows implementations of ``FormattableColumn`` storing primitive data
types or containers with primitive data types to be sorted using the
``--sort-column`` option. Implementations of ``FormattableColumn`` that
store other types of data will still need to implement their own rich
comparison magic methods.

0 comments on commit c1c9910

Please sign in to comment.