From c139f145b1be904d7c3e1d01f4be3c123b04b9b3 Mon Sep 17 00:00:00 2001 From: Sergey B Kirpichev Date: Tue, 28 Apr 2015 23:01:12 +0300 Subject: [PATCH] list.sort(): Add quick exit if length of list <= 1 --- Lib/test/test_sort.py | 14 ++++++++++++++ Objects/listobject.c | 3 +++ 2 files changed, 17 insertions(+) diff --git a/Lib/test/test_sort.py b/Lib/test/test_sort.py index a5d0ebf..8c31868 100644 --- a/Lib/test/test_sort.py +++ b/Lib/test/test_sort.py @@ -166,6 +166,20 @@ class TestBugs(unittest.TestCase): self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp)) memorywaster = [memorywaster] + def test_bug24075(self): + # sort() should do quick exit if len(list) <= 1 + + L = [1] + def spam(x): + raise Exception + try: + L.sort(key=spam) + raised = False + except Exception: + raised = True + + self.assertFalse(raised) + #============================================================================== class TestDecorateSortUndecorate(unittest.TestCase): diff --git a/Objects/listobject.c b/Objects/listobject.c index 45e54ce..6741826 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -1938,6 +1938,9 @@ listsort(PyListObject *self, PyObject *args, PyObject *kwds) if (keyfunc == Py_None) keyfunc = NULL; + if (Py_SIZE(self) <= 1) + Py_RETURN_NONE; + /* The list is temporarily made empty, so that mutations performed * by comparison functions can't affect the slice of memory we're * sorting (allowing mutations during sorting is a core-dump -- 1.9.1