Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added __lt__ function to Text class to enable sort functionality #3016

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion rich/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,20 @@ def __eq__(self, other: object) -> bool:
return NotImplemented
return self.plain == other.plain and self._spans == other._spans

def __lt__(self, other: object) -> bool:
if isinstance(other, str):
return self.plain < other
elif isinstance(other, Text):
return self.plain < other.plain
return NotImplemented

def __gt__(self, other: object) -> bool:
if isinstance(other, str):
return self.plain > other
elif isinstance(other, Text):
return self.plain > other.plain
return NotImplemented

def __contains__(self, other: object) -> bool:
if isinstance(other, str):
return other in self.plain
Expand Down Expand Up @@ -1088,7 +1102,6 @@ def divide(self, offsets: Iterable[int]) -> Lines:
_Span = Span

for span_start, span_end, style in self._spans:

lower_bound = 0
upper_bound = line_count
start_line_no = (lower_bound + upper_bound) // 2
Expand Down
20 changes: 20 additions & 0 deletions tests/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,3 +806,23 @@ def test_markup_property():
== "[bold]foo [italic]bar[/bold] baz[/italic]"
)
assert Text("[bold]foo").markup == "\\[bold]foo"


def test_lt():
text = Text("foobar")
assert not (text < "foo")
assert not (text < "foo ")
assert text < "foobar!"
assert Text("bar") < text
assert "foo" < text
assert not ("foobar" < text)


def test_gt():
text = Text("foobar")
assert text > "foo"
assert text > "foo "
assert not (text > "foobar!")
assert not (Text("bar") > text)
assert "foobar!" > text
assert not ("foobar" > text)