diff --git a/crates/vm/src/builtins/list.rs b/crates/vm/src/builtins/list.rs index 137c9e8d956..f85efe972c7 100644 --- a/crates/vm/src/builtins/list.rs +++ b/crates/vm/src/builtins/list.rs @@ -184,9 +184,8 @@ impl PyList { pub(crate) struct SortOptions { #[pyarg(named, optional)] key: Option, - #[pytraverse(skip)] - #[pyarg(named, default)] - reverse: bool, + #[pyarg(named, default, py_default = "False")] + reverse: Option, } pub type PyListRef = PyRef; @@ -203,6 +202,10 @@ impl PyList { } pub(crate) fn sort(&self, options: SortOptions, vm: &VirtualMachine) -> PyResult<()> { + let reverse = match &options.reverse { + Some(reverse) => reverse.try_to_bool(vm)?, + None => false, + }; // replace list contents with [] for duration of sort. // this prevents keyfunc from messing with the list and makes it easy to // check if it tries to append elements to it. @@ -211,7 +214,7 @@ impl PyList { let version_before = self.mutation_counter.load(Ordering::Relaxed); (core::mem::take(&mut *guard), version_before) }; - let res = do_sort(vm, &mut elements, options.key.as_deref(), options.reverse); + let res = do_sort(vm, &mut elements, options.key.as_deref(), reverse); let mutated = { let mut guard = self.elements.write(); let mutated = self.mutation_counter.load(Ordering::Relaxed) != version_before; diff --git a/extra_tests/snippets/builtin_list.py b/extra_tests/snippets/builtin_list.py index 3e8e3c76681..9ac48448131 100644 --- a/extra_tests/snippets/builtin_list.py +++ b/extra_tests/snippets/builtin_list.py @@ -271,6 +271,27 @@ def __eq__(self, x): assert sorted(lst, key=lambda x: -x) == lst assert sorted(lst, key=lambda x: -x, reverse=True) == orig + +class Truthy: + def __bool__(self): + return True + + +assert sorted([1, 2, 3], reverse=Truthy()) == [3, 2, 1] +assert sorted([1, 2, 3], reverse=[]) == [1, 2, 3] +lst = [1, 2, 3] +lst.sort(reverse=Truthy()) +assert lst == [3, 2, 1] + + +class RaisingBool: + def __bool__(self): + raise ZeroDivisionError + + +assert_raises(ZeroDivisionError, sorted, [1, 2, 3], reverse=RaisingBool()) +assert_raises(TypeError, sorted, None, reverse=RaisingBool()) + assert sorted([(1, 2, 3), (0, 3, 6)]) == [(0, 3, 6), (1, 2, 3)] assert sorted([(1, 2, 3), (0, 3, 6)], key=lambda x: x[0]) == [(0, 3, 6), (1, 2, 3)] assert sorted([(1, 2, 3), (0, 3, 6)], key=lambda x: x[1]) == [(1, 2, 3), (0, 3, 6)]