Skip to content

Commit

Permalink
Make keyword objects comparable
Browse files Browse the repository at this point in the history
  • Loading branch information
Kodiologist committed Aug 15, 2024
1 parent 4c8aeaa commit ce2a569
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
7 changes: 7 additions & 0 deletions NEWS.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
.. default-role:: code

Unreleased
=============================

Bug Fixes
------------------------------
* Keyword objects can now be compared to each other with `<` etc.

0.29.0 (released 2024-05-20)
=============================

Expand Down
2 changes: 1 addition & 1 deletion docs/syntax.rst
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ Thus ``(foo : 3)`` must be rewritten to use runtime unpacking, as in ``(foo #**
{"" 3})``.

.. autoclass:: hy.models.Keyword
:members: __bool__, __call__
:members: __bool__, __lt__, __call__

.. _dotted-identifiers:

Expand Down
10 changes: 9 additions & 1 deletion hy/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import operator
from contextlib import contextmanager
from functools import reduce
from functools import reduce, total_ordering
from itertools import groupby
from math import isinf, isnan

Expand Down Expand Up @@ -206,6 +206,7 @@ def __new__(cls, s, from_parser=False):
_wrappers[type(None)] = lambda _: Symbol("None")


@total_ordering
class Keyword(Object):
"""
Represents a keyword, such as ``:foo``.
Expand Down Expand Up @@ -251,6 +252,13 @@ def __ne__(self, other):
return NotImplemented
return self.name != other.name

def __lt__(self, other):
"""Keywords behave like strings under comparison operators, but are incomparable
to actual ``str`` objects."""
if not isinstance(other, Keyword):
return NotImplemented
return self.name < other.name

def __bool__(self):
"""The empty keyword ``:`` is false. All others are true."""
return bool(self.name)
Expand Down
10 changes: 10 additions & 0 deletions tests/native_tests/keywords.hy
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@
(assert (= (. ': name) "")))


(defn test-order []
; https://github.com/hylang/hy/issues/2594
(assert (< :a :b))
(assert (<= :a :b))
(assert (> :b :a))
(assert (= (sorted [:b :a :c]) [:a :b :c]))
(with [(pytest.raises TypeError)]
(< :a "b")))


(defn test-pickling-keyword []
; https://github.com/hylang/hy/issues/1754
(setv x :test-keyword)
Expand Down

0 comments on commit ce2a569

Please sign in to comment.