Commits

Nick Coghlan committed e9f9656

Use the new subtype to permit use with ord()

  • Participants
  • Parent commits f1560ab
  • Branches bytes_migration_experiment

Comments (0)

Files changed (2)

Lib/test/test_bytes.py

         self.assertRaisesRegex(TypeError, r'\bendswith\b', b.endswith,
                                 x, None, None, None)
 
+    def test_bytes_based_indexing_and_iteration(self):
+        def byte(x):
+            return bytes([x])
+        b = self.type2test(b'hello')
+        self.assertEqual(byte(b[0]), b'h')
+        self.assertEqual(list(map(byte, b)), [b'h',b'e',b'l',b'l',b'o'])
+
+    def test_numeric_indexing_and_iteration(self):
+        b = self.type2test(b'hello')
+        self.assertEqual(ord(b[0]), ord(b'h'))
+        self.assertEqual(list(map(ord, b)), [104, 101, 108, 108, 111])
 
 class BytesTest(BaseBytesTest, unittest.TestCase):
     type2test = bytes

Python/bltinmodule.c

             return PyLong_FromLong(ord);
         }
     }
+    else if (Py_TYPE(obj) == &_PyBytesLong_Type) {
+        /* Transition to returning bytes for bytes iteration & indexing */
+        return PyNumber_Long(obj);
+    }
     else {
         PyErr_Format(PyExc_TypeError,
-                     "ord() expected string of length 1, but " \
+                     "ord() expected str or bytes of length 1, but " \
                      "%.200s found", obj->ob_type->tp_name);
         return NULL;
     }