From 9e46abed5061729915ed39d7bb8c4d014369380e Mon Sep 17 00:00:00 2001 From: =?utf8?q?Walter=20D=C3=B6rwald?= Date: Sun, 18 May 2003 03:15:10 +0000 Subject: [PATCH] Fix array.array.insert(), so that it treats negative indices as being relative to the end of the array, just like list.insert() does. This closes SF bug #739313. --- Doc/lib/libarray.tex | 3 ++- Lib/test/test_array.py | 24 ++++++++++++++++++++++++ Misc/NEWS | 3 +++ Modules/arraymodule.c | 7 +++++-- 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Doc/lib/libarray.tex b/Doc/lib/libarray.tex index a590ed985a..6ec056fbf2 100644 --- a/Doc/lib/libarray.tex +++ b/Doc/lib/libarray.tex @@ -145,7 +145,8 @@ the first occurence of \var{x} in the array. \begin{methoddesc}[array]{insert}{i, x} Insert a new item with value \var{x} in the array before position -\var{i}. +\var{i}. Negative values are treated as being relative to the end +of the array. \end{methoddesc} \begin{methoddesc}[array]{pop}{\optional{i}} diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py index 7a3308be55..98589a5c5b 100755 --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -82,6 +82,30 @@ class BaseTest(unittest.TestCase): self.assertRaises(TypeError, a.insert, None) self.assertRaises(TypeError, a.insert, 0, None) + a = array.array(self.typecode, self.example) + a.insert(-1, self.example[0]) + self.assertEqual( + a, + array.array( + self.typecode, + self.example[:-1] + self.example[:1] + self.example[-1:] + ) + ) + + a = array.array(self.typecode, self.example) + a.insert(-1000, self.example[0]) + self.assertEqual( + a, + array.array(self.typecode, self.example[:1] + self.example) + ) + + a = array.array(self.typecode, self.example) + a.insert(1000, self.example[0]) + self.assertEqual( + a, + array.array(self.typecode, self.example + self.example[:1]) + ) + def test_tofromfile(self): a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.tofile) diff --git a/Misc/NEWS b/Misc/NEWS index 02f845da0f..3a819b881f 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -26,6 +26,9 @@ Core and builtins Extension modules ----------------- +- array.array.insert() now treats negative indices as being relative + to the end of the array, just like list.insert() does. (SF bug #739313) + - The datetime module classes datetime, time, and timedelta are now properly subclassable. diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c index c03160eaba..dcb66cf0a8 100644 --- a/Modules/arraymodule.c +++ b/Modules/arraymodule.c @@ -470,8 +470,11 @@ ins1(arrayobject *self, int where, PyObject *v) PyErr_NoMemory(); return -1; } - if (where < 0) - where = 0; + if (where < 0) { + where += self->ob_size; + if (where < 0) + where = 0; + } if (where > self->ob_size) where = self->ob_size; memmove(items + (where+1)*self->ob_descr->itemsize, -- 2.50.1