[pypy-commit] pypy py3.5-byteformat: add test and impl %b format

plan_rich pypy.commits at gmail.com
Wed Aug 31 04:58:54 EDT 2016


Author: Richard Plangger <planrichi at gmail.com>
Branch: py3.5-byteformat
Changeset: r86771:45a8ee6fd44d
Date: 2016-08-31 10:58 +0200
http://bitbucket.org/pypy/pypy/changeset/45a8ee6fd44d/

Log:	add test and impl %b format

diff --git a/pypy/objspace/std/formatting.py b/pypy/objspace/std/formatting.py
--- a/pypy/objspace/std/formatting.py
+++ b/pypy/objspace/std/formatting.py
@@ -478,7 +478,27 @@
                     self.std_wp(s)
 
         def fmt_b(self, w_value):
-            raise NotImplementedError
+            space = self.space
+            # cpython explicitly checks for bytes & bytearray
+            if space.isinstance_w(w_value, space.w_bytes):
+                self.std_wp(space.bytes_w(w_value))
+                return
+            if space.isinstance_w(w_value, space.w_bytearray):
+                self.std_wp(space.bytes_w(w_value))
+                return
+
+            w_bytes_method = space.lookup(w_value, "__bytes__")
+            if w_bytes_method is not None:
+                w_bytes = space.get_and_call_function(w_bytes_method, w_value)
+                if not space.isinstance_w(w_bytes, space.w_bytes):
+                    raise oefmt(space.w_TypeError,
+                                "__bytes__ returned non-bytes (type '%T')", w_bytes)
+                self.std_wp(space.bytes_w(w_bytes))
+                return
+
+            raise oefmt(space.w_TypeError,
+                    "requires bytes, or an object that" \
+                    "implements __bytes__, not '%T'", w_value)
 
     return StringFormatter
 
diff --git a/pypy/objspace/std/test/test_bytesobject.py b/pypy/objspace/std/test/test_bytesobject.py
--- a/pypy/objspace/std/test/test_bytesobject.py
+++ b/pypy/objspace/std/test/test_bytesobject.py
@@ -1,3 +1,4 @@
+# coding: utf-8
 class TestW_BytesObject:
 
     def teardown_method(self, method):
@@ -880,8 +881,12 @@
         assert b'%04X' % 10 == b'000A'
         assert b'%c' % 48 == b'0'
         assert b'%c' % b'a' == b'a'
+        """
+
+    def test_format_b(self):
+        """
         assert b'%b' % b'abc' == b'abc'
-        assert b'%b' % 'はい'.encode('utf-8') == b'\xe3\x81\xaf\xe3\x81\x84'
+        assert b'%b' % u'はい'.encode('utf-8') == u'はい'.encode('utf-8')
         raises(TypeError, 'b"%b" % 3.14')
         raises(TypeError, 'b"%b" % "hello world"')
         """


More information about the pypy-commit mailing list