[pypy-commit] pypy py3k: Add support for the __bytes__ special method.

amauryfa noreply at buildbot.pypy.org
Mon Oct 22 00:34:16 CEST 2012


Author: Amaury Forgeot d'Arc <amauryfa at gmail.com>
Branch: py3k
Changeset: r58343:12c883a639bb
Date: 2012-10-21 12:48 +0200
http://bitbucket.org/pypy/pypy/changeset/12c883a639bb/

Log:	Add support for the __bytes__ special method.

diff --git a/pypy/objspace/std/stringtype.py b/pypy/objspace/std/stringtype.py
--- a/pypy/objspace/std/stringtype.py
+++ b/pypy/objspace/std/stringtype.py
@@ -310,6 +310,12 @@
     else:
         return [c for c in string]
 
+    w_bytes_method = space.lookup(w_source, "__bytes__")
+    if w_bytes_method:
+        w_bytes = space.call_function(w_bytes_method, w_source)
+        # XXX a bit inefficient
+        return space.bytes_w(w_bytes)
+
     # sequence of bytes
     data = []
     w_iter = space.iter(w_source)
diff --git a/pypy/objspace/std/test/test_stringobject.py b/pypy/objspace/std/test/test_stringobject.py
--- a/pypy/objspace/std/test/test_stringobject.py
+++ b/pypy/objspace/std/test/test_stringobject.py
@@ -702,6 +702,12 @@
         assert b[1:0] == b""
         raises(TypeError, "b[3] = 'x'")
 
+    def test_fromobject(self):
+        class S:
+            def __bytes__(self):
+                return b"bytes"
+        assert bytes(S()) == b"bytes"
+
     def test_getnewargs(self):
         assert  b"foo".__getnewargs__() == (b"foo",)
 


More information about the pypy-commit mailing list