Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9e46abe

Browse files
committed
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.
1 parent df0d87a commit 9e46abe

4 files changed

Lines changed: 34 additions & 3 deletions

File tree

Doc/lib/libarray.tex

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,8 @@ \section{\module{array} ---
145145

146146
\begin{methoddesc}[array]{insert}{i, x}
147147
Insert a new item with value \var{x} in the array before position
148-
\var{i}.
148+
\var{i}. Negative values are treated as being relative to the end
149+
of the array.
149150
\end{methoddesc}
150151

151152
\begin{methoddesc}[array]{pop}{\optional{i}}

Lib/test/test_array.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,30 @@ def test_insert(self):
8282
self.assertRaises(TypeError, a.insert, None)
8383
self.assertRaises(TypeError, a.insert, 0, None)
8484

85+
a = array.array(self.typecode, self.example)
86+
a.insert(-1, self.example[0])
87+
self.assertEqual(
88+
a,
89+
array.array(
90+
self.typecode,
91+
self.example[:-1] + self.example[:1] + self.example[-1:]
92+
)
93+
)
94+
95+
a = array.array(self.typecode, self.example)
96+
a.insert(-1000, self.example[0])
97+
self.assertEqual(
98+
a,
99+
array.array(self.typecode, self.example[:1] + self.example)
100+
)
101+
102+
a = array.array(self.typecode, self.example)
103+
a.insert(1000, self.example[0])
104+
self.assertEqual(
105+
a,
106+
array.array(self.typecode, self.example + self.example[:1])
107+
)
108+
85109
def test_tofromfile(self):
86110
a = array.array(self.typecode, 2*self.example)
87111
self.assertRaises(TypeError, a.tofile)

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ Core and builtins
2626
Extension modules
2727
-----------------
2828

29+
- array.array.insert() now treats negative indices as being relative
30+
to the end of the array, just like list.insert() does. (SF bug #739313)
31+
2932
- The datetime module classes datetime, time, and timedelta are now
3033
properly subclassable.
3134

Modules/arraymodule.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -470,8 +470,11 @@ ins1(arrayobject *self, int where, PyObject *v)
470470
PyErr_NoMemory();
471471
return -1;
472472
}
473-
if (where < 0)
474-
where = 0;
473+
if (where < 0) {
474+
where += self->ob_size;
475+
if (where < 0)
476+
where = 0;
477+
}
475478
if (where > self->ob_size)
476479
where = self->ob_size;
477480
memmove(items + (where+1)*self->ob_descr->itemsize,

0 commit comments

Comments
 (0)