]> granicus.if.org Git - python/commitdiff
Add support for negative indices in UserString.MutableString.__setitem__
authorWalter Dörwald <walter@livinglogic.de>
Fri, 18 Feb 2005 13:22:43 +0000 (13:22 +0000)
committerWalter Dörwald <walter@livinglogic.de>
Fri, 18 Feb 2005 13:22:43 +0000 (13:22 +0000)
and UserString.MutableString.__delitem__.

Lib/UserString.py
Lib/test/test_userstring.py
Misc/NEWS

index e8e0fedd87f783724cc4360ac9662c564407abc8..32511390501f92539b23764246e7ade4d22f4b18 100755 (executable)
@@ -146,9 +146,13 @@ class MutableString(UserString):
     def __hash__(self):
         raise TypeError, "unhashable type (it is mutable)"
     def __setitem__(self, index, sub):
+        if index < 0:
+           index += len(self.data)
         if index < 0 or index >= len(self.data): raise IndexError
         self.data = self.data[:index] + sub + self.data[index+1:]
     def __delitem__(self, index):
+        if index < 0:
+           index += len(self.data)
         if index < 0 or index >= len(self.data): raise IndexError
         self.data = self.data[:index] + self.data[index+1:]
     def __setslice__(self, start, end, sub):
index 95f13515385a33b98ce349511f07e610c33bad55..53114db28513ae1a53c7bb3491577dcf748372a2 100755 (executable)
@@ -52,20 +52,20 @@ class MutableStringTest(UserStringTest):
 
     def test_setitem(self):
         s = self.type2test("foo")
-        self.assertRaises(IndexError, s.__setitem__, -1, "bar")
+        self.assertRaises(IndexError, s.__setitem__, -4, "bar")
         self.assertRaises(IndexError, s.__setitem__, 3, "bar")
+        s[-1] = "bar"
+        self.assertEqual(s, "fobar")
         s[0] = "bar"
-        self.assertEqual(s, "baroo")
-        s[4] = "foo"
-        self.assertEqual(s, "barofoo")
+        self.assertEqual(s, "barobar")
 
     def test_delitem(self):
         s = self.type2test("foo")
-        self.assertRaises(IndexError, s.__delitem__, -1)
+        self.assertRaises(IndexError, s.__delitem__, -4)
         self.assertRaises(IndexError, s.__delitem__, 3)
+        del s[-1]
+        self.assertEqual(s, "fo")
         del s[0]
-        self.assertEqual(s, "oo")
-        del s[1]
         self.assertEqual(s, "o")
         del s[0]
         self.assertEqual(s, "")
index a5ab25a01d1a5d9674522b26e8667638a1e647de..71e7b82440dee3322e5d33fd11707aef457a76d5 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -152,6 +152,9 @@ Library
 - The reconvert.quote function can now emit triple-quoted strings.  The
   reconvert module now has some simple documentation.
 
+- ``UserString.MutableString`` now supports negative indices in
+  ``__setitem__`` and ``__delitem__``
+
 Build
 -----