Skip to content

Commit 56b29ba

Browse files
committed
Fix sorted() to use __lt__ instead of __gt__
CPython's sort uses __lt__ for comparisons, but RustPython was using __gt__. This caused issues when only __lt__ was overridden on a subclass (e.g., NamedTuple with custom __lt__), as it would fall back to the parent class's comparison instead of using the overridden method.
1 parent aa99c05 commit 56b29ba

1 file changed

Lines changed: 10 additions & 5 deletions

File tree

crates/vm/src/builtins/list.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -522,12 +522,17 @@ fn do_sort(
522522
key_func: Option<PyObjectRef>,
523523
reverse: bool,
524524
) -> PyResult<()> {
525-
let op = if reverse {
526-
PyComparisonOp::Lt
527-
} else {
528-
PyComparisonOp::Gt
525+
// CPython uses __lt__ for all comparisons in sort.
526+
// try_sort_by_gt expects is_gt(a, b) = true when a should come AFTER b.
527+
let cmp = |a: &PyObjectRef, b: &PyObjectRef| {
528+
if reverse {
529+
// Descending: a comes after b when a < b
530+
a.rich_compare_bool(b, PyComparisonOp::Lt, vm)
531+
} else {
532+
// Ascending: a comes after b when b < a
533+
b.rich_compare_bool(a, PyComparisonOp::Lt, vm)
534+
}
529535
};
530-
let cmp = |a: &PyObjectRef, b: &PyObjectRef| a.rich_compare_bool(b, op, vm);
531536

532537
if let Some(ref key_func) = key_func {
533538
let mut items = values

0 commit comments

Comments
 (0)