(Contributed by Serhiy Storchaka in :issue:`12022`.)
+Other CPython Implementation Changes
+====================================
+
+* Special methods :meth:`complex.__complex__` and :meth:`bytes.__bytes__` are implemented to
+ support :class:`typing.SupportsComplex` and :class:`typing.SupportsBytes` protocols.
+ (Contributed by Mark Dickinson and Dong-hee Na in :issue:`24234`.)
+
+
New Modules
===========
class BytesTest(BaseBytesTest, unittest.TestCase):
type2test = bytes
+ def test__bytes__(self):
+ foo = b'foo'
+ self.assertEqual(foo.__bytes__(), foo)
+ self.assertEqual(type(foo.__bytes__()), self.type2test)
+
+ class bytes_subclass(bytes):
+ pass
+
+ bar = bytes_subclass(b'bar')
+ self.assertEqual(bar.__bytes__(), bar)
+ self.assertEqual(type(bar.__bytes__()), self.type2test)
+
def test_getitem_error(self):
b = b'python'
msg = "byte indices must be integers or slices"
def test_supports_bytes(self):
- # Note: bytes itself doesn't have __bytes__.
class B:
def __bytes__(self):
return b''
+ self.assertIsSubclass(bytes, typing.SupportsBytes)
self.assertIsSubclass(B, typing.SupportsBytes)
self.assertNotIsSubclass(str, typing.SupportsBytes)
--- /dev/null
+Implement the :meth:`__bytes__` special method on the :class:`bytes` type,
+so a bytes object ``b`` passes an ``isinstance(b, typing.SupportsBytes)``
+check.
};
+/*[clinic input]
+bytes.__bytes__
+Convert this value to exact type bytes.
+[clinic start generated code]*/
+
+static PyObject *
+bytes___bytes___impl(PyBytesObject *self)
+/*[clinic end generated code: output=63a306a9bc0caac5 input=34ec5ddba98bd6bb]*/
+{
+ if (PyBytes_CheckExact(self)) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ else {
+ return PyBytes_FromString(self->ob_sval);
+ }
+}
+
+
#define LEFTSTRIP 0
#define RIGHTSTRIP 1
#define BOTHSTRIP 2
static PyMethodDef
bytes_methods[] = {
{"__getnewargs__", (PyCFunction)bytes_getnewargs, METH_NOARGS},
+ BYTES___BYTES___METHODDEF
{"capitalize", stringlib_capitalize, METH_NOARGS,
_Py_capitalize__doc__},
STRINGLIB_CENTER_METHODDEF
preserve
[clinic start generated code]*/
+PyDoc_STRVAR(bytes___bytes____doc__,
+"__bytes__($self, /)\n"
+"--\n"
+"\n"
+"Convert this value to exact type bytes.");
+
+#define BYTES___BYTES___METHODDEF \
+ {"__bytes__", (PyCFunction)bytes___bytes__, METH_NOARGS, bytes___bytes____doc__},
+
+static PyObject *
+bytes___bytes___impl(PyBytesObject *self);
+
+static PyObject *
+bytes___bytes__(PyBytesObject *self, PyObject *Py_UNUSED(ignored))
+{
+ return bytes___bytes___impl(self);
+}
+
PyDoc_STRVAR(bytes_split__doc__,
"split($self, /, sep=None, maxsplit=-1)\n"
"--\n"
exit:
return return_value;
}
-/*[clinic end generated code: output=b3f0ec2753246b9c input=a9049054013a1b77]*/
+/*[clinic end generated code: output=d706344859f40122 input=a9049054013a1b77]*/
__abs__
__add__
__and__
-__bytes__
__call__
__delitem__
__divmod__