2 /* Class object implementation */
5 #include "structmember.h"
7 /* Free list for method objects to safe malloc/free overhead
8 * The im_self element is used to chain the elements.
10 static PyMethodObject *free_list;
11 static int numfree = 0;
12 #ifndef PyMethod_MAXFREELIST
13 #define PyMethod_MAXFREELIST 256
16 #define TP_DESCR_GET(t) \
17 (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
20 static PyObject *class_lookup(PyClassObject *, PyObject *,
22 static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
23 static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
25 static PyObject *getattrstr, *setattrstr, *delattrstr;
29 PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
30 /* bases is NULL or tuple of classobjects! */
32 PyClassObject *op, *dummy;
33 static PyObject *docstr, *modstr, *namestr;
35 docstr= PyString_InternFromString("__doc__");
40 modstr= PyString_InternFromString("__module__");
44 if (namestr == NULL) {
45 namestr= PyString_InternFromString("__name__");
49 if (name == NULL || !PyString_Check(name)) {
50 PyErr_SetString(PyExc_TypeError,
51 "PyClass_New: name must be a string");
54 if (dict == NULL || !PyDict_Check(dict)) {
55 PyErr_SetString(PyExc_TypeError,
56 "PyClass_New: dict must be a dictionary");
59 if (PyDict_GetItem(dict, docstr) == NULL) {
60 if (PyDict_SetItem(dict, docstr, Py_None) < 0)
63 if (PyDict_GetItem(dict, modstr) == NULL) {
64 PyObject *globals = PyEval_GetGlobals();
65 if (globals != NULL) {
66 PyObject *modname = PyDict_GetItem(globals, namestr);
67 if (modname != NULL) {
68 if (PyDict_SetItem(dict, modstr, modname) < 0)
74 bases = PyTuple_New(0);
81 if (!PyTuple_Check(bases)) {
82 PyErr_SetString(PyExc_TypeError,
83 "PyClass_New: bases must be a tuple");
86 n = PyTuple_Size(bases);
87 for (i = 0; i < n; i++) {
88 base = PyTuple_GET_ITEM(bases, i);
89 if (!PyClass_Check(base)) {
91 (PyObject *) base->ob_type))
92 return PyObject_CallFunctionObjArgs(
93 (PyObject *) base->ob_type,
94 name, bases, dict, NULL);
95 PyErr_SetString(PyExc_TypeError,
96 "PyClass_New: base must be a class");
103 if (getattrstr == NULL) {
104 getattrstr = PyString_InternFromString("__getattr__");
105 if (getattrstr == NULL)
107 setattrstr = PyString_InternFromString("__setattr__");
108 if (setattrstr == NULL)
110 delattrstr = PyString_InternFromString("__delattr__");
111 if (delattrstr == NULL)
115 op = PyObject_GC_New(PyClassObject, &PyClass_Type);
121 op->cl_bases = bases;
126 op->cl_weakreflist = NULL;
128 op->cl_getattr = class_lookup(op, getattrstr, &dummy);
129 op->cl_setattr = class_lookup(op, setattrstr, &dummy);
130 op->cl_delattr = class_lookup(op, delattrstr, &dummy);
131 Py_XINCREF(op->cl_getattr);
132 Py_XINCREF(op->cl_setattr);
133 Py_XINCREF(op->cl_delattr);
134 _PyObject_GC_TRACK(op);
135 return (PyObject *) op;
139 PyMethod_Function(PyObject *im)
141 if (!PyMethod_Check(im)) {
142 PyErr_BadInternalCall();
145 return ((PyMethodObject *)im)->im_func;
149 PyMethod_Self(PyObject *im)
151 if (!PyMethod_Check(im)) {
152 PyErr_BadInternalCall();
155 return ((PyMethodObject *)im)->im_self;
159 PyMethod_Class(PyObject *im)
161 if (!PyMethod_Check(im)) {
162 PyErr_BadInternalCall();
165 return ((PyMethodObject *)im)->im_class;
168 PyDoc_STRVAR(class_doc,
169 "classobj(name, bases, dict)\n\
171 Create a class object. The name must be a string; the second argument\n\
172 a tuple of classes, and the third a dictionary.");
175 class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
177 PyObject *name, *bases, *dict;
178 static char *kwlist[] = {"name", "bases", "dict", 0};
180 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
181 &name, &bases, &dict))
183 return PyClass_New(bases, dict, name);
189 class_dealloc(PyClassObject *op)
191 _PyObject_GC_UNTRACK(op);
192 if (op->cl_weakreflist != NULL)
193 PyObject_ClearWeakRefs((PyObject *) op);
194 Py_DECREF(op->cl_bases);
195 Py_DECREF(op->cl_dict);
196 Py_XDECREF(op->cl_name);
197 Py_XDECREF(op->cl_getattr);
198 Py_XDECREF(op->cl_setattr);
199 Py_XDECREF(op->cl_delattr);
204 class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
207 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
212 n = PyTuple_Size(cp->cl_bases);
213 for (i = 0; i < n; i++) {
214 /* XXX What if one of the bases is not a class? */
215 PyObject *v = class_lookup(
217 PyTuple_GetItem(cp->cl_bases, i), name, pclass);
225 class_getattr(register PyClassObject *op, PyObject *name)
227 register PyObject *v;
228 register char *sname = PyString_AsString(name);
229 PyClassObject *klass;
232 if (sname[0] == '_' && sname[1] == '_') {
233 if (strcmp(sname, "__dict__") == 0) {
234 if (PyEval_GetRestricted()) {
235 PyErr_SetString(PyExc_RuntimeError,
236 "class.__dict__ not accessible in restricted mode");
239 Py_INCREF(op->cl_dict);
242 if (strcmp(sname, "__bases__") == 0) {
243 Py_INCREF(op->cl_bases);
246 if (strcmp(sname, "__name__") == 0) {
247 if (op->cl_name == NULL)
255 v = class_lookup(op, name, &klass);
257 PyErr_Format(PyExc_AttributeError,
258 "class %.50s has no attribute '%.400s'",
259 PyString_AS_STRING(op->cl_name), sname);
262 f = TP_DESCR_GET(v->ob_type);
266 v = f(v, (PyObject *)NULL, (PyObject *)op);
271 set_slot(PyObject **slot, PyObject *v)
273 PyObject *temp = *slot;
280 set_attr_slots(PyClassObject *c)
282 PyClassObject *dummy;
284 set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
285 set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
286 set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
290 set_dict(PyClassObject *c, PyObject *v)
292 if (v == NULL || !PyDict_Check(v))
293 return "__dict__ must be a dictionary object";
294 set_slot(&c->cl_dict, v);
300 set_bases(PyClassObject *c, PyObject *v)
304 if (v == NULL || !PyTuple_Check(v))
305 return "__bases__ must be a tuple object";
307 for (i = 0; i < n; i++) {
308 PyObject *x = PyTuple_GET_ITEM(v, i);
309 if (!PyClass_Check(x))
310 return "__bases__ items must be classes";
311 if (PyClass_IsSubclass(x, (PyObject *)c))
312 return "a __bases__ item causes an inheritance cycle";
314 set_slot(&c->cl_bases, v);
320 set_name(PyClassObject *c, PyObject *v)
322 if (v == NULL || !PyString_Check(v))
323 return "__name__ must be a string object";
324 if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
325 return "__name__ must not contain null bytes";
326 set_slot(&c->cl_name, v);
331 class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
334 if (PyEval_GetRestricted()) {
335 PyErr_SetString(PyExc_RuntimeError,
336 "classes are read-only in restricted mode");
339 sname = PyString_AsString(name);
340 if (sname[0] == '_' && sname[1] == '_') {
341 Py_ssize_t n = PyString_Size(name);
342 if (sname[n-1] == '_' && sname[n-2] == '_') {
344 if (strcmp(sname, "__dict__") == 0)
345 err = set_dict(op, v);
346 else if (strcmp(sname, "__bases__") == 0)
347 err = set_bases(op, v);
348 else if (strcmp(sname, "__name__") == 0)
349 err = set_name(op, v);
350 else if (strcmp(sname, "__getattr__") == 0)
351 set_slot(&op->cl_getattr, v);
352 else if (strcmp(sname, "__setattr__") == 0)
353 set_slot(&op->cl_setattr, v);
354 else if (strcmp(sname, "__delattr__") == 0)
355 set_slot(&op->cl_delattr, v);
356 /* For the last three, we fall through to update the
357 dictionary as well. */
361 PyErr_SetString(PyExc_TypeError, err);
367 int rv = PyDict_DelItem(op->cl_dict, name);
369 PyErr_Format(PyExc_AttributeError,
370 "class %.50s has no attribute '%.400s'",
371 PyString_AS_STRING(op->cl_name), sname);
375 return PyDict_SetItem(op->cl_dict, name, v);
379 class_repr(PyClassObject *op)
381 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
383 if (op->cl_name == NULL || !PyString_Check(op->cl_name))
386 name = PyString_AsString(op->cl_name);
387 if (mod == NULL || !PyString_Check(mod))
388 return PyString_FromFormat("<class ?.%s at %p>", name, op);
390 return PyString_FromFormat("<class %s.%s at %p>",
391 PyString_AsString(mod),
396 class_str(PyClassObject *op)
398 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
399 PyObject *name = op->cl_name;
403 if (name == NULL || !PyString_Check(name))
404 return class_repr(op);
405 if (mod == NULL || !PyString_Check(mod)) {
409 m = PyString_GET_SIZE(mod);
410 n = PyString_GET_SIZE(name);
411 res = PyString_FromStringAndSize((char *)NULL, m+1+n);
413 char *s = PyString_AS_STRING(res);
414 memcpy(s, PyString_AS_STRING(mod), m);
417 memcpy(s, PyString_AS_STRING(name), n);
423 class_traverse(PyClassObject *o, visitproc visit, void *arg)
425 Py_VISIT(o->cl_bases);
426 Py_VISIT(o->cl_dict);
427 Py_VISIT(o->cl_name);
428 Py_VISIT(o->cl_getattr);
429 Py_VISIT(o->cl_setattr);
430 Py_VISIT(o->cl_delattr);
434 PyTypeObject PyClass_Type = {
435 PyObject_HEAD_INIT(&PyType_Type)
438 sizeof(PyClassObject),
440 (destructor)class_dealloc, /* tp_dealloc */
445 (reprfunc)class_repr, /* tp_repr */
446 0, /* tp_as_number */
447 0, /* tp_as_sequence */
448 0, /* tp_as_mapping */
450 PyInstance_New, /* tp_call */
451 (reprfunc)class_str, /* tp_str */
452 (getattrofunc)class_getattr, /* tp_getattro */
453 (setattrofunc)class_setattr, /* tp_setattro */
454 0, /* tp_as_buffer */
455 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
456 class_doc, /* tp_doc */
457 (traverseproc)class_traverse, /* tp_traverse */
459 0, /* tp_richcompare */
460 offsetof(PyClassObject, cl_weakreflist), /* tp_weaklistoffset */
468 0, /* tp_descr_get */
469 0, /* tp_descr_set */
470 0, /* tp_dictoffset */
473 class_new, /* tp_new */
477 PyClass_IsSubclass(PyObject *klass, PyObject *base)
483 if (PyTuple_Check(base)) {
484 n = PyTuple_GET_SIZE(base);
485 for (i = 0; i < n; i++) {
486 if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
491 if (klass == NULL || !PyClass_Check(klass))
493 cp = (PyClassObject *)klass;
494 n = PyTuple_Size(cp->cl_bases);
495 for (i = 0; i < n; i++) {
496 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
503 /* Instance objects */
506 PyInstance_NewRaw(PyObject *klass, PyObject *dict)
508 PyInstanceObject *inst;
510 if (!PyClass_Check(klass)) {
511 PyErr_BadInternalCall();
520 if (!PyDict_Check(dict)) {
521 PyErr_BadInternalCall();
526 inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
531 inst->in_weakreflist = NULL;
533 inst->in_class = (PyClassObject *)klass;
534 inst->in_dict = dict;
535 _PyObject_GC_TRACK(inst);
536 return (PyObject *)inst;
540 PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
542 register PyInstanceObject *inst;
544 static PyObject *initstr;
546 if (initstr == NULL) {
547 initstr = PyString_InternFromString("__init__");
551 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
554 init = instance_getattr2(inst, initstr);
556 if (PyErr_Occurred()) {
560 if ((arg != NULL && (!PyTuple_Check(arg) ||
561 PyTuple_Size(arg) != 0))
562 || (kw != NULL && (!PyDict_Check(kw) ||
563 PyDict_Size(kw) != 0))) {
564 PyErr_SetString(PyExc_TypeError,
565 "this constructor takes no arguments");
571 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
578 if (res != Py_None) {
579 PyErr_SetString(PyExc_TypeError,
580 "__init__() should return None");
587 return (PyObject *)inst;
590 /* Instance methods */
592 PyDoc_STRVAR(instance_doc,
593 "instance(class[, dict])\n\
595 Create an instance without calling its __init__() method.\n\
596 The class must be a classic class.\n\
597 If present, dict must be a dictionary or None.");
600 instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
603 PyObject *dict = Py_None;
605 if (!PyArg_ParseTuple(args, "O!|O:instance",
606 &PyClass_Type, &klass, &dict))
611 else if (!PyDict_Check(dict)) {
612 PyErr_SetString(PyExc_TypeError,
613 "instance() second arg must be dictionary or None");
616 return PyInstance_NewRaw(klass, dict);
621 instance_dealloc(register PyInstanceObject *inst)
623 PyObject *error_type, *error_value, *error_traceback;
625 static PyObject *delstr;
627 _PyObject_GC_UNTRACK(inst);
628 if (inst->in_weakreflist != NULL)
629 PyObject_ClearWeakRefs((PyObject *) inst);
631 /* Temporarily resurrect the object. */
632 assert(inst->ob_type == &PyInstance_Type);
633 assert(inst->ob_refcnt == 0);
636 /* Save the current exception, if any. */
637 PyErr_Fetch(&error_type, &error_value, &error_traceback);
638 /* Execute __del__ method, if any. */
639 if (delstr == NULL) {
640 delstr = PyString_InternFromString("__del__");
642 PyErr_WriteUnraisable((PyObject*)inst);
644 if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
645 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
647 PyErr_WriteUnraisable(del);
652 /* Restore the saved exception. */
653 PyErr_Restore(error_type, error_value, error_traceback);
655 /* Undo the temporary resurrection; can't use DECREF here, it would
656 * cause a recursive call.
658 assert(inst->ob_refcnt > 0);
659 if (--inst->ob_refcnt == 0) {
661 /* New weakrefs could be created during the finalizer call.
662 If this occurs, clear them out without calling their
663 finalizers since they might rely on part of the object
664 being finalized that has already been destroyed. */
665 while (inst->in_weakreflist != NULL) {
666 _PyWeakref_ClearRef((PyWeakReference *)
667 (inst->in_weakreflist));
670 Py_DECREF(inst->in_class);
671 Py_XDECREF(inst->in_dict);
672 PyObject_GC_Del(inst);
675 Py_ssize_t refcnt = inst->ob_refcnt;
676 /* __del__ resurrected it! Make it look like the original
677 * Py_DECREF never happened.
679 _Py_NewReference((PyObject *)inst);
680 inst->ob_refcnt = refcnt;
681 _PyObject_GC_TRACK(inst);
682 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
683 * we need to undo that. */
685 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
686 * object chain, so no more to do there.
687 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
688 * _Py_NewReference bumped tp_allocs: both of those need to be
692 --inst->ob_type->tp_frees;
693 --inst->ob_type->tp_allocs;
699 instance_getattr1(register PyInstanceObject *inst, PyObject *name)
701 register PyObject *v;
702 register char *sname = PyString_AsString(name);
703 if (sname[0] == '_' && sname[1] == '_') {
704 if (strcmp(sname, "__dict__") == 0) {
705 if (PyEval_GetRestricted()) {
706 PyErr_SetString(PyExc_RuntimeError,
707 "instance.__dict__ not accessible in restricted mode");
710 Py_INCREF(inst->in_dict);
711 return inst->in_dict;
713 if (strcmp(sname, "__class__") == 0) {
714 Py_INCREF(inst->in_class);
715 return (PyObject *)inst->in_class;
718 v = instance_getattr2(inst, name);
719 if (v == NULL && !PyErr_Occurred()) {
720 PyErr_Format(PyExc_AttributeError,
721 "%.50s instance has no attribute '%.400s'",
722 PyString_AS_STRING(inst->in_class->cl_name), sname);
728 instance_getattr2(register PyInstanceObject *inst, PyObject *name)
730 register PyObject *v;
731 PyClassObject *klass;
734 v = PyDict_GetItem(inst->in_dict, name);
739 v = class_lookup(inst->in_class, name, &klass);
742 f = TP_DESCR_GET(v->ob_type);
744 PyObject *w = f(v, (PyObject *)inst,
745 (PyObject *)(inst->in_class));
754 instance_getattr(register PyInstanceObject *inst, PyObject *name)
756 register PyObject *func, *res;
757 res = instance_getattr1(inst, name);
758 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
760 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
763 args = PyTuple_Pack(2, inst, name);
766 res = PyEval_CallObject(func, args);
772 /* See classobject.h comments: this only does dict lookups, and is always
776 _PyInstance_Lookup(PyObject *pinst, PyObject *name)
779 PyClassObject *klass;
780 PyInstanceObject *inst; /* pinst cast to the right type */
782 assert(PyInstance_Check(pinst));
783 inst = (PyInstanceObject *)pinst;
785 assert(PyString_Check(name));
787 v = PyDict_GetItem(inst->in_dict, name);
789 v = class_lookup(inst->in_class, name, &klass);
794 instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
797 int rv = PyDict_DelItem(inst->in_dict, name);
799 PyErr_Format(PyExc_AttributeError,
800 "%.50s instance has no attribute '%.400s'",
801 PyString_AS_STRING(inst->in_class->cl_name),
802 PyString_AS_STRING(name));
806 return PyDict_SetItem(inst->in_dict, name, v);
810 instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
812 PyObject *func, *args, *res, *tmp;
813 char *sname = PyString_AsString(name);
814 if (sname[0] == '_' && sname[1] == '_') {
815 Py_ssize_t n = PyString_Size(name);
816 if (sname[n-1] == '_' && sname[n-2] == '_') {
817 if (strcmp(sname, "__dict__") == 0) {
818 if (PyEval_GetRestricted()) {
819 PyErr_SetString(PyExc_RuntimeError,
820 "__dict__ not accessible in restricted mode");
823 if (v == NULL || !PyDict_Check(v)) {
824 PyErr_SetString(PyExc_TypeError,
825 "__dict__ must be set to a dictionary");
834 if (strcmp(sname, "__class__") == 0) {
835 if (PyEval_GetRestricted()) {
836 PyErr_SetString(PyExc_RuntimeError,
837 "__class__ not accessible in restricted mode");
840 if (v == NULL || !PyClass_Check(v)) {
841 PyErr_SetString(PyExc_TypeError,
842 "__class__ must be set to a class");
845 tmp = (PyObject *)(inst->in_class);
847 inst->in_class = (PyClassObject *)v;
854 func = inst->in_class->cl_delattr;
856 func = inst->in_class->cl_setattr;
858 return instance_setattr1(inst, name, v);
860 args = PyTuple_Pack(2, inst, name);
862 args = PyTuple_Pack(3, inst, name, v);
865 res = PyEval_CallObject(func, args);
874 instance_repr(PyInstanceObject *inst)
878 static PyObject *reprstr;
880 if (reprstr == NULL) {
881 reprstr = PyString_InternFromString("__repr__");
885 func = instance_getattr(inst, reprstr);
887 PyObject *classname, *mod;
889 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
892 classname = inst->in_class->cl_name;
893 mod = PyDict_GetItemString(inst->in_class->cl_dict,
895 if (classname != NULL && PyString_Check(classname))
896 cname = PyString_AsString(classname);
899 if (mod == NULL || !PyString_Check(mod))
900 return PyString_FromFormat("<?.%s instance at %p>",
903 return PyString_FromFormat("<%s.%s instance at %p>",
904 PyString_AsString(mod),
907 res = PyEval_CallObject(func, (PyObject *)NULL);
913 instance_str(PyInstanceObject *inst)
917 static PyObject *strstr;
919 if (strstr == NULL) {
920 strstr = PyString_InternFromString("__str__");
924 func = instance_getattr(inst, strstr);
926 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
929 return instance_repr(inst);
931 res = PyEval_CallObject(func, (PyObject *)NULL);
937 instance_hash(PyInstanceObject *inst)
942 static PyObject *hashstr, *eqstr, *cmpstr;
944 if (hashstr == NULL) {
945 hashstr = PyString_InternFromString("__hash__");
949 func = instance_getattr(inst, hashstr);
951 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
954 /* If there is no __eq__ and no __cmp__ method, we hash on the
955 address. If an __eq__ or __cmp__ method exists, there must
958 eqstr = PyString_InternFromString("__eq__");
962 func = instance_getattr(inst, eqstr);
964 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
967 if (cmpstr == NULL) {
968 cmpstr = PyString_InternFromString("__cmp__");
972 func = instance_getattr(inst, cmpstr);
974 if (!PyErr_ExceptionMatches(
975 PyExc_AttributeError))
978 return _Py_HashPointer(inst);
982 PyErr_SetString(PyExc_TypeError, "unhashable instance");
985 res = PyEval_CallObject(func, (PyObject *)NULL);
989 if (PyInt_Check(res) || PyLong_Check(res))
990 /* This already converts a -1 result to -2. */
991 outcome = res->ob_type->tp_hash(res);
993 PyErr_SetString(PyExc_TypeError,
994 "__hash__() should return an int");
1002 instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
1004 Py_VISIT(o->in_class);
1005 Py_VISIT(o->in_dict);
1009 static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
1010 static PyObject *iterstr, *nextstr;
1013 instance_length(PyInstanceObject *inst)
1019 if (lenstr == NULL) {
1020 lenstr = PyString_InternFromString("__len__");
1024 func = instance_getattr(inst, lenstr);
1027 res = PyEval_CallObject(func, (PyObject *)NULL);
1031 if (PyInt_Check(res)) {
1032 outcome = PyInt_AsSsize_t(res);
1033 if (outcome == -1 && PyErr_Occurred()) {
1037 #if SIZEOF_SIZE_T < SIZEOF_INT
1038 /* Overflow check -- range of PyInt is more than C int */
1039 if (outcome != (int)outcome) {
1040 PyErr_SetString(PyExc_OverflowError,
1041 "__len__() should return 0 <= outcome < 2**31");
1047 PyErr_SetString(PyExc_ValueError,
1048 "__len__() should return >= 0");
1053 PyErr_SetString(PyExc_TypeError,
1054 "__len__() should return an int");
1062 instance_subscript(PyInstanceObject *inst, PyObject *key)
1068 if (getitemstr == NULL) {
1069 getitemstr = PyString_InternFromString("__getitem__");
1070 if (getitemstr == NULL)
1073 func = instance_getattr(inst, getitemstr);
1076 arg = PyTuple_Pack(1, key);
1081 res = PyEval_CallObject(func, arg);
1088 instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1094 if (value == NULL) {
1095 if (delitemstr == NULL) {
1096 delitemstr = PyString_InternFromString("__delitem__");
1097 if (delitemstr == NULL)
1100 func = instance_getattr(inst, delitemstr);
1103 if (setitemstr == NULL) {
1104 setitemstr = PyString_InternFromString("__setitem__");
1105 if (setitemstr == NULL)
1108 func = instance_getattr(inst, setitemstr);
1113 arg = PyTuple_Pack(1, key);
1115 arg = PyTuple_Pack(2, key, value);
1120 res = PyEval_CallObject(func, arg);
1129 static PyMappingMethods instance_as_mapping = {
1130 (lenfunc)instance_length, /* mp_length */
1131 (binaryfunc)instance_subscript, /* mp_subscript */
1132 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
1136 instance_item(PyInstanceObject *inst, Py_ssize_t i)
1138 PyObject *func, *res;
1140 if (getitemstr == NULL) {
1141 getitemstr = PyString_InternFromString("__getitem__");
1142 if (getitemstr == NULL)
1145 func = instance_getattr(inst, getitemstr);
1148 res = PyObject_CallFunction(func, "n", i);
1154 instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
1156 PyObject *func, *arg, *res;
1157 static PyObject *getslicestr;
1159 if (getslicestr == NULL) {
1160 getslicestr = PyString_InternFromString("__getslice__");
1161 if (getslicestr == NULL)
1164 func = instance_getattr(inst, getslicestr);
1167 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1171 if (getitemstr == NULL) {
1172 getitemstr = PyString_InternFromString("__getitem__");
1173 if (getitemstr == NULL)
1176 func = instance_getattr(inst, getitemstr);
1179 arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
1182 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
1183 "use __getitem__", 1) < 0) {
1187 arg = Py_BuildValue("(nn)", i, j);
1194 res = PyEval_CallObject(func, arg);
1201 instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
1203 PyObject *func, *arg, *res;
1206 if (delitemstr == NULL) {
1207 delitemstr = PyString_InternFromString("__delitem__");
1208 if (delitemstr == NULL)
1211 func = instance_getattr(inst, delitemstr);
1214 if (setitemstr == NULL) {
1215 setitemstr = PyString_InternFromString("__setitem__");
1216 if (setitemstr == NULL)
1219 func = instance_getattr(inst, setitemstr);
1224 arg = PyInt_FromSsize_t(i);
1226 arg = Py_BuildValue("(nO)", i, item);
1231 res = PyEval_CallObject(func, arg);
1241 instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
1243 PyObject *func, *arg, *res;
1244 static PyObject *setslicestr, *delslicestr;
1246 if (value == NULL) {
1247 if (delslicestr == NULL) {
1249 PyString_InternFromString("__delslice__");
1250 if (delslicestr == NULL)
1253 func = instance_getattr(inst, delslicestr);
1255 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1258 if (delitemstr == NULL) {
1260 PyString_InternFromString("__delitem__");
1261 if (delitemstr == NULL)
1264 func = instance_getattr(inst, delitemstr);
1268 arg = Py_BuildValue("(N)",
1269 _PySlice_FromIndices(i, j));
1272 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
1273 "removed; use __delitem__", 1) < 0) {
1277 arg = Py_BuildValue("(nn)", i, j);
1281 if (setslicestr == NULL) {
1283 PyString_InternFromString("__setslice__");
1284 if (setslicestr == NULL)
1287 func = instance_getattr(inst, setslicestr);
1289 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1292 if (setitemstr == NULL) {
1294 PyString_InternFromString("__setitem__");
1295 if (setitemstr == NULL)
1298 func = instance_getattr(inst, setitemstr);
1302 arg = Py_BuildValue("(NO)",
1303 _PySlice_FromIndices(i, j), value);
1306 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
1307 "removed; use __setitem__", 1) < 0) {
1311 arg = Py_BuildValue("(nnO)", i, j, value);
1318 res = PyEval_CallObject(func, arg);
1328 instance_contains(PyInstanceObject *inst, PyObject *member)
1330 static PyObject *__contains__;
1333 /* Try __contains__ first.
1334 * If that can't be done, try iterator-based searching.
1337 if(__contains__ == NULL) {
1338 __contains__ = PyString_InternFromString("__contains__");
1339 if(__contains__ == NULL)
1342 func = instance_getattr(inst, __contains__);
1346 PyObject *arg = PyTuple_Pack(1, member);
1351 res = PyEval_CallObject(func, arg);
1356 ret = PyObject_IsTrue(res);
1361 /* Couldn't find __contains__. */
1362 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1364 /* Assume the failure was simply due to that there is no
1365 * __contains__ attribute, and try iterating instead.
1368 rc = _PySequence_IterSearch((PyObject *)inst, member,
1369 PY_ITERSEARCH_CONTAINS);
1376 static PySequenceMethods
1377 instance_as_sequence = {
1378 (lenfunc)instance_length, /* sq_length */
1381 (ssizeargfunc)instance_item, /* sq_item */
1382 (ssizessizeargfunc)instance_slice, /* sq_slice */
1383 (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
1384 (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1385 (objobjproc)instance_contains, /* sq_contains */
1389 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1391 PyObject *func, *res;
1393 if ((func = instance_getattr(self, methodname)) == NULL)
1395 res = PyEval_CallObject(func, (PyObject *)NULL);
1401 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1405 PyObject *func = PyObject_GetAttrString(v, opname);
1407 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1410 Py_INCREF(Py_NotImplemented);
1411 return Py_NotImplemented;
1413 args = PyTuple_Pack(1, w);
1418 result = PyEval_CallObject(func, args);
1425 static PyObject *coerce_obj;
1427 /* Try one half of a binary operator involving a class instance. */
1429 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1433 PyObject *coercefunc;
1434 PyObject *coerced = NULL;
1438 if (!PyInstance_Check(v)) {
1439 Py_INCREF(Py_NotImplemented);
1440 return Py_NotImplemented;
1443 if (coerce_obj == NULL) {
1444 coerce_obj = PyString_InternFromString("__coerce__");
1445 if (coerce_obj == NULL)
1448 coercefunc = PyObject_GetAttr(v, coerce_obj);
1449 if (coercefunc == NULL) {
1450 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1453 return generic_binary_op(v, w, opname);
1456 args = PyTuple_Pack(1, w);
1458 Py_DECREF(coercefunc);
1461 coerced = PyEval_CallObject(coercefunc, args);
1463 Py_DECREF(coercefunc);
1464 if (coerced == NULL) {
1467 if (coerced == Py_None || coerced == Py_NotImplemented) {
1469 return generic_binary_op(v, w, opname);
1471 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1473 PyErr_SetString(PyExc_TypeError,
1474 "coercion should return None or 2-tuple");
1477 v1 = PyTuple_GetItem(coerced, 0);
1478 w = PyTuple_GetItem(coerced, 1);
1479 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1480 /* prevent recursion if __coerce__ returns self as the first
1482 result = generic_binary_op(v1, w, opname);
1484 if (Py_EnterRecursiveCall(" after coercion"))
1487 result = (thisfunc)(w, v1);
1489 result = (thisfunc)(v1, w);
1490 Py_LeaveRecursiveCall();
1496 /* Implement a binary operator involving at least one class instance. */
1498 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1499 binaryfunc thisfunc)
1501 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1502 if (result == Py_NotImplemented) {
1504 result = half_binop(w, v, ropname, thisfunc, 1);
1510 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1511 char *ropname, binaryfunc thisfunc)
1513 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1514 if (result == Py_NotImplemented) {
1516 result = do_binop(v, w, opname, ropname, thisfunc);
1522 instance_coerce(PyObject **pv, PyObject **pw)
1526 PyObject *coercefunc;
1530 if (coerce_obj == NULL) {
1531 coerce_obj = PyString_InternFromString("__coerce__");
1532 if (coerce_obj == NULL)
1535 coercefunc = PyObject_GetAttr(v, coerce_obj);
1536 if (coercefunc == NULL) {
1537 /* No __coerce__ method */
1538 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1543 /* Has __coerce__ method: call it */
1544 args = PyTuple_Pack(1, w);
1548 coerced = PyEval_CallObject(coercefunc, args);
1550 Py_DECREF(coercefunc);
1551 if (coerced == NULL) {
1552 /* __coerce__ call raised an exception */
1555 if (coerced == Py_None || coerced == Py_NotImplemented) {
1556 /* __coerce__ says "I can't do it" */
1560 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1561 /* __coerce__ return value is malformed */
1563 PyErr_SetString(PyExc_TypeError,
1564 "coercion should return None or 2-tuple");
1567 /* __coerce__ returned two new values */
1568 *pv = PyTuple_GetItem(coerced, 0);
1569 *pw = PyTuple_GetItem(coerced, 1);
1576 #define UNARY(funcname, methodname) \
1577 static PyObject *funcname(PyInstanceObject *self) { \
1578 static PyObject *o; \
1579 if (o == NULL) { o = PyString_InternFromString(methodname); \
1580 if (o == NULL) return NULL; } \
1581 return generic_unary_op(self, o); \
1584 /* unary function with a fallback */
1585 #define UNARY_FB(funcname, methodname, funcname_fb) \
1586 static PyObject *funcname(PyInstanceObject *self) { \
1587 static PyObject *o; \
1588 if (o == NULL) { o = PyString_InternFromString(methodname); \
1589 if (o == NULL) return NULL; } \
1590 if (PyObject_HasAttr((PyObject*)self, o)) \
1591 return generic_unary_op(self, o); \
1593 return funcname_fb(self); \
1596 #define BINARY(f, m, n) \
1597 static PyObject *f(PyObject *v, PyObject *w) { \
1598 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1601 #define BINARY_INPLACE(f, m, n) \
1602 static PyObject *f(PyObject *v, PyObject *w) { \
1603 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1607 UNARY(instance_neg, "__neg__")
1608 UNARY(instance_pos, "__pos__")
1609 UNARY(instance_abs, "__abs__")
1611 BINARY(instance_or, "or", PyNumber_Or)
1612 BINARY(instance_and, "and", PyNumber_And)
1613 BINARY(instance_xor, "xor", PyNumber_Xor)
1614 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1615 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1616 BINARY(instance_add, "add", PyNumber_Add)
1617 BINARY(instance_sub, "sub", PyNumber_Subtract)
1618 BINARY(instance_mul, "mul", PyNumber_Multiply)
1619 BINARY(instance_div, "div", PyNumber_Divide)
1620 BINARY(instance_mod, "mod", PyNumber_Remainder)
1621 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1622 BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1623 BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1625 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1626 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1627 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1628 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1629 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1630 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1631 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1632 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1633 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1634 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1635 BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1636 BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1638 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1639 -2 for an exception;
1643 2 if this particular 3-way comparison is not implemented or undefined.
1646 half_cmp(PyObject *v, PyObject *w)
1648 static PyObject *cmp_obj;
1654 assert(PyInstance_Check(v));
1656 if (cmp_obj == NULL) {
1657 cmp_obj = PyString_InternFromString("__cmp__");
1658 if (cmp_obj == NULL)
1662 cmp_func = PyObject_GetAttr(v, cmp_obj);
1663 if (cmp_func == NULL) {
1664 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1670 args = PyTuple_Pack(1, w);
1672 Py_DECREF(cmp_func);
1676 result = PyEval_CallObject(cmp_func, args);
1678 Py_DECREF(cmp_func);
1683 if (result == Py_NotImplemented) {
1688 l = PyInt_AsLong(result);
1690 if (l == -1 && PyErr_Occurred()) {
1691 PyErr_SetString(PyExc_TypeError,
1692 "comparison did not return an int");
1696 return l < 0 ? -1 : l > 0 ? 1 : 0;
1699 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1700 We first try a coercion. Return:
1701 -2 for an exception;
1705 2 if this particular 3-way comparison is not implemented or undefined.
1706 THIS IS ONLY CALLED FROM object.c!
1709 instance_compare(PyObject *v, PyObject *w)
1713 c = PyNumber_CoerceEx(&v, &w);
1717 /* If neither is now an instance, use regular comparison */
1718 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1719 c = PyObject_Compare(v, w);
1722 if (PyErr_Occurred())
1724 return c < 0 ? -1 : c > 0 ? 1 : 0;
1728 /* The coercion didn't do anything.
1729 Treat this the same as returning v and w unchanged. */
1734 if (PyInstance_Check(v)) {
1742 if (PyInstance_Check(w)) {
1758 instance_nonzero(PyInstanceObject *self)
1760 PyObject *func, *res;
1762 static PyObject *nonzerostr;
1764 if (nonzerostr == NULL) {
1765 nonzerostr = PyString_InternFromString("__nonzero__");
1766 if (nonzerostr == NULL)
1769 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1770 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1773 if (lenstr == NULL) {
1774 lenstr = PyString_InternFromString("__len__");
1778 if ((func = instance_getattr(self, lenstr)) == NULL) {
1779 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1782 /* Fall back to the default behavior:
1783 all instances are nonzero */
1787 res = PyEval_CallObject(func, (PyObject *)NULL);
1791 if (!PyInt_Check(res)) {
1793 PyErr_SetString(PyExc_TypeError,
1794 "__nonzero__ should return an int");
1797 outcome = PyInt_AsLong(res);
1800 PyErr_SetString(PyExc_ValueError,
1801 "__nonzero__ should return >= 0");
1808 instance_index(PyInstanceObject *self)
1810 PyObject *func, *res;
1811 static PyObject *indexstr = NULL;
1813 if (indexstr == NULL) {
1814 indexstr = PyString_InternFromString("__index__");
1815 if (indexstr == NULL)
1818 if ((func = instance_getattr(self, indexstr)) == NULL) {
1819 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1822 PyErr_SetString(PyExc_TypeError,
1823 "object cannot be interpreted as an index");
1826 res = PyEval_CallObject(func, (PyObject *)NULL);
1832 UNARY(instance_invert, "__invert__")
1833 UNARY(_instance_trunc, "__trunc__")
1836 instance_int(PyInstanceObject *self)
1838 PyObject *truncated;
1839 static PyObject *int_name;
1840 if (int_name == NULL) {
1841 int_name = PyString_InternFromString("__int__");
1842 if (int_name == NULL)
1845 if (PyObject_HasAttr((PyObject*)self, int_name))
1846 return generic_unary_op(self, int_name);
1848 truncated = _instance_trunc(self);
1849 /* __trunc__ is specified to return an Integral type, but
1850 int() needs to return an int. */
1851 return _PyNumber_ConvertIntegralToInt(
1853 "__trunc__ returned non-Integral (type %.200s)");
1856 UNARY_FB(instance_long, "__long__", instance_int)
1857 UNARY(instance_float, "__float__")
1858 UNARY(instance_oct, "__oct__")
1859 UNARY(instance_hex, "__hex__")
1862 bin_power(PyObject *v, PyObject *w)
1864 return PyNumber_Power(v, w, Py_None);
1867 /* This version is for ternary calls only (z != None) */
1869 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1872 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1879 /* XXX Doesn't do coercions... */
1880 func = PyObject_GetAttrString(v, "__pow__");
1883 args = PyTuple_Pack(2, w, z);
1888 result = PyEval_CallObject(func, args);
1896 bin_inplace_power(PyObject *v, PyObject *w)
1898 return PyNumber_InPlacePower(v, w, Py_None);
1903 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1906 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1907 "__rpow__", bin_inplace_power);
1910 /* XXX Doesn't do coercions... */
1915 func = PyObject_GetAttrString(v, "__ipow__");
1917 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1920 return instance_pow(v, w, z);
1922 args = PyTuple_Pack(2, w, z);
1927 result = PyEval_CallObject(func, args);
1935 /* Map rich comparison operators to their __xx__ namesakes */
1937 static PyObject **name_op = NULL;
1943 char *_name_op[] = {
1952 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1953 if (name_op == NULL)
1955 for (i = 0; i < NAME_OPS; ++i) {
1956 name_op[i] = PyString_InternFromString(_name_op[i]);
1957 if (name_op[i] == NULL)
1964 half_richcompare(PyObject *v, PyObject *w, int op)
1970 assert(PyInstance_Check(v));
1972 if (name_op == NULL) {
1973 if (init_name_op() < 0)
1976 /* If the instance doesn't define an __getattr__ method, use
1977 instance_getattr2 directly because it will not set an
1978 exception on failure. */
1979 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1980 method = instance_getattr2((PyInstanceObject *)v,
1983 method = PyObject_GetAttr(v, name_op[op]);
1984 if (method == NULL) {
1985 if (PyErr_Occurred()) {
1986 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1990 res = Py_NotImplemented;
1995 args = PyTuple_Pack(1, w);
2001 res = PyEval_CallObject(method, args);
2009 instance_richcompare(PyObject *v, PyObject *w, int op)
2013 if (PyInstance_Check(v)) {
2014 res = half_richcompare(v, w, op);
2015 if (res != Py_NotImplemented)
2020 if (PyInstance_Check(w)) {
2021 res = half_richcompare(w, v, _Py_SwappedOp[op]);
2022 if (res != Py_NotImplemented)
2027 Py_INCREF(Py_NotImplemented);
2028 return Py_NotImplemented;
2032 /* Get the iterator */
2034 instance_getiter(PyInstanceObject *self)
2038 if (iterstr == NULL) {
2039 iterstr = PyString_InternFromString("__iter__");
2040 if (iterstr == NULL)
2043 if (getitemstr == NULL) {
2044 getitemstr = PyString_InternFromString("__getitem__");
2045 if (getitemstr == NULL)
2049 if ((func = instance_getattr(self, iterstr)) != NULL) {
2050 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2052 if (res != NULL && !PyIter_Check(res)) {
2053 PyErr_Format(PyExc_TypeError,
2054 "__iter__ returned non-iterator "
2056 res->ob_type->tp_name);
2062 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2065 if ((func = instance_getattr(self, getitemstr)) == NULL) {
2066 PyErr_SetString(PyExc_TypeError,
2067 "iteration over non-sequence");
2071 return PySeqIter_New((PyObject *)self);
2075 /* Call the iterator's next */
2077 instance_iternext(PyInstanceObject *self)
2081 if (nextstr == NULL) {
2082 nextstr = PyString_InternFromString("next");
2083 if (nextstr == NULL)
2087 if ((func = instance_getattr(self, nextstr)) != NULL) {
2088 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2093 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
2099 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
2104 instance_call(PyObject *func, PyObject *arg, PyObject *kw)
2106 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
2108 PyInstanceObject *inst = (PyInstanceObject*) func;
2109 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2112 PyErr_Format(PyExc_AttributeError,
2113 "%.200s instance has no __call__ method",
2114 PyString_AsString(inst->in_class->cl_name));
2117 /* We must check and increment the recursion depth here. Scenario:
2120 A.__call__ = A() # that's right
2122 a() # infinite recursion
2123 This bounces between instance_call() and PyObject_Call() without
2124 ever hitting eval_frame() (which has the main recursion check). */
2125 if (Py_EnterRecursiveCall(" in __call__")) {
2129 res = PyObject_Call(call, arg, kw);
2130 Py_LeaveRecursiveCall();
2137 static PyNumberMethods instance_as_number = {
2138 instance_add, /* nb_add */
2139 instance_sub, /* nb_subtract */
2140 instance_mul, /* nb_multiply */
2141 instance_div, /* nb_divide */
2142 instance_mod, /* nb_remainder */
2143 instance_divmod, /* nb_divmod */
2144 instance_pow, /* nb_power */
2145 (unaryfunc)instance_neg, /* nb_negative */
2146 (unaryfunc)instance_pos, /* nb_positive */
2147 (unaryfunc)instance_abs, /* nb_absolute */
2148 (inquiry)instance_nonzero, /* nb_nonzero */
2149 (unaryfunc)instance_invert, /* nb_invert */
2150 instance_lshift, /* nb_lshift */
2151 instance_rshift, /* nb_rshift */
2152 instance_and, /* nb_and */
2153 instance_xor, /* nb_xor */
2154 instance_or, /* nb_or */
2155 instance_coerce, /* nb_coerce */
2156 (unaryfunc)instance_int, /* nb_int */
2157 (unaryfunc)instance_long, /* nb_long */
2158 (unaryfunc)instance_float, /* nb_float */
2159 (unaryfunc)instance_oct, /* nb_oct */
2160 (unaryfunc)instance_hex, /* nb_hex */
2161 instance_iadd, /* nb_inplace_add */
2162 instance_isub, /* nb_inplace_subtract */
2163 instance_imul, /* nb_inplace_multiply */
2164 instance_idiv, /* nb_inplace_divide */
2165 instance_imod, /* nb_inplace_remainder */
2166 instance_ipow, /* nb_inplace_power */
2167 instance_ilshift, /* nb_inplace_lshift */
2168 instance_irshift, /* nb_inplace_rshift */
2169 instance_iand, /* nb_inplace_and */
2170 instance_ixor, /* nb_inplace_xor */
2171 instance_ior, /* nb_inplace_or */
2172 instance_floordiv, /* nb_floor_divide */
2173 instance_truediv, /* nb_true_divide */
2174 instance_ifloordiv, /* nb_inplace_floor_divide */
2175 instance_itruediv, /* nb_inplace_true_divide */
2176 (unaryfunc)instance_index, /* nb_index */
2179 PyTypeObject PyInstance_Type = {
2180 PyObject_HEAD_INIT(&PyType_Type)
2183 sizeof(PyInstanceObject),
2185 (destructor)instance_dealloc, /* tp_dealloc */
2189 instance_compare, /* tp_compare */
2190 (reprfunc)instance_repr, /* tp_repr */
2191 &instance_as_number, /* tp_as_number */
2192 &instance_as_sequence, /* tp_as_sequence */
2193 &instance_as_mapping, /* tp_as_mapping */
2194 (hashfunc)instance_hash, /* tp_hash */
2195 instance_call, /* tp_call */
2196 (reprfunc)instance_str, /* tp_str */
2197 (getattrofunc)instance_getattr, /* tp_getattro */
2198 (setattrofunc)instance_setattr, /* tp_setattro */
2199 0, /* tp_as_buffer */
2200 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2201 instance_doc, /* tp_doc */
2202 (traverseproc)instance_traverse, /* tp_traverse */
2204 instance_richcompare, /* tp_richcompare */
2205 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2206 (getiterfunc)instance_getiter, /* tp_iter */
2207 (iternextfunc)instance_iternext, /* tp_iternext */
2213 0, /* tp_descr_get */
2214 0, /* tp_descr_set */
2215 0, /* tp_dictoffset */
2218 instance_new, /* tp_new */
2222 /* Instance method objects are used for two purposes:
2223 (a) as bound instance methods (returned by instancename.methodname)
2224 (b) as unbound methods (returned by ClassName.methodname)
2225 In case (b), im_self is NULL
2229 PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
2231 register PyMethodObject *im;
2234 free_list = (PyMethodObject *)(im->im_self);
2235 PyObject_INIT(im, &PyMethod_Type);
2239 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2243 im->im_weakreflist = NULL;
2249 im->im_class = klass;
2250 _PyObject_GC_TRACK(im);
2251 return (PyObject *)im;
2254 /* Descriptors for PyMethod attributes */
2256 /* im_class, im_func and im_self are stored in the PyMethod object */
2258 #define OFF(x) offsetof(PyMethodObject, x)
2260 static PyMemberDef instancemethod_memberlist[] = {
2261 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2262 "the class associated with a method"},
2263 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2264 "the function (or other callable) implementing a method"},
2265 {"__func__", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2266 "the function (or other callable) implementing a method"},
2267 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2268 "the instance to which a method is bound; None for unbound methods"},
2269 {"__self__", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2270 "the instance to which a method is bound; None for unbound methods"},
2271 {NULL} /* Sentinel */
2274 /* Christian Tismer argued convincingly that method attributes should
2275 (nearly) always override function attributes.
2276 The one exception is __doc__; there's a default __doc__ which
2277 should only be used for the class, not for instances */
2280 instancemethod_get_doc(PyMethodObject *im, void *context)
2282 static PyObject *docstr;
2283 if (docstr == NULL) {
2284 docstr= PyString_InternFromString("__doc__");
2288 return PyObject_GetAttr(im->im_func, docstr);
2291 static PyGetSetDef instancemethod_getset[] = {
2292 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2297 instancemethod_getattro(PyObject *obj, PyObject *name)
2299 PyMethodObject *im = (PyMethodObject *)obj;
2300 PyTypeObject *tp = obj->ob_type;
2301 PyObject *descr = NULL;
2303 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2304 if (tp->tp_dict == NULL) {
2305 if (PyType_Ready(tp) < 0)
2308 descr = _PyType_Lookup(tp, name);
2311 if (descr != NULL) {
2312 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
2314 return f(descr, obj, (PyObject *)obj->ob_type);
2321 return PyObject_GetAttr(im->im_func, name);
2324 PyDoc_STRVAR(instancemethod_doc,
2325 "instancemethod(function, instance, class)\n\
2327 Create an instance method object.");
2330 instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2334 PyObject *classObj = NULL;
2336 if (!_PyArg_NoKeywords("instancemethod", kw))
2338 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2339 &func, &self, &classObj))
2341 if (!PyCallable_Check(func)) {
2342 PyErr_SetString(PyExc_TypeError,
2343 "first argument must be callable");
2346 if (self == Py_None)
2348 if (self == NULL && classObj == NULL) {
2349 PyErr_SetString(PyExc_TypeError,
2350 "unbound methods must have non-NULL im_class");
2354 return PyMethod_New(func, self, classObj);
2358 instancemethod_dealloc(register PyMethodObject *im)
2360 _PyObject_GC_UNTRACK(im);
2361 if (im->im_weakreflist != NULL)
2362 PyObject_ClearWeakRefs((PyObject *)im);
2363 Py_DECREF(im->im_func);
2364 Py_XDECREF(im->im_self);
2365 Py_XDECREF(im->im_class);
2366 if (numfree < PyMethod_MAXFREELIST) {
2367 im->im_self = (PyObject *)free_list;
2372 PyObject_GC_Del(im);
2377 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2380 cmp = PyObject_Compare(a->im_func, b->im_func);
2384 if (a->im_self == b->im_self)
2386 if (a->im_self == NULL || b->im_self == NULL)
2387 return (a->im_self < b->im_self) ? -1 : 1;
2389 return PyObject_Compare(a->im_self, b->im_self);
2393 instancemethod_repr(PyMethodObject *a)
2395 PyObject *self = a->im_self;
2396 PyObject *func = a->im_func;
2397 PyObject *klass = a->im_class;
2398 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2399 char *sfuncname = "?", *sklassname = "?";
2401 funcname = PyObject_GetAttrString(func, "__name__");
2402 if (funcname == NULL) {
2403 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2407 else if (!PyString_Check(funcname)) {
2408 Py_DECREF(funcname);
2412 sfuncname = PyString_AS_STRING(funcname);
2416 klassname = PyObject_GetAttrString(klass, "__name__");
2417 if (klassname == NULL) {
2418 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2422 else if (!PyString_Check(klassname)) {
2423 Py_DECREF(klassname);
2427 sklassname = PyString_AS_STRING(klassname);
2430 result = PyString_FromFormat("<unbound method %s.%s>",
2431 sklassname, sfuncname);
2433 /* XXX Shouldn't use repr() here! */
2434 PyObject *selfrepr = PyObject_Repr(self);
2435 if (selfrepr == NULL)
2437 if (!PyString_Check(selfrepr)) {
2438 Py_DECREF(selfrepr);
2441 result = PyString_FromFormat("<bound method %s.%s of %s>",
2442 sklassname, sfuncname,
2443 PyString_AS_STRING(selfrepr));
2444 Py_DECREF(selfrepr);
2447 Py_XDECREF(funcname);
2448 Py_XDECREF(klassname);
2453 instancemethod_hash(PyMethodObject *a)
2456 if (a->im_self == NULL)
2457 x = PyObject_Hash(Py_None);
2459 x = PyObject_Hash(a->im_self);
2462 y = PyObject_Hash(a->im_func);
2472 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2474 Py_VISIT(im->im_func);
2475 Py_VISIT(im->im_self);
2476 Py_VISIT(im->im_class);
2481 getclassname(PyObject *klass, char *buf, int bufsize)
2485 assert(bufsize > 1);
2486 strcpy(buf, "?"); /* Default outcome */
2489 name = PyObject_GetAttrString(klass, "__name__");
2491 /* This function cannot return an exception */
2495 if (PyString_Check(name)) {
2496 strncpy(buf, PyString_AS_STRING(name), bufsize);
2497 buf[bufsize-1] = '\0';
2503 getinstclassname(PyObject *inst, char *buf, int bufsize)
2508 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2509 strcpy(buf, "nothing");
2513 klass = PyObject_GetAttrString(inst, "__class__");
2514 if (klass == NULL) {
2515 /* This function cannot return an exception */
2517 klass = (PyObject *)(inst->ob_type);
2520 getclassname(klass, buf, bufsize);
2525 instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2527 PyObject *self = PyMethod_GET_SELF(func);
2528 PyObject *klass = PyMethod_GET_CLASS(func);
2531 func = PyMethod_GET_FUNCTION(func);
2533 /* Unbound methods must be called with an instance of
2534 the class (or a derived class) as first argument */
2536 if (PyTuple_Size(arg) >= 1)
2537 self = PyTuple_GET_ITEM(arg, 0);
2541 ok = PyObject_IsInstance(self, klass);
2548 getclassname(klass, clsbuf, sizeof(clsbuf));
2549 getinstclassname(self, instbuf, sizeof(instbuf));
2550 PyErr_Format(PyExc_TypeError,
2551 "unbound method %s%s must be called with "
2552 "%s instance as first argument "
2553 "(got %s%s instead)",
2554 PyEval_GetFuncName(func),
2555 PyEval_GetFuncDesc(func),
2558 self == NULL ? "" : " instance");
2564 Py_ssize_t argcount = PyTuple_Size(arg);
2565 PyObject *newarg = PyTuple_New(argcount + 1);
2570 PyTuple_SET_ITEM(newarg, 0, self);
2571 for (i = 0; i < argcount; i++) {
2572 PyObject *v = PyTuple_GET_ITEM(arg, i);
2574 PyTuple_SET_ITEM(newarg, i+1, v);
2578 result = PyObject_Call((PyObject *)func, arg, kw);
2584 instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
2586 /* Don't rebind an already bound method, or an unbound method
2587 of a class that's not a base class of cls. */
2589 if (PyMethod_GET_SELF(meth) != NULL) {
2594 /* No, it is an unbound method */
2595 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2596 /* Do subclass test. If it fails, return meth unchanged. */
2597 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2605 /* Bind it to obj */
2606 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
2609 PyTypeObject PyMethod_Type = {
2610 PyObject_HEAD_INIT(&PyType_Type)
2613 sizeof(PyMethodObject),
2615 (destructor)instancemethod_dealloc, /* tp_dealloc */
2619 (cmpfunc)instancemethod_compare, /* tp_compare */
2620 (reprfunc)instancemethod_repr, /* tp_repr */
2621 0, /* tp_as_number */
2622 0, /* tp_as_sequence */
2623 0, /* tp_as_mapping */
2624 (hashfunc)instancemethod_hash, /* tp_hash */
2625 instancemethod_call, /* tp_call */
2627 instancemethod_getattro, /* tp_getattro */
2628 PyObject_GenericSetAttr, /* tp_setattro */
2629 0, /* tp_as_buffer */
2630 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2631 instancemethod_doc, /* tp_doc */
2632 (traverseproc)instancemethod_traverse, /* tp_traverse */
2634 0, /* tp_richcompare */
2635 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2637 0, /* tp_iternext */
2639 instancemethod_memberlist, /* tp_members */
2640 instancemethod_getset, /* tp_getset */
2643 instancemethod_descr_get, /* tp_descr_get */
2644 0, /* tp_descr_set */
2645 0, /* tp_dictoffset */
2648 instancemethod_new, /* tp_new */
2651 /* Clear out the free list */
2654 PyMethod_ClearFreeList(void)
2656 int freelist_size = numfree;
2659 PyMethodObject *im = free_list;
2660 free_list = (PyMethodObject *)(im->im_self);
2661 PyObject_GC_Del(im);
2664 assert(numfree == 0);
2665 return freelist_size;
2671 (void)PyMethod_ClearFreeList();