Skip to content
Open
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: 15 additions & 0 deletions Lib/ipaddress.py
Original file line number Diff line number Diff line change
Expand Up @@ -2002,6 +2002,21 @@ def __str__(self):
def __hash__(self):
return hash((self._ip, self._scope_id))

def __lt__(self, other):
if not isinstance(other, IPv6Address):
return NotImplemented
if self._ip != other._ip:
return self._ip < other._ip
self_scope = self._scope_id
other_scope = other._scope_id
if self_scope is None and other_scope is None:
return False
if other_scope is None:
return False
if self_scope is None:
return True
return self_scope < other_scope

def __eq__(self, other):
address_equal = super().__eq__(other)
if address_equal is NotImplemented:
Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_ipaddress.py
Original file line number Diff line number Diff line change
Expand Up @@ -986,6 +986,17 @@ def test_same_type_ordering(self):
self.assertFalse(lhs >= rhs)
self.assertFalse(rhs <= lhs)

def test_scoped_ipv6_ordering_same_ip(self):
# gh-151769: addresses with the same integer but different
# scope_id must be ordered; None < any string
unscoped = self.v6addr
scoped = ipaddress.IPv6Address(str(unscoped) + '%eth0')
self.assertNotEqual(unscoped, scoped)
self.assertLess(unscoped, scoped)
self.assertGreater(scoped, unscoped)
# sorted() must be deterministic
self.assertEqual(sorted([scoped, unscoped]), [unscoped, scoped])

def test_containment(self):
for obj in self.v4_addresses:
self.assertIn(obj, self.v4net)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix :class:`ipaddress.IPv6Address` ordering to account for ``scope_id``,
so addresses with the same IP but different scope IDs compare as ordered
and :func:`sorted` is deterministic.
Loading