summaryrefslogtreecommitdiffstats
path: root/Objects
diff options
context:
space:
mode:
authorBenjamin Peterson <benjamin@python.org>2012-12-19 21:27:41 (GMT)
committerBenjamin Peterson <benjamin@python.org>2012-12-19 21:27:41 (GMT)
commit5ff3f73d94305900c0773e67ebdd9701d856a0fe (patch)
tree2d63f3211ab3419a020f71fd081ff6d02cf9d7e2 /Objects
parent1f415cf2c2b5f3eec5489ec1276c0629b32b28c0 (diff)
downloadcpython-5ff3f73d94305900c0773e67ebdd9701d856a0fe.zip
cpython-5ff3f73d94305900c0773e67ebdd9701d856a0fe.tar.gz
cpython-5ff3f73d94305900c0773e67ebdd9701d856a0fe.tar.bz2
try to call __bytes__ before __index__ (closes #16722)
Diffstat (limited to 'Objects')
-rw-r--r--Objects/bytesobject.c33
1 files changed, 28 insertions, 5 deletions
diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c
index bf9259f..52db15d 100644
--- a/Objects/bytesobject.c
+++ b/Objects/bytesobject.c
@@ -2505,8 +2505,10 @@ bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
const char *encoding = NULL;
const char *errors = NULL;
PyObject *new = NULL;
+ PyObject *func;
Py_ssize_t size;
static char *kwlist[] = {"source", "encoding", "errors", 0};
+ _Py_IDENTIFIER(__bytes__);
if (type != &PyBytes_Type)
return str_subtype_new(type, args, kwds);
@@ -2536,6 +2538,28 @@ bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
assert(PyBytes_Check(new));
return new;
}
+
+ /* We'd like to call PyObject_Bytes here, but we need to check for an
+ integer argument before deferring to PyBytes_FromObject, something
+ PyObject_Bytes doesn't do. */
+ func = _PyObject_LookupSpecial(x, &PyId___bytes__);
+ if (func != NULL) {
+ new = PyObject_CallFunctionObjArgs(func, NULL);
+ Py_DECREF(func);
+ if (new == NULL)
+ return NULL;
+ if (!PyBytes_Check(new)) {
+ PyErr_Format(PyExc_TypeError,
+ "__bytes__ returned non-bytes (type %.200s)",
+ Py_TYPE(new)->tp_name);
+ Py_DECREF(new);
+ return NULL;
+ }
+ return new;
+ }
+ else if (PyErr_Occurred())
+ return NULL;
+
/* Is it an integer? */
size = PyNumber_AsSsize_t(x, PyExc_OverflowError);
if (size == -1 && PyErr_Occurred()) {
@@ -2549,12 +2573,10 @@ bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
}
else {
new = PyBytes_FromStringAndSize(NULL, size);
- if (new == NULL) {
+ if (new == NULL)
return NULL;
- }
- if (size > 0) {
+ if (size > 0)
memset(((PyBytesObject*)new)->ob_sval, 0, size);
- }
return new;
}
@@ -2564,7 +2586,8 @@ bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
"encoding or errors without a string argument");
return NULL;
}
- return PyObject_Bytes(x);
+
+ return PyBytes_FromObject(x);
}
PyObject *