[pypy-svn] pypy default: (holger, mfoord) more complete implementation of bytearry.extend

mfoord commits-noreply at bitbucket.org
Mon Jan 17 18:48:07 CET 2011


Author: Michael Foord <michael at voidspace.org.uk>
Branch: 
Changeset: r40807:8f0a96a2432d
Date: 2011-01-17 18:43 +0100
http://bitbucket.org/pypy/pypy/changeset/8f0a96a2432d/

Log:	(holger, mfoord) more complete implementation of bytearry.extend

diff --git a/pypy/objspace/std/bytearrayobject.py b/pypy/objspace/std/bytearrayobject.py
--- a/pypy/objspace/std/bytearrayobject.py
+++ b/pypy/objspace/std/bytearrayobject.py
@@ -381,13 +381,21 @@
     if space.isinstance_w(w_other, space.w_unicode):
         raise OperationError(space.w_TypeError, space.wrap(
             "bytes string or buffer expected"))
-    if not space.isinstance_w(w_other, space.w_list):
-        w_bytearray.data += [c for c in space.bufferstr_w(w_other)]
-    else:
-        l = list()
+    try:
+        other = space.bufferstr_w(w_other)
+    except OperationError, e:
+        if not e.match(space, space.w_TypeError):
+            raise
+        # We now try treating w_other as an iterable
+        l = []
         for w_item in space.unpackiterable(w_other):
             if space.isinstance_w(w_item, space.w_str):
                 res = space.str_w(w_item)
+                if len(res) != 1:
+                    raise OperationError(
+                        space.w_ValueError,
+                        space.wrap("string must be of size 1")
+                    )
             else:
                 i = space.int_w(w_item)
                 try:
@@ -398,9 +406,10 @@
                         space.wrap("byte must be in range(0, 256)")
                     )
 
-
-            l.append(res)
-        w_bytearray.data += l
+            l.append(res)
+        w_bytearray.data += l
+    else:
+        w_bytearray.data += [c for c in other]
 
 def inplace_add__Bytearray_Bytearray(space, w_bytearray1, w_bytearray2):
     list_extend__Bytearray_Bytearray(space, w_bytearray1, w_bytearray2)

diff --git a/pypy/objspace/std/test/test_bytes.py b/pypy/objspace/std/test/test_bytes.py
--- a/pypy/objspace/std/test/test_bytes.py
+++ b/pypy/objspace/std/test/test_bytes.py
@@ -201,7 +201,13 @@
         b.extend(list('hello'))
         assert b == bytearray('worldhello')
 
+        b = bytearray('world')
+        b.extend(c for c in 'hello')
+        assert b == bytearray('worldhello')
+
+        raises(ValueError, b.extend, ['fish'])
         raises(ValueError, b.extend, [256])
+        raises(TypeError, b.extend, object())
         raises(TypeError, b.extend, [object()])
         raises(TypeError, b.extend, u"unicode")
 


More information about the Pypy-commit mailing list