Chris McDonough's patch to defend against certain DoS attacks on FieldStorage.
[python.git] / Objects / classobject.c
blob56bf29c5b5ab44c423378ce00f81bcdfc041236c
2 /* Class object implementation */
4 #include "Python.h"
5 #include "structmember.h"
7 #define TP_DESCR_GET(t) \
8 (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
11 /* Forward */
12 static PyObject *class_lookup(PyClassObject *, PyObject *,
13 PyClassObject **);
14 static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
15 static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
17 static PyObject *getattrstr, *setattrstr, *delattrstr;
20 PyObject *
21 PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
22 /* bases is NULL or tuple of classobjects! */
24 PyClassObject *op, *dummy;
25 static PyObject *docstr, *modstr, *namestr;
26 if (docstr == NULL) {
27 docstr= PyString_InternFromString("__doc__");
28 if (docstr == NULL)
29 return NULL;
31 if (modstr == NULL) {
32 modstr= PyString_InternFromString("__module__");
33 if (modstr == NULL)
34 return NULL;
36 if (namestr == NULL) {
37 namestr= PyString_InternFromString("__name__");
38 if (namestr == NULL)
39 return NULL;
41 if (name == NULL || !PyString_Check(name)) {
42 PyErr_SetString(PyExc_TypeError,
43 "PyClass_New: name must be a string");
44 return NULL;
46 if (dict == NULL || !PyDict_Check(dict)) {
47 PyErr_SetString(PyExc_TypeError,
48 "PyClass_New: dict must be a dictionary");
49 return NULL;
51 if (PyDict_GetItem(dict, docstr) == NULL) {
52 if (PyDict_SetItem(dict, docstr, Py_None) < 0)
53 return NULL;
55 if (PyDict_GetItem(dict, modstr) == NULL) {
56 PyObject *globals = PyEval_GetGlobals();
57 if (globals != NULL) {
58 PyObject *modname = PyDict_GetItem(globals, namestr);
59 if (modname != NULL) {
60 if (PyDict_SetItem(dict, modstr, modname) < 0)
61 return NULL;
65 if (bases == NULL) {
66 bases = PyTuple_New(0);
67 if (bases == NULL)
68 return NULL;
70 else {
71 Py_ssize_t i, n;
72 PyObject *base;
73 if (!PyTuple_Check(bases)) {
74 PyErr_SetString(PyExc_TypeError,
75 "PyClass_New: bases must be a tuple");
76 return NULL;
78 n = PyTuple_Size(bases);
79 for (i = 0; i < n; i++) {
80 base = PyTuple_GET_ITEM(bases, i);
81 if (!PyClass_Check(base)) {
82 if (PyCallable_Check(
83 (PyObject *) base->ob_type))
84 return PyObject_CallFunctionObjArgs(
85 (PyObject *) base->ob_type,
86 name, bases, dict, NULL);
87 PyErr_SetString(PyExc_TypeError,
88 "PyClass_New: base must be a class");
89 return NULL;
92 Py_INCREF(bases);
94 op = PyObject_GC_New(PyClassObject, &PyClass_Type);
95 if (op == NULL) {
96 Py_DECREF(bases);
97 return NULL;
99 op->cl_bases = bases;
100 Py_INCREF(dict);
101 op->cl_dict = dict;
102 Py_XINCREF(name);
103 op->cl_name = name;
104 if (getattrstr == NULL) {
105 getattrstr = PyString_InternFromString("__getattr__");
106 setattrstr = PyString_InternFromString("__setattr__");
107 delattrstr = PyString_InternFromString("__delattr__");
109 op->cl_getattr = class_lookup(op, getattrstr, &dummy);
110 op->cl_setattr = class_lookup(op, setattrstr, &dummy);
111 op->cl_delattr = class_lookup(op, delattrstr, &dummy);
112 Py_XINCREF(op->cl_getattr);
113 Py_XINCREF(op->cl_setattr);
114 Py_XINCREF(op->cl_delattr);
115 _PyObject_GC_TRACK(op);
116 return (PyObject *) op;
119 PyObject *
120 PyMethod_Function(PyObject *im)
122 if (!PyMethod_Check(im)) {
123 PyErr_BadInternalCall();
124 return NULL;
126 return ((PyMethodObject *)im)->im_func;
129 PyObject *
130 PyMethod_Self(PyObject *im)
132 if (!PyMethod_Check(im)) {
133 PyErr_BadInternalCall();
134 return NULL;
136 return ((PyMethodObject *)im)->im_self;
139 PyObject *
140 PyMethod_Class(PyObject *im)
142 if (!PyMethod_Check(im)) {
143 PyErr_BadInternalCall();
144 return NULL;
146 return ((PyMethodObject *)im)->im_class;
149 PyDoc_STRVAR(class_doc,
150 "classobj(name, bases, dict)\n\
152 Create a class object. The name must be a string; the second argument\n\
153 a tuple of classes, and the third a dictionary.");
155 static PyObject *
156 class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
158 PyObject *name, *bases, *dict;
159 static char *kwlist[] = {"name", "bases", "dict", 0};
161 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
162 &name, &bases, &dict))
163 return NULL;
164 return PyClass_New(bases, dict, name);
167 /* Class methods */
169 static void
170 class_dealloc(PyClassObject *op)
172 _PyObject_GC_UNTRACK(op);
173 Py_DECREF(op->cl_bases);
174 Py_DECREF(op->cl_dict);
175 Py_XDECREF(op->cl_name);
176 Py_XDECREF(op->cl_getattr);
177 Py_XDECREF(op->cl_setattr);
178 Py_XDECREF(op->cl_delattr);
179 PyObject_GC_Del(op);
182 static PyObject *
183 class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
185 Py_ssize_t i, n;
186 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
187 if (value != NULL) {
188 *pclass = cp;
189 return value;
191 n = PyTuple_Size(cp->cl_bases);
192 for (i = 0; i < n; i++) {
193 /* XXX What if one of the bases is not a class? */
194 PyObject *v = class_lookup(
195 (PyClassObject *)
196 PyTuple_GetItem(cp->cl_bases, i), name, pclass);
197 if (v != NULL)
198 return v;
200 return NULL;
203 static PyObject *
204 class_getattr(register PyClassObject *op, PyObject *name)
206 register PyObject *v;
207 register char *sname = PyString_AsString(name);
208 PyClassObject *klass;
209 descrgetfunc f;
211 if (sname[0] == '_' && sname[1] == '_') {
212 if (strcmp(sname, "__dict__") == 0) {
213 if (PyEval_GetRestricted()) {
214 PyErr_SetString(PyExc_RuntimeError,
215 "class.__dict__ not accessible in restricted mode");
216 return NULL;
218 Py_INCREF(op->cl_dict);
219 return op->cl_dict;
221 if (strcmp(sname, "__bases__") == 0) {
222 Py_INCREF(op->cl_bases);
223 return op->cl_bases;
225 if (strcmp(sname, "__name__") == 0) {
226 if (op->cl_name == NULL)
227 v = Py_None;
228 else
229 v = op->cl_name;
230 Py_INCREF(v);
231 return v;
234 v = class_lookup(op, name, &klass);
235 if (v == NULL) {
236 PyErr_Format(PyExc_AttributeError,
237 "class %.50s has no attribute '%.400s'",
238 PyString_AS_STRING(op->cl_name), sname);
239 return NULL;
241 f = TP_DESCR_GET(v->ob_type);
242 if (f == NULL)
243 Py_INCREF(v);
244 else
245 v = f(v, (PyObject *)NULL, (PyObject *)op);
246 return v;
249 static void
250 set_slot(PyObject **slot, PyObject *v)
252 PyObject *temp = *slot;
253 Py_XINCREF(v);
254 *slot = v;
255 Py_XDECREF(temp);
258 static void
259 set_attr_slots(PyClassObject *c)
261 PyClassObject *dummy;
263 set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
264 set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
265 set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
268 static char *
269 set_dict(PyClassObject *c, PyObject *v)
271 if (v == NULL || !PyDict_Check(v))
272 return "__dict__ must be a dictionary object";
273 set_slot(&c->cl_dict, v);
274 set_attr_slots(c);
275 return "";
278 static char *
279 set_bases(PyClassObject *c, PyObject *v)
281 Py_ssize_t i, n;
283 if (v == NULL || !PyTuple_Check(v))
284 return "__bases__ must be a tuple object";
285 n = PyTuple_Size(v);
286 for (i = 0; i < n; i++) {
287 PyObject *x = PyTuple_GET_ITEM(v, i);
288 if (!PyClass_Check(x))
289 return "__bases__ items must be classes";
290 if (PyClass_IsSubclass(x, (PyObject *)c))
291 return "a __bases__ item causes an inheritance cycle";
293 set_slot(&c->cl_bases, v);
294 set_attr_slots(c);
295 return "";
298 static char *
299 set_name(PyClassObject *c, PyObject *v)
301 if (v == NULL || !PyString_Check(v))
302 return "__name__ must be a string object";
303 if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
304 return "__name__ must not contain null bytes";
305 set_slot(&c->cl_name, v);
306 return "";
309 static int
310 class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
312 char *sname;
313 if (PyEval_GetRestricted()) {
314 PyErr_SetString(PyExc_RuntimeError,
315 "classes are read-only in restricted mode");
316 return -1;
318 sname = PyString_AsString(name);
319 if (sname[0] == '_' && sname[1] == '_') {
320 Py_ssize_t n = PyString_Size(name);
321 if (sname[n-1] == '_' && sname[n-2] == '_') {
322 char *err = NULL;
323 if (strcmp(sname, "__dict__") == 0)
324 err = set_dict(op, v);
325 else if (strcmp(sname, "__bases__") == 0)
326 err = set_bases(op, v);
327 else if (strcmp(sname, "__name__") == 0)
328 err = set_name(op, v);
329 else if (strcmp(sname, "__getattr__") == 0)
330 set_slot(&op->cl_getattr, v);
331 else if (strcmp(sname, "__setattr__") == 0)
332 set_slot(&op->cl_setattr, v);
333 else if (strcmp(sname, "__delattr__") == 0)
334 set_slot(&op->cl_delattr, v);
335 /* For the last three, we fall through to update the
336 dictionary as well. */
337 if (err != NULL) {
338 if (*err == '\0')
339 return 0;
340 PyErr_SetString(PyExc_TypeError, err);
341 return -1;
345 if (v == NULL) {
346 int rv = PyDict_DelItem(op->cl_dict, name);
347 if (rv < 0)
348 PyErr_Format(PyExc_AttributeError,
349 "class %.50s has no attribute '%.400s'",
350 PyString_AS_STRING(op->cl_name), sname);
351 return rv;
353 else
354 return PyDict_SetItem(op->cl_dict, name, v);
357 static PyObject *
358 class_repr(PyClassObject *op)
360 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
361 char *name;
362 if (op->cl_name == NULL || !PyString_Check(op->cl_name))
363 name = "?";
364 else
365 name = PyString_AsString(op->cl_name);
366 if (mod == NULL || !PyString_Check(mod))
367 return PyString_FromFormat("<class ?.%s at %p>", name, op);
368 else
369 return PyString_FromFormat("<class %s.%s at %p>",
370 PyString_AsString(mod),
371 name, op);
374 static PyObject *
375 class_str(PyClassObject *op)
377 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
378 PyObject *name = op->cl_name;
379 PyObject *res;
380 Py_ssize_t m, n;
382 if (name == NULL || !PyString_Check(name))
383 return class_repr(op);
384 if (mod == NULL || !PyString_Check(mod)) {
385 Py_INCREF(name);
386 return name;
388 m = PyString_GET_SIZE(mod);
389 n = PyString_GET_SIZE(name);
390 res = PyString_FromStringAndSize((char *)NULL, m+1+n);
391 if (res != NULL) {
392 char *s = PyString_AS_STRING(res);
393 memcpy(s, PyString_AS_STRING(mod), m);
394 s += m;
395 *s++ = '.';
396 memcpy(s, PyString_AS_STRING(name), n);
398 return res;
401 static int
402 class_traverse(PyClassObject *o, visitproc visit, void *arg)
404 Py_VISIT(o->cl_bases);
405 Py_VISIT(o->cl_dict);
406 Py_VISIT(o->cl_name);
407 Py_VISIT(o->cl_getattr);
408 Py_VISIT(o->cl_setattr);
409 Py_VISIT(o->cl_delattr);
410 return 0;
413 PyTypeObject PyClass_Type = {
414 PyObject_HEAD_INIT(&PyType_Type)
416 "classobj",
417 sizeof(PyClassObject),
419 (destructor)class_dealloc, /* tp_dealloc */
420 0, /* tp_print */
421 0, /* tp_getattr */
422 0, /* tp_setattr */
423 0, /* tp_compare */
424 (reprfunc)class_repr, /* tp_repr */
425 0, /* tp_as_number */
426 0, /* tp_as_sequence */
427 0, /* tp_as_mapping */
428 0, /* tp_hash */
429 PyInstance_New, /* tp_call */
430 (reprfunc)class_str, /* tp_str */
431 (getattrofunc)class_getattr, /* tp_getattro */
432 (setattrofunc)class_setattr, /* tp_setattro */
433 0, /* tp_as_buffer */
434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
435 class_doc, /* tp_doc */
436 (traverseproc)class_traverse, /* tp_traverse */
437 0, /* tp_clear */
438 0, /* tp_richcompare */
439 0, /* tp_weaklistoffset */
440 0, /* tp_iter */
441 0, /* tp_iternext */
442 0, /* tp_methods */
443 0, /* tp_members */
444 0, /* tp_getset */
445 0, /* tp_base */
446 0, /* tp_dict */
447 0, /* tp_descr_get */
448 0, /* tp_descr_set */
449 0, /* tp_dictoffset */
450 0, /* tp_init */
451 0, /* tp_alloc */
452 class_new, /* tp_new */
456 PyClass_IsSubclass(PyObject *klass, PyObject *base)
458 Py_ssize_t i, n;
459 PyClassObject *cp;
460 if (klass == base)
461 return 1;
462 if (PyTuple_Check(base)) {
463 n = PyTuple_GET_SIZE(base);
464 for (i = 0; i < n; i++) {
465 if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
466 return 1;
468 return 0;
470 if (klass == NULL || !PyClass_Check(klass))
471 return 0;
472 cp = (PyClassObject *)klass;
473 n = PyTuple_Size(cp->cl_bases);
474 for (i = 0; i < n; i++) {
475 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
476 return 1;
478 return 0;
482 /* Instance objects */
484 PyObject *
485 PyInstance_NewRaw(PyObject *klass, PyObject *dict)
487 PyInstanceObject *inst;
489 if (!PyClass_Check(klass)) {
490 PyErr_BadInternalCall();
491 return NULL;
493 if (dict == NULL) {
494 dict = PyDict_New();
495 if (dict == NULL)
496 return NULL;
498 else {
499 if (!PyDict_Check(dict)) {
500 PyErr_BadInternalCall();
501 return NULL;
503 Py_INCREF(dict);
505 inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
506 if (inst == NULL) {
507 Py_DECREF(dict);
508 return NULL;
510 inst->in_weakreflist = NULL;
511 Py_INCREF(klass);
512 inst->in_class = (PyClassObject *)klass;
513 inst->in_dict = dict;
514 _PyObject_GC_TRACK(inst);
515 return (PyObject *)inst;
518 PyObject *
519 PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
521 register PyInstanceObject *inst;
522 PyObject *init;
523 static PyObject *initstr;
525 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
526 if (inst == NULL)
527 return NULL;
528 if (initstr == NULL)
529 initstr = PyString_InternFromString("__init__");
530 init = instance_getattr2(inst, initstr);
531 if (init == NULL) {
532 if (PyErr_Occurred()) {
533 Py_DECREF(inst);
534 return NULL;
536 if ((arg != NULL && (!PyTuple_Check(arg) ||
537 PyTuple_Size(arg) != 0))
538 || (kw != NULL && (!PyDict_Check(kw) ||
539 PyDict_Size(kw) != 0))) {
540 PyErr_SetString(PyExc_TypeError,
541 "this constructor takes no arguments");
542 Py_DECREF(inst);
543 inst = NULL;
546 else {
547 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
548 Py_DECREF(init);
549 if (res == NULL) {
550 Py_DECREF(inst);
551 inst = NULL;
553 else {
554 if (res != Py_None) {
555 PyErr_SetString(PyExc_TypeError,
556 "__init__() should return None");
557 Py_DECREF(inst);
558 inst = NULL;
560 Py_DECREF(res);
563 return (PyObject *)inst;
566 /* Instance methods */
568 PyDoc_STRVAR(instance_doc,
569 "instance(class[, dict])\n\
571 Create an instance without calling its __init__() method.\n\
572 The class must be a classic class.\n\
573 If present, dict must be a dictionary or None.");
575 static PyObject *
576 instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
578 PyObject *klass;
579 PyObject *dict = Py_None;
581 if (!PyArg_ParseTuple(args, "O!|O:instance",
582 &PyClass_Type, &klass, &dict))
583 return NULL;
585 if (dict == Py_None)
586 dict = NULL;
587 else if (!PyDict_Check(dict)) {
588 PyErr_SetString(PyExc_TypeError,
589 "instance() second arg must be dictionary or None");
590 return NULL;
592 return PyInstance_NewRaw(klass, dict);
596 static void
597 instance_dealloc(register PyInstanceObject *inst)
599 PyObject *error_type, *error_value, *error_traceback;
600 PyObject *del;
601 static PyObject *delstr;
603 _PyObject_GC_UNTRACK(inst);
604 if (inst->in_weakreflist != NULL)
605 PyObject_ClearWeakRefs((PyObject *) inst);
607 /* Temporarily resurrect the object. */
608 assert(inst->ob_type == &PyInstance_Type);
609 assert(inst->ob_refcnt == 0);
610 inst->ob_refcnt = 1;
612 /* Save the current exception, if any. */
613 PyErr_Fetch(&error_type, &error_value, &error_traceback);
614 /* Execute __del__ method, if any. */
615 if (delstr == NULL)
616 delstr = PyString_InternFromString("__del__");
617 if ((del = instance_getattr2(inst, delstr)) != NULL) {
618 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
619 if (res == NULL)
620 PyErr_WriteUnraisable(del);
621 else
622 Py_DECREF(res);
623 Py_DECREF(del);
625 /* Restore the saved exception. */
626 PyErr_Restore(error_type, error_value, error_traceback);
628 /* Undo the temporary resurrection; can't use DECREF here, it would
629 * cause a recursive call.
631 assert(inst->ob_refcnt > 0);
632 if (--inst->ob_refcnt == 0) {
633 Py_DECREF(inst->in_class);
634 Py_XDECREF(inst->in_dict);
635 PyObject_GC_Del(inst);
637 else {
638 Py_ssize_t refcnt = inst->ob_refcnt;
639 /* __del__ resurrected it! Make it look like the original
640 * Py_DECREF never happened.
642 _Py_NewReference((PyObject *)inst);
643 inst->ob_refcnt = refcnt;
644 _PyObject_GC_TRACK(inst);
645 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
646 * we need to undo that. */
647 _Py_DEC_REFTOTAL;
648 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
649 * object chain, so no more to do there.
650 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
651 * _Py_NewReference bumped tp_allocs: both of those need to be
652 * undone.
654 #ifdef COUNT_ALLOCS
655 --inst->ob_type->tp_frees;
656 --inst->ob_type->tp_allocs;
657 #endif
661 static PyObject *
662 instance_getattr1(register PyInstanceObject *inst, PyObject *name)
664 register PyObject *v;
665 register char *sname = PyString_AsString(name);
666 if (sname[0] == '_' && sname[1] == '_') {
667 if (strcmp(sname, "__dict__") == 0) {
668 if (PyEval_GetRestricted()) {
669 PyErr_SetString(PyExc_RuntimeError,
670 "instance.__dict__ not accessible in restricted mode");
671 return NULL;
673 Py_INCREF(inst->in_dict);
674 return inst->in_dict;
676 if (strcmp(sname, "__class__") == 0) {
677 Py_INCREF(inst->in_class);
678 return (PyObject *)inst->in_class;
681 v = instance_getattr2(inst, name);
682 if (v == NULL && !PyErr_Occurred()) {
683 PyErr_Format(PyExc_AttributeError,
684 "%.50s instance has no attribute '%.400s'",
685 PyString_AS_STRING(inst->in_class->cl_name), sname);
687 return v;
690 static PyObject *
691 instance_getattr2(register PyInstanceObject *inst, PyObject *name)
693 register PyObject *v;
694 PyClassObject *klass;
695 descrgetfunc f;
697 v = PyDict_GetItem(inst->in_dict, name);
698 if (v != NULL) {
699 Py_INCREF(v);
700 return v;
702 v = class_lookup(inst->in_class, name, &klass);
703 if (v != NULL) {
704 Py_INCREF(v);
705 f = TP_DESCR_GET(v->ob_type);
706 if (f != NULL) {
707 PyObject *w = f(v, (PyObject *)inst,
708 (PyObject *)(inst->in_class));
709 Py_DECREF(v);
710 v = w;
713 return v;
716 static PyObject *
717 instance_getattr(register PyInstanceObject *inst, PyObject *name)
719 register PyObject *func, *res;
720 res = instance_getattr1(inst, name);
721 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
722 PyObject *args;
723 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
724 return NULL;
725 PyErr_Clear();
726 args = PyTuple_Pack(2, inst, name);
727 if (args == NULL)
728 return NULL;
729 res = PyEval_CallObject(func, args);
730 Py_DECREF(args);
732 return res;
735 /* See classobject.h comments: this only does dict lookups, and is always
736 * safe to call.
738 PyObject *
739 _PyInstance_Lookup(PyObject *pinst, PyObject *name)
741 PyObject *v;
742 PyClassObject *klass;
743 PyInstanceObject *inst; /* pinst cast to the right type */
745 assert(PyInstance_Check(pinst));
746 inst = (PyInstanceObject *)pinst;
748 assert(PyString_Check(name));
750 v = PyDict_GetItem(inst->in_dict, name);
751 if (v == NULL)
752 v = class_lookup(inst->in_class, name, &klass);
753 return v;
756 static int
757 instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
759 if (v == NULL) {
760 int rv = PyDict_DelItem(inst->in_dict, name);
761 if (rv < 0)
762 PyErr_Format(PyExc_AttributeError,
763 "%.50s instance has no attribute '%.400s'",
764 PyString_AS_STRING(inst->in_class->cl_name),
765 PyString_AS_STRING(name));
766 return rv;
768 else
769 return PyDict_SetItem(inst->in_dict, name, v);
772 static int
773 instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
775 PyObject *func, *args, *res, *tmp;
776 char *sname = PyString_AsString(name);
777 if (sname[0] == '_' && sname[1] == '_') {
778 Py_ssize_t n = PyString_Size(name);
779 if (sname[n-1] == '_' && sname[n-2] == '_') {
780 if (strcmp(sname, "__dict__") == 0) {
781 if (PyEval_GetRestricted()) {
782 PyErr_SetString(PyExc_RuntimeError,
783 "__dict__ not accessible in restricted mode");
784 return -1;
786 if (v == NULL || !PyDict_Check(v)) {
787 PyErr_SetString(PyExc_TypeError,
788 "__dict__ must be set to a dictionary");
789 return -1;
791 tmp = inst->in_dict;
792 Py_INCREF(v);
793 inst->in_dict = v;
794 Py_DECREF(tmp);
795 return 0;
797 if (strcmp(sname, "__class__") == 0) {
798 if (PyEval_GetRestricted()) {
799 PyErr_SetString(PyExc_RuntimeError,
800 "__class__ not accessible in restricted mode");
801 return -1;
803 if (v == NULL || !PyClass_Check(v)) {
804 PyErr_SetString(PyExc_TypeError,
805 "__class__ must be set to a class");
806 return -1;
808 tmp = (PyObject *)(inst->in_class);
809 Py_INCREF(v);
810 inst->in_class = (PyClassObject *)v;
811 Py_DECREF(tmp);
812 return 0;
816 if (v == NULL)
817 func = inst->in_class->cl_delattr;
818 else
819 func = inst->in_class->cl_setattr;
820 if (func == NULL)
821 return instance_setattr1(inst, name, v);
822 if (v == NULL)
823 args = PyTuple_Pack(2, inst, name);
824 else
825 args = PyTuple_Pack(3, inst, name, v);
826 if (args == NULL)
827 return -1;
828 res = PyEval_CallObject(func, args);
829 Py_DECREF(args);
830 if (res == NULL)
831 return -1;
832 Py_DECREF(res);
833 return 0;
836 static PyObject *
837 instance_repr(PyInstanceObject *inst)
839 PyObject *func;
840 PyObject *res;
841 static PyObject *reprstr;
843 if (reprstr == NULL)
844 reprstr = PyString_InternFromString("__repr__");
845 func = instance_getattr(inst, reprstr);
846 if (func == NULL) {
847 PyObject *classname, *mod;
848 char *cname;
849 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
850 return NULL;
851 PyErr_Clear();
852 classname = inst->in_class->cl_name;
853 mod = PyDict_GetItemString(inst->in_class->cl_dict,
854 "__module__");
855 if (classname != NULL && PyString_Check(classname))
856 cname = PyString_AsString(classname);
857 else
858 cname = "?";
859 if (mod == NULL || !PyString_Check(mod))
860 return PyString_FromFormat("<?.%s instance at %p>",
861 cname, inst);
862 else
863 return PyString_FromFormat("<%s.%s instance at %p>",
864 PyString_AsString(mod),
865 cname, inst);
867 res = PyEval_CallObject(func, (PyObject *)NULL);
868 Py_DECREF(func);
869 return res;
872 static PyObject *
873 instance_str(PyInstanceObject *inst)
875 PyObject *func;
876 PyObject *res;
877 static PyObject *strstr;
879 if (strstr == NULL)
880 strstr = PyString_InternFromString("__str__");
881 func = instance_getattr(inst, strstr);
882 if (func == NULL) {
883 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
884 return NULL;
885 PyErr_Clear();
886 return instance_repr(inst);
888 res = PyEval_CallObject(func, (PyObject *)NULL);
889 Py_DECREF(func);
890 return res;
893 static long
894 instance_hash(PyInstanceObject *inst)
896 PyObject *func;
897 PyObject *res;
898 long outcome;
899 static PyObject *hashstr, *eqstr, *cmpstr;
901 if (hashstr == NULL)
902 hashstr = PyString_InternFromString("__hash__");
903 func = instance_getattr(inst, hashstr);
904 if (func == NULL) {
905 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
906 return -1;
907 PyErr_Clear();
908 /* If there is no __eq__ and no __cmp__ method, we hash on the
909 address. If an __eq__ or __cmp__ method exists, there must
910 be a __hash__. */
911 if (eqstr == NULL)
912 eqstr = PyString_InternFromString("__eq__");
913 func = instance_getattr(inst, eqstr);
914 if (func == NULL) {
915 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
916 return -1;
917 PyErr_Clear();
918 if (cmpstr == NULL)
919 cmpstr = PyString_InternFromString("__cmp__");
920 func = instance_getattr(inst, cmpstr);
921 if (func == NULL) {
922 if (!PyErr_ExceptionMatches(
923 PyExc_AttributeError))
924 return -1;
925 PyErr_Clear();
926 return _Py_HashPointer(inst);
929 Py_XDECREF(func);
930 PyErr_SetString(PyExc_TypeError, "unhashable instance");
931 return -1;
933 res = PyEval_CallObject(func, (PyObject *)NULL);
934 Py_DECREF(func);
935 if (res == NULL)
936 return -1;
937 if (PyInt_Check(res) || PyLong_Check(res))
938 /* This already converts a -1 result to -2. */
939 outcome = res->ob_type->tp_hash(res);
940 else {
941 PyErr_SetString(PyExc_TypeError,
942 "__hash__() should return an int");
943 outcome = -1;
945 Py_DECREF(res);
946 return outcome;
949 static int
950 instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
952 Py_VISIT(o->in_class);
953 Py_VISIT(o->in_dict);
954 return 0;
957 static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
958 static PyObject *iterstr, *nextstr;
960 static Py_ssize_t
961 instance_length(PyInstanceObject *inst)
963 PyObject *func;
964 PyObject *res;
965 Py_ssize_t outcome;
967 if (lenstr == NULL)
968 lenstr = PyString_InternFromString("__len__");
969 func = instance_getattr(inst, lenstr);
970 if (func == NULL)
971 return -1;
972 res = PyEval_CallObject(func, (PyObject *)NULL);
973 Py_DECREF(func);
974 if (res == NULL)
975 return -1;
976 if (PyInt_Check(res)) {
977 Py_ssize_t temp = PyInt_AsSsize_t(res);
978 if (temp == -1 && PyErr_Occurred()) {
979 Py_DECREF(res);
980 return -1;
982 outcome = (Py_ssize_t)temp;
983 #if SIZEOF_SIZE_T < SIZEOF_LONG
984 /* Overflow check -- range of PyInt is more than C int */
985 if (outcome != temp) {
986 PyErr_SetString(PyExc_OverflowError,
987 "__len__() should return 0 <= outcome < 2**31");
988 outcome = -1;
990 else
991 #endif
992 if (outcome < 0)
993 PyErr_SetString(PyExc_ValueError,
994 "__len__() should return >= 0");
996 else {
997 PyErr_SetString(PyExc_TypeError,
998 "__len__() should return an int");
999 outcome = -1;
1001 Py_DECREF(res);
1002 return outcome;
1005 static PyObject *
1006 instance_subscript(PyInstanceObject *inst, PyObject *key)
1008 PyObject *func;
1009 PyObject *arg;
1010 PyObject *res;
1012 if (getitemstr == NULL)
1013 getitemstr = PyString_InternFromString("__getitem__");
1014 func = instance_getattr(inst, getitemstr);
1015 if (func == NULL)
1016 return NULL;
1017 arg = PyTuple_Pack(1, key);
1018 if (arg == NULL) {
1019 Py_DECREF(func);
1020 return NULL;
1022 res = PyEval_CallObject(func, arg);
1023 Py_DECREF(func);
1024 Py_DECREF(arg);
1025 return res;
1028 static int
1029 instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1031 PyObject *func;
1032 PyObject *arg;
1033 PyObject *res;
1035 if (value == NULL) {
1036 if (delitemstr == NULL)
1037 delitemstr = PyString_InternFromString("__delitem__");
1038 func = instance_getattr(inst, delitemstr);
1040 else {
1041 if (setitemstr == NULL)
1042 setitemstr = PyString_InternFromString("__setitem__");
1043 func = instance_getattr(inst, setitemstr);
1045 if (func == NULL)
1046 return -1;
1047 if (value == NULL)
1048 arg = PyTuple_Pack(1, key);
1049 else
1050 arg = PyTuple_Pack(2, key, value);
1051 if (arg == NULL) {
1052 Py_DECREF(func);
1053 return -1;
1055 res = PyEval_CallObject(func, arg);
1056 Py_DECREF(func);
1057 Py_DECREF(arg);
1058 if (res == NULL)
1059 return -1;
1060 Py_DECREF(res);
1061 return 0;
1064 static PyMappingMethods instance_as_mapping = {
1065 (lenfunc)instance_length, /* mp_length */
1066 (binaryfunc)instance_subscript, /* mp_subscript */
1067 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
1070 static PyObject *
1071 instance_item(PyInstanceObject *inst, Py_ssize_t i)
1073 PyObject *func, *res;
1075 if (getitemstr == NULL)
1076 getitemstr = PyString_InternFromString("__getitem__");
1077 func = instance_getattr(inst, getitemstr);
1078 if (func == NULL)
1079 return NULL;
1080 res = PyObject_CallFunction(func, "n", i);
1081 Py_DECREF(func);
1082 return res;
1085 static PyObject *
1086 instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
1088 PyObject *func, *arg, *res;
1089 static PyObject *getslicestr;
1091 if (getslicestr == NULL)
1092 getslicestr = PyString_InternFromString("__getslice__");
1093 func = instance_getattr(inst, getslicestr);
1095 if (func == NULL) {
1096 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1097 return NULL;
1098 PyErr_Clear();
1100 if (getitemstr == NULL)
1101 getitemstr = PyString_InternFromString("__getitem__");
1102 func = instance_getattr(inst, getitemstr);
1103 if (func == NULL)
1104 return NULL;
1105 arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
1106 } else
1107 arg = Py_BuildValue("(nn)", i, j);
1109 if (arg == NULL) {
1110 Py_DECREF(func);
1111 return NULL;
1113 res = PyEval_CallObject(func, arg);
1114 Py_DECREF(func);
1115 Py_DECREF(arg);
1116 return res;
1119 static int
1120 instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
1122 PyObject *func, *arg, *res;
1124 if (item == NULL) {
1125 if (delitemstr == NULL)
1126 delitemstr = PyString_InternFromString("__delitem__");
1127 func = instance_getattr(inst, delitemstr);
1129 else {
1130 if (setitemstr == NULL)
1131 setitemstr = PyString_InternFromString("__setitem__");
1132 func = instance_getattr(inst, setitemstr);
1134 if (func == NULL)
1135 return -1;
1136 if (item == NULL)
1137 arg = PyInt_FromSsize_t(i);
1138 else
1139 arg = Py_BuildValue("(nO)", i, item);
1140 if (arg == NULL) {
1141 Py_DECREF(func);
1142 return -1;
1144 res = PyEval_CallObject(func, arg);
1145 Py_DECREF(func);
1146 Py_DECREF(arg);
1147 if (res == NULL)
1148 return -1;
1149 Py_DECREF(res);
1150 return 0;
1153 static int
1154 instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
1156 PyObject *func, *arg, *res;
1157 static PyObject *setslicestr, *delslicestr;
1159 if (value == NULL) {
1160 if (delslicestr == NULL)
1161 delslicestr =
1162 PyString_InternFromString("__delslice__");
1163 func = instance_getattr(inst, delslicestr);
1164 if (func == NULL) {
1165 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1166 return -1;
1167 PyErr_Clear();
1168 if (delitemstr == NULL)
1169 delitemstr =
1170 PyString_InternFromString("__delitem__");
1171 func = instance_getattr(inst, delitemstr);
1172 if (func == NULL)
1173 return -1;
1175 arg = Py_BuildValue("(N)",
1176 _PySlice_FromIndices(i, j));
1177 } else
1178 arg = Py_BuildValue("(nn)", i, j);
1180 else {
1181 if (setslicestr == NULL)
1182 setslicestr =
1183 PyString_InternFromString("__setslice__");
1184 func = instance_getattr(inst, setslicestr);
1185 if (func == NULL) {
1186 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1187 return -1;
1188 PyErr_Clear();
1189 if (setitemstr == NULL)
1190 setitemstr =
1191 PyString_InternFromString("__setitem__");
1192 func = instance_getattr(inst, setitemstr);
1193 if (func == NULL)
1194 return -1;
1196 arg = Py_BuildValue("(NO)",
1197 _PySlice_FromIndices(i, j), value);
1198 } else
1199 arg = Py_BuildValue("(nnO)", i, j, value);
1201 if (arg == NULL) {
1202 Py_DECREF(func);
1203 return -1;
1205 res = PyEval_CallObject(func, arg);
1206 Py_DECREF(func);
1207 Py_DECREF(arg);
1208 if (res == NULL)
1209 return -1;
1210 Py_DECREF(res);
1211 return 0;
1214 static int
1215 instance_contains(PyInstanceObject *inst, PyObject *member)
1217 static PyObject *__contains__;
1218 PyObject *func;
1220 /* Try __contains__ first.
1221 * If that can't be done, try iterator-based searching.
1224 if(__contains__ == NULL) {
1225 __contains__ = PyString_InternFromString("__contains__");
1226 if(__contains__ == NULL)
1227 return -1;
1229 func = instance_getattr(inst, __contains__);
1230 if (func) {
1231 PyObject *res;
1232 int ret;
1233 PyObject *arg = PyTuple_Pack(1, member);
1234 if(arg == NULL) {
1235 Py_DECREF(func);
1236 return -1;
1238 res = PyEval_CallObject(func, arg);
1239 Py_DECREF(func);
1240 Py_DECREF(arg);
1241 if(res == NULL)
1242 return -1;
1243 ret = PyObject_IsTrue(res);
1244 Py_DECREF(res);
1245 return ret;
1248 /* Couldn't find __contains__. */
1249 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1250 /* Assume the failure was simply due to that there is no
1251 * __contains__ attribute, and try iterating instead.
1253 PyErr_Clear();
1254 return _PySequence_IterSearch((PyObject *)inst, member,
1255 PY_ITERSEARCH_CONTAINS) > 0;
1257 else
1258 return -1;
1261 static PySequenceMethods
1262 instance_as_sequence = {
1263 (lenfunc)instance_length, /* sq_length */
1264 0, /* sq_concat */
1265 0, /* sq_repeat */
1266 (ssizeargfunc)instance_item, /* sq_item */
1267 (ssizessizeargfunc)instance_slice, /* sq_slice */
1268 (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
1269 (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1270 (objobjproc)instance_contains, /* sq_contains */
1273 static PyObject *
1274 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1276 PyObject *func, *res;
1278 if ((func = instance_getattr(self, methodname)) == NULL)
1279 return NULL;
1280 res = PyEval_CallObject(func, (PyObject *)NULL);
1281 Py_DECREF(func);
1282 return res;
1285 static PyObject *
1286 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1288 PyObject *result;
1289 PyObject *args;
1290 PyObject *func = PyObject_GetAttrString(v, opname);
1291 if (func == NULL) {
1292 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1293 return NULL;
1294 PyErr_Clear();
1295 Py_INCREF(Py_NotImplemented);
1296 return Py_NotImplemented;
1298 args = PyTuple_Pack(1, w);
1299 if (args == NULL) {
1300 Py_DECREF(func);
1301 return NULL;
1303 result = PyEval_CallObject(func, args);
1304 Py_DECREF(args);
1305 Py_DECREF(func);
1306 return result;
1310 static PyObject *coerce_obj;
1312 /* Try one half of a binary operator involving a class instance. */
1313 static PyObject *
1314 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1315 int swapped)
1317 PyObject *args;
1318 PyObject *coercefunc;
1319 PyObject *coerced = NULL;
1320 PyObject *v1;
1321 PyObject *result;
1323 if (!PyInstance_Check(v)) {
1324 Py_INCREF(Py_NotImplemented);
1325 return Py_NotImplemented;
1328 if (coerce_obj == NULL) {
1329 coerce_obj = PyString_InternFromString("__coerce__");
1330 if (coerce_obj == NULL)
1331 return NULL;
1333 coercefunc = PyObject_GetAttr(v, coerce_obj);
1334 if (coercefunc == NULL) {
1335 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1336 return NULL;
1337 PyErr_Clear();
1338 return generic_binary_op(v, w, opname);
1341 args = PyTuple_Pack(1, w);
1342 if (args == NULL) {
1343 Py_DECREF(coercefunc);
1344 return NULL;
1346 coerced = PyEval_CallObject(coercefunc, args);
1347 Py_DECREF(args);
1348 Py_DECREF(coercefunc);
1349 if (coerced == NULL) {
1350 return NULL;
1352 if (coerced == Py_None || coerced == Py_NotImplemented) {
1353 Py_DECREF(coerced);
1354 return generic_binary_op(v, w, opname);
1356 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1357 Py_DECREF(coerced);
1358 PyErr_SetString(PyExc_TypeError,
1359 "coercion should return None or 2-tuple");
1360 return NULL;
1362 v1 = PyTuple_GetItem(coerced, 0);
1363 w = PyTuple_GetItem(coerced, 1);
1364 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1365 /* prevent recursion if __coerce__ returns self as the first
1366 * argument */
1367 result = generic_binary_op(v1, w, opname);
1368 } else {
1369 if (Py_EnterRecursiveCall(" after coercion"))
1370 return NULL;
1371 if (swapped)
1372 result = (thisfunc)(w, v1);
1373 else
1374 result = (thisfunc)(v1, w);
1375 Py_LeaveRecursiveCall();
1377 Py_DECREF(coerced);
1378 return result;
1381 /* Implement a binary operator involving at least one class instance. */
1382 static PyObject *
1383 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1384 binaryfunc thisfunc)
1386 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1387 if (result == Py_NotImplemented) {
1388 Py_DECREF(result);
1389 result = half_binop(w, v, ropname, thisfunc, 1);
1391 return result;
1394 static PyObject *
1395 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1396 char *ropname, binaryfunc thisfunc)
1398 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1399 if (result == Py_NotImplemented) {
1400 Py_DECREF(result);
1401 result = do_binop(v, w, opname, ropname, thisfunc);
1403 return result;
1406 static int
1407 instance_coerce(PyObject **pv, PyObject **pw)
1409 PyObject *v = *pv;
1410 PyObject *w = *pw;
1411 PyObject *coercefunc;
1412 PyObject *args;
1413 PyObject *coerced;
1415 if (coerce_obj == NULL) {
1416 coerce_obj = PyString_InternFromString("__coerce__");
1417 if (coerce_obj == NULL)
1418 return -1;
1420 coercefunc = PyObject_GetAttr(v, coerce_obj);
1421 if (coercefunc == NULL) {
1422 /* No __coerce__ method */
1423 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1424 return -1;
1425 PyErr_Clear();
1426 return 1;
1428 /* Has __coerce__ method: call it */
1429 args = PyTuple_Pack(1, w);
1430 if (args == NULL) {
1431 return -1;
1433 coerced = PyEval_CallObject(coercefunc, args);
1434 Py_DECREF(args);
1435 Py_DECREF(coercefunc);
1436 if (coerced == NULL) {
1437 /* __coerce__ call raised an exception */
1438 return -1;
1440 if (coerced == Py_None || coerced == Py_NotImplemented) {
1441 /* __coerce__ says "I can't do it" */
1442 Py_DECREF(coerced);
1443 return 1;
1445 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1446 /* __coerce__ return value is malformed */
1447 Py_DECREF(coerced);
1448 PyErr_SetString(PyExc_TypeError,
1449 "coercion should return None or 2-tuple");
1450 return -1;
1452 /* __coerce__ returned two new values */
1453 *pv = PyTuple_GetItem(coerced, 0);
1454 *pw = PyTuple_GetItem(coerced, 1);
1455 Py_INCREF(*pv);
1456 Py_INCREF(*pw);
1457 Py_DECREF(coerced);
1458 return 0;
1461 #define UNARY(funcname, methodname) \
1462 static PyObject *funcname(PyInstanceObject *self) { \
1463 static PyObject *o; \
1464 if (o == NULL) o = PyString_InternFromString(methodname); \
1465 return generic_unary_op(self, o); \
1468 #define BINARY(f, m, n) \
1469 static PyObject *f(PyObject *v, PyObject *w) { \
1470 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1473 #define BINARY_INPLACE(f, m, n) \
1474 static PyObject *f(PyObject *v, PyObject *w) { \
1475 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1476 "__r" m "__", n); \
1479 UNARY(instance_neg, "__neg__")
1480 UNARY(instance_pos, "__pos__")
1481 UNARY(instance_abs, "__abs__")
1483 BINARY(instance_or, "or", PyNumber_Or)
1484 BINARY(instance_and, "and", PyNumber_And)
1485 BINARY(instance_xor, "xor", PyNumber_Xor)
1486 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1487 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1488 BINARY(instance_add, "add", PyNumber_Add)
1489 BINARY(instance_sub, "sub", PyNumber_Subtract)
1490 BINARY(instance_mul, "mul", PyNumber_Multiply)
1491 BINARY(instance_div, "div", PyNumber_Divide)
1492 BINARY(instance_mod, "mod", PyNumber_Remainder)
1493 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1494 BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1495 BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1497 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1498 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1499 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1500 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1501 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1502 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1503 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1504 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1505 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1506 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1507 BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1508 BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1510 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1511 -2 for an exception;
1512 -1 if v < w;
1513 0 if v == w;
1514 1 if v > w;
1515 2 if this particular 3-way comparison is not implemented or undefined.
1517 static int
1518 half_cmp(PyObject *v, PyObject *w)
1520 static PyObject *cmp_obj;
1521 PyObject *args;
1522 PyObject *cmp_func;
1523 PyObject *result;
1524 long l;
1526 assert(PyInstance_Check(v));
1528 if (cmp_obj == NULL) {
1529 cmp_obj = PyString_InternFromString("__cmp__");
1530 if (cmp_obj == NULL)
1531 return -2;
1534 cmp_func = PyObject_GetAttr(v, cmp_obj);
1535 if (cmp_func == NULL) {
1536 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1537 return -2;
1538 PyErr_Clear();
1539 return 2;
1542 args = PyTuple_Pack(1, w);
1543 if (args == NULL) {
1544 Py_DECREF(cmp_func);
1545 return -2;
1548 result = PyEval_CallObject(cmp_func, args);
1549 Py_DECREF(args);
1550 Py_DECREF(cmp_func);
1552 if (result == NULL)
1553 return -2;
1555 if (result == Py_NotImplemented) {
1556 Py_DECREF(result);
1557 return 2;
1560 l = PyInt_AsLong(result);
1561 Py_DECREF(result);
1562 if (l == -1 && PyErr_Occurred()) {
1563 PyErr_SetString(PyExc_TypeError,
1564 "comparison did not return an int");
1565 return -2;
1568 return l < 0 ? -1 : l > 0 ? 1 : 0;
1571 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1572 We first try a coercion. Return:
1573 -2 for an exception;
1574 -1 if v < w;
1575 0 if v == w;
1576 1 if v > w;
1577 2 if this particular 3-way comparison is not implemented or undefined.
1578 THIS IS ONLY CALLED FROM object.c!
1580 static int
1581 instance_compare(PyObject *v, PyObject *w)
1583 int c;
1585 c = PyNumber_CoerceEx(&v, &w);
1586 if (c < 0)
1587 return -2;
1588 if (c == 0) {
1589 /* If neither is now an instance, use regular comparison */
1590 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1591 c = PyObject_Compare(v, w);
1592 Py_DECREF(v);
1593 Py_DECREF(w);
1594 if (PyErr_Occurred())
1595 return -2;
1596 return c < 0 ? -1 : c > 0 ? 1 : 0;
1599 else {
1600 /* The coercion didn't do anything.
1601 Treat this the same as returning v and w unchanged. */
1602 Py_INCREF(v);
1603 Py_INCREF(w);
1606 if (PyInstance_Check(v)) {
1607 c = half_cmp(v, w);
1608 if (c <= 1) {
1609 Py_DECREF(v);
1610 Py_DECREF(w);
1611 return c;
1614 if (PyInstance_Check(w)) {
1615 c = half_cmp(w, v);
1616 if (c <= 1) {
1617 Py_DECREF(v);
1618 Py_DECREF(w);
1619 if (c >= -1)
1620 c = -c;
1621 return c;
1624 Py_DECREF(v);
1625 Py_DECREF(w);
1626 return 2;
1629 static int
1630 instance_nonzero(PyInstanceObject *self)
1632 PyObject *func, *res;
1633 long outcome;
1634 static PyObject *nonzerostr;
1636 if (nonzerostr == NULL)
1637 nonzerostr = PyString_InternFromString("__nonzero__");
1638 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1639 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1640 return -1;
1641 PyErr_Clear();
1642 if (lenstr == NULL)
1643 lenstr = PyString_InternFromString("__len__");
1644 if ((func = instance_getattr(self, lenstr)) == NULL) {
1645 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1646 return -1;
1647 PyErr_Clear();
1648 /* Fall back to the default behavior:
1649 all instances are nonzero */
1650 return 1;
1653 res = PyEval_CallObject(func, (PyObject *)NULL);
1654 Py_DECREF(func);
1655 if (res == NULL)
1656 return -1;
1657 if (!PyInt_Check(res)) {
1658 Py_DECREF(res);
1659 PyErr_SetString(PyExc_TypeError,
1660 "__nonzero__ should return an int");
1661 return -1;
1663 outcome = PyInt_AsLong(res);
1664 Py_DECREF(res);
1665 if (outcome < 0) {
1666 PyErr_SetString(PyExc_ValueError,
1667 "__nonzero__ should return >= 0");
1668 return -1;
1670 return outcome > 0;
1673 static Py_ssize_t
1674 instance_index(PyInstanceObject *self)
1676 PyObject *func, *res;
1677 Py_ssize_t outcome;
1678 static PyObject *indexstr = NULL;
1680 if (indexstr == NULL) {
1681 indexstr = PyString_InternFromString("__index__");
1682 if (indexstr == NULL)
1683 return -1;
1685 if ((func = instance_getattr(self, indexstr)) == NULL) {
1686 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1687 return -1;
1688 PyErr_Clear();
1689 PyErr_SetString(PyExc_TypeError,
1690 "object cannot be interpreted as an index");
1691 return -1;
1693 res = PyEval_CallObject(func, (PyObject *)NULL);
1694 Py_DECREF(func);
1695 if (res == NULL)
1696 return -1;
1697 if (PyInt_Check(res) || PyLong_Check(res)) {
1698 outcome = res->ob_type->tp_as_number->nb_index(res);
1700 else {
1701 PyErr_SetString(PyExc_TypeError,
1702 "__index__ must return an int or a long");
1703 outcome = -1;
1705 Py_DECREF(res);
1706 return outcome;
1710 UNARY(instance_invert, "__invert__")
1711 UNARY(instance_int, "__int__")
1712 UNARY(instance_long, "__long__")
1713 UNARY(instance_float, "__float__")
1714 UNARY(instance_oct, "__oct__")
1715 UNARY(instance_hex, "__hex__")
1717 static PyObject *
1718 bin_power(PyObject *v, PyObject *w)
1720 return PyNumber_Power(v, w, Py_None);
1723 /* This version is for ternary calls only (z != None) */
1724 static PyObject *
1725 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1727 if (z == Py_None) {
1728 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1730 else {
1731 PyObject *func;
1732 PyObject *args;
1733 PyObject *result;
1735 /* XXX Doesn't do coercions... */
1736 func = PyObject_GetAttrString(v, "__pow__");
1737 if (func == NULL)
1738 return NULL;
1739 args = PyTuple_Pack(2, w, z);
1740 if (args == NULL) {
1741 Py_DECREF(func);
1742 return NULL;
1744 result = PyEval_CallObject(func, args);
1745 Py_DECREF(func);
1746 Py_DECREF(args);
1747 return result;
1751 static PyObject *
1752 bin_inplace_power(PyObject *v, PyObject *w)
1754 return PyNumber_InPlacePower(v, w, Py_None);
1758 static PyObject *
1759 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1761 if (z == Py_None) {
1762 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1763 "__rpow__", bin_inplace_power);
1765 else {
1766 /* XXX Doesn't do coercions... */
1767 PyObject *func;
1768 PyObject *args;
1769 PyObject *result;
1771 func = PyObject_GetAttrString(v, "__ipow__");
1772 if (func == NULL) {
1773 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1774 return NULL;
1775 PyErr_Clear();
1776 return instance_pow(v, w, z);
1778 args = PyTuple_Pack(2, w, z);
1779 if (args == NULL) {
1780 Py_DECREF(func);
1781 return NULL;
1783 result = PyEval_CallObject(func, args);
1784 Py_DECREF(func);
1785 Py_DECREF(args);
1786 return result;
1791 /* Map rich comparison operators to their __xx__ namesakes */
1792 #define NAME_OPS 6
1793 static PyObject **name_op = NULL;
1795 static int
1796 init_name_op(void)
1798 int i;
1799 char *_name_op[] = {
1800 "__lt__",
1801 "__le__",
1802 "__eq__",
1803 "__ne__",
1804 "__gt__",
1805 "__ge__",
1808 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1809 if (name_op == NULL)
1810 return -1;
1811 for (i = 0; i < NAME_OPS; ++i) {
1812 name_op[i] = PyString_InternFromString(_name_op[i]);
1813 if (name_op[i] == NULL)
1814 return -1;
1816 return 0;
1819 static PyObject *
1820 half_richcompare(PyObject *v, PyObject *w, int op)
1822 PyObject *method;
1823 PyObject *args;
1824 PyObject *res;
1826 assert(PyInstance_Check(v));
1828 if (name_op == NULL) {
1829 if (init_name_op() < 0)
1830 return NULL;
1832 /* If the instance doesn't define an __getattr__ method, use
1833 instance_getattr2 directly because it will not set an
1834 exception on failure. */
1835 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1836 method = instance_getattr2((PyInstanceObject *)v,
1837 name_op[op]);
1838 else
1839 method = PyObject_GetAttr(v, name_op[op]);
1840 if (method == NULL) {
1841 if (PyErr_Occurred()) {
1842 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1843 return NULL;
1844 PyErr_Clear();
1846 res = Py_NotImplemented;
1847 Py_INCREF(res);
1848 return res;
1851 args = PyTuple_Pack(1, w);
1852 if (args == NULL) {
1853 Py_DECREF(method);
1854 return NULL;
1857 res = PyEval_CallObject(method, args);
1858 Py_DECREF(args);
1859 Py_DECREF(method);
1861 return res;
1864 static PyObject *
1865 instance_richcompare(PyObject *v, PyObject *w, int op)
1867 PyObject *res;
1869 if (PyInstance_Check(v)) {
1870 res = half_richcompare(v, w, op);
1871 if (res != Py_NotImplemented)
1872 return res;
1873 Py_DECREF(res);
1876 if (PyInstance_Check(w)) {
1877 res = half_richcompare(w, v, _Py_SwappedOp[op]);
1878 if (res != Py_NotImplemented)
1879 return res;
1880 Py_DECREF(res);
1883 Py_INCREF(Py_NotImplemented);
1884 return Py_NotImplemented;
1888 /* Get the iterator */
1889 static PyObject *
1890 instance_getiter(PyInstanceObject *self)
1892 PyObject *func;
1894 if (iterstr == NULL) {
1895 iterstr = PyString_InternFromString("__iter__");
1896 if (iterstr == NULL)
1897 return NULL;
1899 if (getitemstr == NULL) {
1900 getitemstr = PyString_InternFromString("__getitem__");
1901 if (getitemstr == NULL)
1902 return NULL;
1905 if ((func = instance_getattr(self, iterstr)) != NULL) {
1906 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1907 Py_DECREF(func);
1908 if (res != NULL && !PyIter_Check(res)) {
1909 PyErr_Format(PyExc_TypeError,
1910 "__iter__ returned non-iterator "
1911 "of type '%.100s'",
1912 res->ob_type->tp_name);
1913 Py_DECREF(res);
1914 res = NULL;
1916 return res;
1918 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1919 return NULL;
1920 PyErr_Clear();
1921 if ((func = instance_getattr(self, getitemstr)) == NULL) {
1922 PyErr_SetString(PyExc_TypeError,
1923 "iteration over non-sequence");
1924 return NULL;
1926 Py_DECREF(func);
1927 return PySeqIter_New((PyObject *)self);
1931 /* Call the iterator's next */
1932 static PyObject *
1933 instance_iternext(PyInstanceObject *self)
1935 PyObject *func;
1937 if (nextstr == NULL)
1938 nextstr = PyString_InternFromString("next");
1940 if ((func = instance_getattr(self, nextstr)) != NULL) {
1941 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1942 Py_DECREF(func);
1943 if (res != NULL) {
1944 return res;
1946 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
1947 PyErr_Clear();
1948 return NULL;
1950 return NULL;
1952 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
1953 return NULL;
1956 static PyObject *
1957 instance_call(PyObject *func, PyObject *arg, PyObject *kw)
1959 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
1960 if (call == NULL) {
1961 PyInstanceObject *inst = (PyInstanceObject*) func;
1962 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1963 return NULL;
1964 PyErr_Clear();
1965 PyErr_Format(PyExc_AttributeError,
1966 "%.200s instance has no __call__ method",
1967 PyString_AsString(inst->in_class->cl_name));
1968 return NULL;
1970 /* We must check and increment the recursion depth here. Scenario:
1971 class A:
1972 pass
1973 A.__call__ = A() # that's right
1974 a = A() # ok
1975 a() # infinite recursion
1976 This bounces between instance_call() and PyObject_Call() without
1977 ever hitting eval_frame() (which has the main recursion check). */
1978 if (Py_EnterRecursiveCall(" in __call__")) {
1979 res = NULL;
1981 else {
1982 res = PyObject_Call(call, arg, kw);
1983 Py_LeaveRecursiveCall();
1985 Py_DECREF(call);
1986 return res;
1990 static PyNumberMethods instance_as_number = {
1991 instance_add, /* nb_add */
1992 instance_sub, /* nb_subtract */
1993 instance_mul, /* nb_multiply */
1994 instance_div, /* nb_divide */
1995 instance_mod, /* nb_remainder */
1996 instance_divmod, /* nb_divmod */
1997 instance_pow, /* nb_power */
1998 (unaryfunc)instance_neg, /* nb_negative */
1999 (unaryfunc)instance_pos, /* nb_positive */
2000 (unaryfunc)instance_abs, /* nb_absolute */
2001 (inquiry)instance_nonzero, /* nb_nonzero */
2002 (unaryfunc)instance_invert, /* nb_invert */
2003 instance_lshift, /* nb_lshift */
2004 instance_rshift, /* nb_rshift */
2005 instance_and, /* nb_and */
2006 instance_xor, /* nb_xor */
2007 instance_or, /* nb_or */
2008 instance_coerce, /* nb_coerce */
2009 (unaryfunc)instance_int, /* nb_int */
2010 (unaryfunc)instance_long, /* nb_long */
2011 (unaryfunc)instance_float, /* nb_float */
2012 (unaryfunc)instance_oct, /* nb_oct */
2013 (unaryfunc)instance_hex, /* nb_hex */
2014 instance_iadd, /* nb_inplace_add */
2015 instance_isub, /* nb_inplace_subtract */
2016 instance_imul, /* nb_inplace_multiply */
2017 instance_idiv, /* nb_inplace_divide */
2018 instance_imod, /* nb_inplace_remainder */
2019 instance_ipow, /* nb_inplace_power */
2020 instance_ilshift, /* nb_inplace_lshift */
2021 instance_irshift, /* nb_inplace_rshift */
2022 instance_iand, /* nb_inplace_and */
2023 instance_ixor, /* nb_inplace_xor */
2024 instance_ior, /* nb_inplace_or */
2025 instance_floordiv, /* nb_floor_divide */
2026 instance_truediv, /* nb_true_divide */
2027 instance_ifloordiv, /* nb_inplace_floor_divide */
2028 instance_itruediv, /* nb_inplace_true_divide */
2029 (lenfunc)instance_index, /* nb_index */
2032 PyTypeObject PyInstance_Type = {
2033 PyObject_HEAD_INIT(&PyType_Type)
2035 "instance",
2036 sizeof(PyInstanceObject),
2038 (destructor)instance_dealloc, /* tp_dealloc */
2039 0, /* tp_print */
2040 0, /* tp_getattr */
2041 0, /* tp_setattr */
2042 instance_compare, /* tp_compare */
2043 (reprfunc)instance_repr, /* tp_repr */
2044 &instance_as_number, /* tp_as_number */
2045 &instance_as_sequence, /* tp_as_sequence */
2046 &instance_as_mapping, /* tp_as_mapping */
2047 (hashfunc)instance_hash, /* tp_hash */
2048 instance_call, /* tp_call */
2049 (reprfunc)instance_str, /* tp_str */
2050 (getattrofunc)instance_getattr, /* tp_getattro */
2051 (setattrofunc)instance_setattr, /* tp_setattro */
2052 0, /* tp_as_buffer */
2053 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2054 instance_doc, /* tp_doc */
2055 (traverseproc)instance_traverse, /* tp_traverse */
2056 0, /* tp_clear */
2057 instance_richcompare, /* tp_richcompare */
2058 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2059 (getiterfunc)instance_getiter, /* tp_iter */
2060 (iternextfunc)instance_iternext, /* tp_iternext */
2061 0, /* tp_methods */
2062 0, /* tp_members */
2063 0, /* tp_getset */
2064 0, /* tp_base */
2065 0, /* tp_dict */
2066 0, /* tp_descr_get */
2067 0, /* tp_descr_set */
2068 0, /* tp_dictoffset */
2069 0, /* tp_init */
2070 0, /* tp_alloc */
2071 instance_new, /* tp_new */
2075 /* Instance method objects are used for two purposes:
2076 (a) as bound instance methods (returned by instancename.methodname)
2077 (b) as unbound methods (returned by ClassName.methodname)
2078 In case (b), im_self is NULL
2081 static PyMethodObject *free_list;
2083 PyObject *
2084 PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
2086 register PyMethodObject *im;
2087 if (!PyCallable_Check(func)) {
2088 PyErr_BadInternalCall();
2089 return NULL;
2091 im = free_list;
2092 if (im != NULL) {
2093 free_list = (PyMethodObject *)(im->im_self);
2094 PyObject_INIT(im, &PyMethod_Type);
2096 else {
2097 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2098 if (im == NULL)
2099 return NULL;
2101 im->im_weakreflist = NULL;
2102 Py_INCREF(func);
2103 im->im_func = func;
2104 Py_XINCREF(self);
2105 im->im_self = self;
2106 Py_XINCREF(klass);
2107 im->im_class = klass;
2108 _PyObject_GC_TRACK(im);
2109 return (PyObject *)im;
2112 /* Descriptors for PyMethod attributes */
2114 /* im_class, im_func and im_self are stored in the PyMethod object */
2116 #define OFF(x) offsetof(PyMethodObject, x)
2118 static PyMemberDef instancemethod_memberlist[] = {
2119 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2120 "the class associated with a method"},
2121 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2122 "the function (or other callable) implementing a method"},
2123 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2124 "the instance to which a method is bound; None for unbound methods"},
2125 {NULL} /* Sentinel */
2128 /* Christian Tismer argued convincingly that method attributes should
2129 (nearly) always override function attributes.
2130 The one exception is __doc__; there's a default __doc__ which
2131 should only be used for the class, not for instances */
2133 static PyObject *
2134 instancemethod_get_doc(PyMethodObject *im, void *context)
2136 static PyObject *docstr;
2137 if (docstr == NULL) {
2138 docstr= PyString_InternFromString("__doc__");
2139 if (docstr == NULL)
2140 return NULL;
2142 return PyObject_GetAttr(im->im_func, docstr);
2145 static PyGetSetDef instancemethod_getset[] = {
2146 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2150 static PyObject *
2151 instancemethod_getattro(PyObject *obj, PyObject *name)
2153 PyMethodObject *im = (PyMethodObject *)obj;
2154 PyTypeObject *tp = obj->ob_type;
2155 PyObject *descr = NULL;
2157 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2158 if (tp->tp_dict == NULL) {
2159 if (PyType_Ready(tp) < 0)
2160 return NULL;
2162 descr = _PyType_Lookup(tp, name);
2165 if (descr != NULL) {
2166 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
2167 if (f != NULL)
2168 return f(descr, obj, (PyObject *)obj->ob_type);
2169 else {
2170 Py_INCREF(descr);
2171 return descr;
2175 return PyObject_GetAttr(im->im_func, name);
2178 PyDoc_STRVAR(instancemethod_doc,
2179 "instancemethod(function, instance, class)\n\
2181 Create an instance method object.");
2183 static PyObject *
2184 instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2186 PyObject *func;
2187 PyObject *self;
2188 PyObject *classObj = NULL;
2190 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2191 &func, &self, &classObj))
2192 return NULL;
2193 if (!PyCallable_Check(func)) {
2194 PyErr_SetString(PyExc_TypeError,
2195 "first argument must be callable");
2196 return NULL;
2198 if (self == Py_None)
2199 self = NULL;
2200 if (self == NULL && classObj == NULL) {
2201 PyErr_SetString(PyExc_TypeError,
2202 "unbound methods must have non-NULL im_class");
2203 return NULL;
2206 return PyMethod_New(func, self, classObj);
2209 static void
2210 instancemethod_dealloc(register PyMethodObject *im)
2212 _PyObject_GC_UNTRACK(im);
2213 if (im->im_weakreflist != NULL)
2214 PyObject_ClearWeakRefs((PyObject *)im);
2215 Py_DECREF(im->im_func);
2216 Py_XDECREF(im->im_self);
2217 Py_XDECREF(im->im_class);
2218 im->im_self = (PyObject *)free_list;
2219 free_list = im;
2222 static int
2223 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2225 int cmp;
2226 cmp = PyObject_Compare(a->im_func, b->im_func);
2227 if (cmp)
2228 return cmp;
2230 if (a->im_self == b->im_self)
2231 return 0;
2232 if (a->im_self == NULL || b->im_self == NULL)
2233 return (a->im_self < b->im_self) ? -1 : 1;
2234 else
2235 return PyObject_Compare(a->im_self, b->im_self);
2238 static PyObject *
2239 instancemethod_repr(PyMethodObject *a)
2241 PyObject *self = a->im_self;
2242 PyObject *func = a->im_func;
2243 PyObject *klass = a->im_class;
2244 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2245 char *sfuncname = "?", *sklassname = "?";
2247 funcname = PyObject_GetAttrString(func, "__name__");
2248 if (funcname == NULL) {
2249 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2250 return NULL;
2251 PyErr_Clear();
2253 else if (!PyString_Check(funcname)) {
2254 Py_DECREF(funcname);
2255 funcname = NULL;
2257 else
2258 sfuncname = PyString_AS_STRING(funcname);
2259 if (klass == NULL)
2260 klassname = NULL;
2261 else {
2262 klassname = PyObject_GetAttrString(klass, "__name__");
2263 if (klassname == NULL) {
2264 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2265 return NULL;
2266 PyErr_Clear();
2268 else if (!PyString_Check(klassname)) {
2269 Py_DECREF(klassname);
2270 klassname = NULL;
2272 else
2273 sklassname = PyString_AS_STRING(klassname);
2275 if (self == NULL)
2276 result = PyString_FromFormat("<unbound method %s.%s>",
2277 sklassname, sfuncname);
2278 else {
2279 /* XXX Shouldn't use repr() here! */
2280 PyObject *selfrepr = PyObject_Repr(self);
2281 if (selfrepr == NULL)
2282 goto fail;
2283 if (!PyString_Check(selfrepr)) {
2284 Py_DECREF(selfrepr);
2285 goto fail;
2287 result = PyString_FromFormat("<bound method %s.%s of %s>",
2288 sklassname, sfuncname,
2289 PyString_AS_STRING(selfrepr));
2290 Py_DECREF(selfrepr);
2292 fail:
2293 Py_XDECREF(funcname);
2294 Py_XDECREF(klassname);
2295 return result;
2298 static long
2299 instancemethod_hash(PyMethodObject *a)
2301 long x, y;
2302 if (a->im_self == NULL)
2303 x = PyObject_Hash(Py_None);
2304 else
2305 x = PyObject_Hash(a->im_self);
2306 if (x == -1)
2307 return -1;
2308 y = PyObject_Hash(a->im_func);
2309 if (y == -1)
2310 return -1;
2311 x = x ^ y;
2312 if (x == -1)
2313 x = -2;
2314 return x;
2317 static int
2318 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2320 Py_VISIT(im->im_func);
2321 Py_VISIT(im->im_self);
2322 Py_VISIT(im->im_class);
2323 return 0;
2326 static void
2327 getclassname(PyObject *klass, char *buf, int bufsize)
2329 PyObject *name;
2331 assert(bufsize > 1);
2332 strcpy(buf, "?"); /* Default outcome */
2333 if (klass == NULL)
2334 return;
2335 name = PyObject_GetAttrString(klass, "__name__");
2336 if (name == NULL) {
2337 /* This function cannot return an exception */
2338 PyErr_Clear();
2339 return;
2341 if (PyString_Check(name)) {
2342 strncpy(buf, PyString_AS_STRING(name), bufsize);
2343 buf[bufsize-1] = '\0';
2345 Py_DECREF(name);
2348 static void
2349 getinstclassname(PyObject *inst, char *buf, int bufsize)
2351 PyObject *klass;
2353 if (inst == NULL) {
2354 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2355 strcpy(buf, "nothing");
2356 return;
2359 klass = PyObject_GetAttrString(inst, "__class__");
2360 if (klass == NULL) {
2361 /* This function cannot return an exception */
2362 PyErr_Clear();
2363 klass = (PyObject *)(inst->ob_type);
2364 Py_INCREF(klass);
2366 getclassname(klass, buf, bufsize);
2367 Py_XDECREF(klass);
2370 static PyObject *
2371 instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2373 PyObject *self = PyMethod_GET_SELF(func);
2374 PyObject *klass = PyMethod_GET_CLASS(func);
2375 PyObject *result;
2377 func = PyMethod_GET_FUNCTION(func);
2378 if (self == NULL) {
2379 /* Unbound methods must be called with an instance of
2380 the class (or a derived class) as first argument */
2381 int ok;
2382 if (PyTuple_Size(arg) >= 1)
2383 self = PyTuple_GET_ITEM(arg, 0);
2384 if (self == NULL)
2385 ok = 0;
2386 else {
2387 ok = PyObject_IsInstance(self, klass);
2388 if (ok < 0)
2389 return NULL;
2391 if (!ok) {
2392 char clsbuf[256];
2393 char instbuf[256];
2394 getclassname(klass, clsbuf, sizeof(clsbuf));
2395 getinstclassname(self, instbuf, sizeof(instbuf));
2396 PyErr_Format(PyExc_TypeError,
2397 "unbound method %s%s must be called with "
2398 "%s instance as first argument "
2399 "(got %s%s instead)",
2400 PyEval_GetFuncName(func),
2401 PyEval_GetFuncDesc(func),
2402 clsbuf,
2403 instbuf,
2404 self == NULL ? "" : " instance");
2405 return NULL;
2407 Py_INCREF(arg);
2409 else {
2410 Py_ssize_t argcount = PyTuple_Size(arg);
2411 PyObject *newarg = PyTuple_New(argcount + 1);
2412 int i;
2413 if (newarg == NULL)
2414 return NULL;
2415 Py_INCREF(self);
2416 PyTuple_SET_ITEM(newarg, 0, self);
2417 for (i = 0; i < argcount; i++) {
2418 PyObject *v = PyTuple_GET_ITEM(arg, i);
2419 Py_XINCREF(v);
2420 PyTuple_SET_ITEM(newarg, i+1, v);
2422 arg = newarg;
2424 result = PyObject_Call((PyObject *)func, arg, kw);
2425 Py_DECREF(arg);
2426 return result;
2429 static PyObject *
2430 instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
2432 /* Don't rebind an already bound method, or an unbound method
2433 of a class that's not a base class of cls. */
2435 if (PyMethod_GET_SELF(meth) != NULL) {
2436 /* Already bound */
2437 Py_INCREF(meth);
2438 return meth;
2440 /* No, it is an unbound method */
2441 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2442 /* Do subclass test. If it fails, return meth unchanged. */
2443 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2444 if (ok < 0)
2445 return NULL;
2446 if (!ok) {
2447 Py_INCREF(meth);
2448 return meth;
2451 /* Bind it to obj */
2452 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
2455 PyTypeObject PyMethod_Type = {
2456 PyObject_HEAD_INIT(&PyType_Type)
2458 "instancemethod",
2459 sizeof(PyMethodObject),
2461 (destructor)instancemethod_dealloc, /* tp_dealloc */
2462 0, /* tp_print */
2463 0, /* tp_getattr */
2464 0, /* tp_setattr */
2465 (cmpfunc)instancemethod_compare, /* tp_compare */
2466 (reprfunc)instancemethod_repr, /* tp_repr */
2467 0, /* tp_as_number */
2468 0, /* tp_as_sequence */
2469 0, /* tp_as_mapping */
2470 (hashfunc)instancemethod_hash, /* tp_hash */
2471 instancemethod_call, /* tp_call */
2472 0, /* tp_str */
2473 instancemethod_getattro, /* tp_getattro */
2474 PyObject_GenericSetAttr, /* tp_setattro */
2475 0, /* tp_as_buffer */
2476 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2477 instancemethod_doc, /* tp_doc */
2478 (traverseproc)instancemethod_traverse, /* tp_traverse */
2479 0, /* tp_clear */
2480 0, /* tp_richcompare */
2481 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2482 0, /* tp_iter */
2483 0, /* tp_iternext */
2484 0, /* tp_methods */
2485 instancemethod_memberlist, /* tp_members */
2486 instancemethod_getset, /* tp_getset */
2487 0, /* tp_base */
2488 0, /* tp_dict */
2489 instancemethod_descr_get, /* tp_descr_get */
2490 0, /* tp_descr_set */
2491 0, /* tp_dictoffset */
2492 0, /* tp_init */
2493 0, /* tp_alloc */
2494 instancemethod_new, /* tp_new */
2497 /* Clear out the free list */
2499 void
2500 PyMethod_Fini(void)
2502 while (free_list) {
2503 PyMethodObject *im = free_list;
2504 free_list = (PyMethodObject *)(im->im_self);
2505 PyObject_GC_Del(im);