From 809e22543f8bafd2df66fbe116ad49bbca5793f3 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Sat, 9 May 2009 02:07:04 +0000 Subject: [PATCH] lookup __reversed__ correctly as a special method --- Lib/test/test_descr.py | 3 +++ Objects/enumobject.c | 11 ++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index 2b00ce9ea6e..fe4eaeae885 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -1676,12 +1676,15 @@ order (MRO) for bases """ return self def hello(self): return "hello" + def empty_seq(self): + return [] # It would be nice to have every special method tested here, but I'm # only listing the ones I can remember outside of typeobject.c, since it # does it right. specials = [ ("__unicode__", unicode, hello), + ("__reversed__", reversed, empty_seq), # These two fail because the compiler generates LOAD_ATTR to look # them up. We'd have to add a new opcode to fix this, and it's # probably not worth it. diff --git a/Objects/enumobject.c b/Objects/enumobject.c index b1e412d9bf3..12a226c7483 100644 --- a/Objects/enumobject.c +++ b/Objects/enumobject.c @@ -222,7 +222,8 @@ static PyObject * reversed_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { Py_ssize_t n; - PyObject *seq; + PyObject *seq, *reversed_meth; + static PyObject *reversed_cache = NULL; reversedobject *ro; if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds)) @@ -231,8 +232,12 @@ reversed_new(PyTypeObject *type, PyObject *args, PyObject *kwds) if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) ) return NULL; - if (PyObject_HasAttrString(seq, "__reversed__")) - return PyObject_CallMethod(seq, "__reversed__", NULL); + reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__", &reversed_cache); + if (reversed_meth != NULL) { + PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL); + Py_DECREF(reversed_meth); + return res; + } if (!PySequence_Check(seq)) { PyErr_SetString(PyExc_TypeError,