Added duplicate call to fileConfig() to ensure that it cleans up after itself correctly.
[python.git] / Objects / classobject.c
blobc69ba744e62f62d736cc5a62ee5b64589daaa59e
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)) {
938 outcome = PyInt_AsLong(res);
939 if (outcome == -1)
940 outcome = -2;
942 else {
943 PyErr_SetString(PyExc_TypeError,
944 "__hash__() should return an int");
945 outcome = -1;
947 Py_DECREF(res);
948 return outcome;
951 static int
952 instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
954 Py_VISIT(o->in_class);
955 Py_VISIT(o->in_dict);
956 return 0;
959 static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
960 static PyObject *iterstr, *nextstr;
962 static Py_ssize_t
963 instance_length(PyInstanceObject *inst)
965 PyObject *func;
966 PyObject *res;
967 Py_ssize_t outcome;
969 if (lenstr == NULL)
970 lenstr = PyString_InternFromString("__len__");
971 func = instance_getattr(inst, lenstr);
972 if (func == NULL)
973 return -1;
974 res = PyEval_CallObject(func, (PyObject *)NULL);
975 Py_DECREF(func);
976 if (res == NULL)
977 return -1;
978 if (PyInt_Check(res)) {
979 Py_ssize_t temp = PyInt_AsSsize_t(res);
980 if (temp == -1 && PyErr_Occurred()) {
981 Py_DECREF(res);
982 return -1;
984 outcome = (Py_ssize_t)temp;
985 #if SIZEOF_SIZE_T < SIZEOF_LONG
986 /* Overflow check -- range of PyInt is more than C int */
987 if (outcome != temp) {
988 PyErr_SetString(PyExc_OverflowError,
989 "__len__() should return 0 <= outcome < 2**31");
990 outcome = -1;
992 else
993 #endif
994 if (outcome < 0)
995 PyErr_SetString(PyExc_ValueError,
996 "__len__() should return >= 0");
998 else {
999 PyErr_SetString(PyExc_TypeError,
1000 "__len__() should return an int");
1001 outcome = -1;
1003 Py_DECREF(res);
1004 return outcome;
1007 static PyObject *
1008 instance_subscript(PyInstanceObject *inst, PyObject *key)
1010 PyObject *func;
1011 PyObject *arg;
1012 PyObject *res;
1014 if (getitemstr == NULL)
1015 getitemstr = PyString_InternFromString("__getitem__");
1016 func = instance_getattr(inst, getitemstr);
1017 if (func == NULL)
1018 return NULL;
1019 arg = PyTuple_Pack(1, key);
1020 if (arg == NULL) {
1021 Py_DECREF(func);
1022 return NULL;
1024 res = PyEval_CallObject(func, arg);
1025 Py_DECREF(func);
1026 Py_DECREF(arg);
1027 return res;
1030 static int
1031 instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1033 PyObject *func;
1034 PyObject *arg;
1035 PyObject *res;
1037 if (value == NULL) {
1038 if (delitemstr == NULL)
1039 delitemstr = PyString_InternFromString("__delitem__");
1040 func = instance_getattr(inst, delitemstr);
1042 else {
1043 if (setitemstr == NULL)
1044 setitemstr = PyString_InternFromString("__setitem__");
1045 func = instance_getattr(inst, setitemstr);
1047 if (func == NULL)
1048 return -1;
1049 if (value == NULL)
1050 arg = PyTuple_Pack(1, key);
1051 else
1052 arg = PyTuple_Pack(2, key, value);
1053 if (arg == NULL) {
1054 Py_DECREF(func);
1055 return -1;
1057 res = PyEval_CallObject(func, arg);
1058 Py_DECREF(func);
1059 Py_DECREF(arg);
1060 if (res == NULL)
1061 return -1;
1062 Py_DECREF(res);
1063 return 0;
1066 static PyMappingMethods instance_as_mapping = {
1067 (lenfunc)instance_length, /* mp_length */
1068 (binaryfunc)instance_subscript, /* mp_subscript */
1069 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
1072 static PyObject *
1073 instance_item(PyInstanceObject *inst, Py_ssize_t i)
1075 PyObject *func, *res;
1077 if (getitemstr == NULL)
1078 getitemstr = PyString_InternFromString("__getitem__");
1079 func = instance_getattr(inst, getitemstr);
1080 if (func == NULL)
1081 return NULL;
1082 res = PyObject_CallFunction(func, "n", i);
1083 Py_DECREF(func);
1084 return res;
1087 static PyObject *
1088 instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
1090 PyObject *func, *arg, *res;
1091 static PyObject *getslicestr;
1093 if (getslicestr == NULL)
1094 getslicestr = PyString_InternFromString("__getslice__");
1095 func = instance_getattr(inst, getslicestr);
1097 if (func == NULL) {
1098 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1099 return NULL;
1100 PyErr_Clear();
1102 if (getitemstr == NULL)
1103 getitemstr = PyString_InternFromString("__getitem__");
1104 func = instance_getattr(inst, getitemstr);
1105 if (func == NULL)
1106 return NULL;
1107 arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
1108 } else
1109 arg = Py_BuildValue("(nn)", i, j);
1111 if (arg == NULL) {
1112 Py_DECREF(func);
1113 return NULL;
1115 res = PyEval_CallObject(func, arg);
1116 Py_DECREF(func);
1117 Py_DECREF(arg);
1118 return res;
1121 static int
1122 instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
1124 PyObject *func, *arg, *res;
1126 if (item == NULL) {
1127 if (delitemstr == NULL)
1128 delitemstr = PyString_InternFromString("__delitem__");
1129 func = instance_getattr(inst, delitemstr);
1131 else {
1132 if (setitemstr == NULL)
1133 setitemstr = PyString_InternFromString("__setitem__");
1134 func = instance_getattr(inst, setitemstr);
1136 if (func == NULL)
1137 return -1;
1138 if (item == NULL)
1139 arg = PyInt_FromSsize_t(i);
1140 else
1141 arg = Py_BuildValue("(nO)", i, item);
1142 if (arg == NULL) {
1143 Py_DECREF(func);
1144 return -1;
1146 res = PyEval_CallObject(func, arg);
1147 Py_DECREF(func);
1148 Py_DECREF(arg);
1149 if (res == NULL)
1150 return -1;
1151 Py_DECREF(res);
1152 return 0;
1155 static int
1156 instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
1158 PyObject *func, *arg, *res;
1159 static PyObject *setslicestr, *delslicestr;
1161 if (value == NULL) {
1162 if (delslicestr == NULL)
1163 delslicestr =
1164 PyString_InternFromString("__delslice__");
1165 func = instance_getattr(inst, delslicestr);
1166 if (func == NULL) {
1167 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1168 return -1;
1169 PyErr_Clear();
1170 if (delitemstr == NULL)
1171 delitemstr =
1172 PyString_InternFromString("__delitem__");
1173 func = instance_getattr(inst, delitemstr);
1174 if (func == NULL)
1175 return -1;
1177 arg = Py_BuildValue("(N)",
1178 _PySlice_FromIndices(i, j));
1179 } else
1180 arg = Py_BuildValue("(nn)", i, j);
1182 else {
1183 if (setslicestr == NULL)
1184 setslicestr =
1185 PyString_InternFromString("__setslice__");
1186 func = instance_getattr(inst, setslicestr);
1187 if (func == NULL) {
1188 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1189 return -1;
1190 PyErr_Clear();
1191 if (setitemstr == NULL)
1192 setitemstr =
1193 PyString_InternFromString("__setitem__");
1194 func = instance_getattr(inst, setitemstr);
1195 if (func == NULL)
1196 return -1;
1198 arg = Py_BuildValue("(NO)",
1199 _PySlice_FromIndices(i, j), value);
1200 } else
1201 arg = Py_BuildValue("(nnO)", i, j, value);
1203 if (arg == NULL) {
1204 Py_DECREF(func);
1205 return -1;
1207 res = PyEval_CallObject(func, arg);
1208 Py_DECREF(func);
1209 Py_DECREF(arg);
1210 if (res == NULL)
1211 return -1;
1212 Py_DECREF(res);
1213 return 0;
1216 static int
1217 instance_contains(PyInstanceObject *inst, PyObject *member)
1219 static PyObject *__contains__;
1220 PyObject *func;
1222 /* Try __contains__ first.
1223 * If that can't be done, try iterator-based searching.
1226 if(__contains__ == NULL) {
1227 __contains__ = PyString_InternFromString("__contains__");
1228 if(__contains__ == NULL)
1229 return -1;
1231 func = instance_getattr(inst, __contains__);
1232 if (func) {
1233 PyObject *res;
1234 int ret;
1235 PyObject *arg = PyTuple_Pack(1, member);
1236 if(arg == NULL) {
1237 Py_DECREF(func);
1238 return -1;
1240 res = PyEval_CallObject(func, arg);
1241 Py_DECREF(func);
1242 Py_DECREF(arg);
1243 if(res == NULL)
1244 return -1;
1245 ret = PyObject_IsTrue(res);
1246 Py_DECREF(res);
1247 return ret;
1250 /* Couldn't find __contains__. */
1251 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1252 /* Assume the failure was simply due to that there is no
1253 * __contains__ attribute, and try iterating instead.
1255 PyErr_Clear();
1256 return _PySequence_IterSearch((PyObject *)inst, member,
1257 PY_ITERSEARCH_CONTAINS) > 0;
1259 else
1260 return -1;
1263 static PySequenceMethods
1264 instance_as_sequence = {
1265 (lenfunc)instance_length, /* sq_length */
1266 0, /* sq_concat */
1267 0, /* sq_repeat */
1268 (ssizeargfunc)instance_item, /* sq_item */
1269 (ssizessizeargfunc)instance_slice, /* sq_slice */
1270 (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
1271 (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1272 (objobjproc)instance_contains, /* sq_contains */
1275 static PyObject *
1276 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1278 PyObject *func, *res;
1280 if ((func = instance_getattr(self, methodname)) == NULL)
1281 return NULL;
1282 res = PyEval_CallObject(func, (PyObject *)NULL);
1283 Py_DECREF(func);
1284 return res;
1287 static PyObject *
1288 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1290 PyObject *result;
1291 PyObject *args;
1292 PyObject *func = PyObject_GetAttrString(v, opname);
1293 if (func == NULL) {
1294 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1295 return NULL;
1296 PyErr_Clear();
1297 Py_INCREF(Py_NotImplemented);
1298 return Py_NotImplemented;
1300 args = PyTuple_Pack(1, w);
1301 if (args == NULL) {
1302 Py_DECREF(func);
1303 return NULL;
1305 result = PyEval_CallObject(func, args);
1306 Py_DECREF(args);
1307 Py_DECREF(func);
1308 return result;
1312 static PyObject *coerce_obj;
1314 /* Try one half of a binary operator involving a class instance. */
1315 static PyObject *
1316 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1317 int swapped)
1319 PyObject *args;
1320 PyObject *coercefunc;
1321 PyObject *coerced = NULL;
1322 PyObject *v1;
1323 PyObject *result;
1325 if (!PyInstance_Check(v)) {
1326 Py_INCREF(Py_NotImplemented);
1327 return Py_NotImplemented;
1330 if (coerce_obj == NULL) {
1331 coerce_obj = PyString_InternFromString("__coerce__");
1332 if (coerce_obj == NULL)
1333 return NULL;
1335 coercefunc = PyObject_GetAttr(v, coerce_obj);
1336 if (coercefunc == NULL) {
1337 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1338 return NULL;
1339 PyErr_Clear();
1340 return generic_binary_op(v, w, opname);
1343 args = PyTuple_Pack(1, w);
1344 if (args == NULL) {
1345 Py_DECREF(coercefunc);
1346 return NULL;
1348 coerced = PyEval_CallObject(coercefunc, args);
1349 Py_DECREF(args);
1350 Py_DECREF(coercefunc);
1351 if (coerced == NULL) {
1352 return NULL;
1354 if (coerced == Py_None || coerced == Py_NotImplemented) {
1355 Py_DECREF(coerced);
1356 return generic_binary_op(v, w, opname);
1358 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1359 Py_DECREF(coerced);
1360 PyErr_SetString(PyExc_TypeError,
1361 "coercion should return None or 2-tuple");
1362 return NULL;
1364 v1 = PyTuple_GetItem(coerced, 0);
1365 w = PyTuple_GetItem(coerced, 1);
1366 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1367 /* prevent recursion if __coerce__ returns self as the first
1368 * argument */
1369 result = generic_binary_op(v1, w, opname);
1370 } else {
1371 if (Py_EnterRecursiveCall(" after coercion"))
1372 return NULL;
1373 if (swapped)
1374 result = (thisfunc)(w, v1);
1375 else
1376 result = (thisfunc)(v1, w);
1377 Py_LeaveRecursiveCall();
1379 Py_DECREF(coerced);
1380 return result;
1383 /* Implement a binary operator involving at least one class instance. */
1384 static PyObject *
1385 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1386 binaryfunc thisfunc)
1388 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1389 if (result == Py_NotImplemented) {
1390 Py_DECREF(result);
1391 result = half_binop(w, v, ropname, thisfunc, 1);
1393 return result;
1396 static PyObject *
1397 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1398 char *ropname, binaryfunc thisfunc)
1400 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1401 if (result == Py_NotImplemented) {
1402 Py_DECREF(result);
1403 result = do_binop(v, w, opname, ropname, thisfunc);
1405 return result;
1408 static int
1409 instance_coerce(PyObject **pv, PyObject **pw)
1411 PyObject *v = *pv;
1412 PyObject *w = *pw;
1413 PyObject *coercefunc;
1414 PyObject *args;
1415 PyObject *coerced;
1417 if (coerce_obj == NULL) {
1418 coerce_obj = PyString_InternFromString("__coerce__");
1419 if (coerce_obj == NULL)
1420 return -1;
1422 coercefunc = PyObject_GetAttr(v, coerce_obj);
1423 if (coercefunc == NULL) {
1424 /* No __coerce__ method */
1425 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1426 return -1;
1427 PyErr_Clear();
1428 return 1;
1430 /* Has __coerce__ method: call it */
1431 args = PyTuple_Pack(1, w);
1432 if (args == NULL) {
1433 return -1;
1435 coerced = PyEval_CallObject(coercefunc, args);
1436 Py_DECREF(args);
1437 Py_DECREF(coercefunc);
1438 if (coerced == NULL) {
1439 /* __coerce__ call raised an exception */
1440 return -1;
1442 if (coerced == Py_None || coerced == Py_NotImplemented) {
1443 /* __coerce__ says "I can't do it" */
1444 Py_DECREF(coerced);
1445 return 1;
1447 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1448 /* __coerce__ return value is malformed */
1449 Py_DECREF(coerced);
1450 PyErr_SetString(PyExc_TypeError,
1451 "coercion should return None or 2-tuple");
1452 return -1;
1454 /* __coerce__ returned two new values */
1455 *pv = PyTuple_GetItem(coerced, 0);
1456 *pw = PyTuple_GetItem(coerced, 1);
1457 Py_INCREF(*pv);
1458 Py_INCREF(*pw);
1459 Py_DECREF(coerced);
1460 return 0;
1463 #define UNARY(funcname, methodname) \
1464 static PyObject *funcname(PyInstanceObject *self) { \
1465 static PyObject *o; \
1466 if (o == NULL) o = PyString_InternFromString(methodname); \
1467 return generic_unary_op(self, o); \
1470 #define BINARY(f, m, n) \
1471 static PyObject *f(PyObject *v, PyObject *w) { \
1472 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1475 #define BINARY_INPLACE(f, m, n) \
1476 static PyObject *f(PyObject *v, PyObject *w) { \
1477 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1478 "__r" m "__", n); \
1481 UNARY(instance_neg, "__neg__")
1482 UNARY(instance_pos, "__pos__")
1483 UNARY(instance_abs, "__abs__")
1485 BINARY(instance_or, "or", PyNumber_Or)
1486 BINARY(instance_and, "and", PyNumber_And)
1487 BINARY(instance_xor, "xor", PyNumber_Xor)
1488 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1489 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1490 BINARY(instance_add, "add", PyNumber_Add)
1491 BINARY(instance_sub, "sub", PyNumber_Subtract)
1492 BINARY(instance_mul, "mul", PyNumber_Multiply)
1493 BINARY(instance_div, "div", PyNumber_Divide)
1494 BINARY(instance_mod, "mod", PyNumber_Remainder)
1495 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1496 BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1497 BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1499 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1500 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1501 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1502 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1503 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1504 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1505 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1506 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1507 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1508 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1509 BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1510 BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1512 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1513 -2 for an exception;
1514 -1 if v < w;
1515 0 if v == w;
1516 1 if v > w;
1517 2 if this particular 3-way comparison is not implemented or undefined.
1519 static int
1520 half_cmp(PyObject *v, PyObject *w)
1522 static PyObject *cmp_obj;
1523 PyObject *args;
1524 PyObject *cmp_func;
1525 PyObject *result;
1526 long l;
1528 assert(PyInstance_Check(v));
1530 if (cmp_obj == NULL) {
1531 cmp_obj = PyString_InternFromString("__cmp__");
1532 if (cmp_obj == NULL)
1533 return -2;
1536 cmp_func = PyObject_GetAttr(v, cmp_obj);
1537 if (cmp_func == NULL) {
1538 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1539 return -2;
1540 PyErr_Clear();
1541 return 2;
1544 args = PyTuple_Pack(1, w);
1545 if (args == NULL) {
1546 Py_DECREF(cmp_func);
1547 return -2;
1550 result = PyEval_CallObject(cmp_func, args);
1551 Py_DECREF(args);
1552 Py_DECREF(cmp_func);
1554 if (result == NULL)
1555 return -2;
1557 if (result == Py_NotImplemented) {
1558 Py_DECREF(result);
1559 return 2;
1562 l = PyInt_AsLong(result);
1563 Py_DECREF(result);
1564 if (l == -1 && PyErr_Occurred()) {
1565 PyErr_SetString(PyExc_TypeError,
1566 "comparison did not return an int");
1567 return -2;
1570 return l < 0 ? -1 : l > 0 ? 1 : 0;
1573 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1574 We first try a coercion. Return:
1575 -2 for an exception;
1576 -1 if v < w;
1577 0 if v == w;
1578 1 if v > w;
1579 2 if this particular 3-way comparison is not implemented or undefined.
1580 THIS IS ONLY CALLED FROM object.c!
1582 static int
1583 instance_compare(PyObject *v, PyObject *w)
1585 int c;
1587 c = PyNumber_CoerceEx(&v, &w);
1588 if (c < 0)
1589 return -2;
1590 if (c == 0) {
1591 /* If neither is now an instance, use regular comparison */
1592 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1593 c = PyObject_Compare(v, w);
1594 Py_DECREF(v);
1595 Py_DECREF(w);
1596 if (PyErr_Occurred())
1597 return -2;
1598 return c < 0 ? -1 : c > 0 ? 1 : 0;
1601 else {
1602 /* The coercion didn't do anything.
1603 Treat this the same as returning v and w unchanged. */
1604 Py_INCREF(v);
1605 Py_INCREF(w);
1608 if (PyInstance_Check(v)) {
1609 c = half_cmp(v, w);
1610 if (c <= 1) {
1611 Py_DECREF(v);
1612 Py_DECREF(w);
1613 return c;
1616 if (PyInstance_Check(w)) {
1617 c = half_cmp(w, v);
1618 if (c <= 1) {
1619 Py_DECREF(v);
1620 Py_DECREF(w);
1621 if (c >= -1)
1622 c = -c;
1623 return c;
1626 Py_DECREF(v);
1627 Py_DECREF(w);
1628 return 2;
1631 static int
1632 instance_nonzero(PyInstanceObject *self)
1634 PyObject *func, *res;
1635 long outcome;
1636 static PyObject *nonzerostr;
1638 if (nonzerostr == NULL)
1639 nonzerostr = PyString_InternFromString("__nonzero__");
1640 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1641 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1642 return -1;
1643 PyErr_Clear();
1644 if (lenstr == NULL)
1645 lenstr = PyString_InternFromString("__len__");
1646 if ((func = instance_getattr(self, lenstr)) == NULL) {
1647 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1648 return -1;
1649 PyErr_Clear();
1650 /* Fall back to the default behavior:
1651 all instances are nonzero */
1652 return 1;
1655 res = PyEval_CallObject(func, (PyObject *)NULL);
1656 Py_DECREF(func);
1657 if (res == NULL)
1658 return -1;
1659 if (!PyInt_Check(res)) {
1660 Py_DECREF(res);
1661 PyErr_SetString(PyExc_TypeError,
1662 "__nonzero__ should return an int");
1663 return -1;
1665 outcome = PyInt_AsLong(res);
1666 Py_DECREF(res);
1667 if (outcome < 0) {
1668 PyErr_SetString(PyExc_ValueError,
1669 "__nonzero__ should return >= 0");
1670 return -1;
1672 return outcome > 0;
1675 static Py_ssize_t
1676 instance_index(PyInstanceObject *self)
1678 PyObject *func, *res;
1679 Py_ssize_t outcome;
1680 static PyObject *indexstr = NULL;
1682 if (indexstr == NULL) {
1683 indexstr = PyString_InternFromString("__index__");
1684 if (indexstr == NULL)
1685 return -1;
1687 if ((func = instance_getattr(self, indexstr)) == NULL) {
1688 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1689 return -1;
1690 PyErr_Clear();
1691 PyErr_SetString(PyExc_TypeError,
1692 "object cannot be interpreted as an index");
1693 return -1;
1695 res = PyEval_CallObject(func, (PyObject *)NULL);
1696 Py_DECREF(func);
1697 if (res == NULL)
1698 return -1;
1699 if (PyInt_Check(res) || PyLong_Check(res)) {
1700 outcome = res->ob_type->tp_as_number->nb_index(res);
1702 else {
1703 PyErr_SetString(PyExc_TypeError,
1704 "__index__ must return an int or a long");
1705 outcome = -1;
1707 Py_DECREF(res);
1708 return outcome;
1712 UNARY(instance_invert, "__invert__")
1713 UNARY(instance_int, "__int__")
1714 UNARY(instance_long, "__long__")
1715 UNARY(instance_float, "__float__")
1716 UNARY(instance_oct, "__oct__")
1717 UNARY(instance_hex, "__hex__")
1719 static PyObject *
1720 bin_power(PyObject *v, PyObject *w)
1722 return PyNumber_Power(v, w, Py_None);
1725 /* This version is for ternary calls only (z != None) */
1726 static PyObject *
1727 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1729 if (z == Py_None) {
1730 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1732 else {
1733 PyObject *func;
1734 PyObject *args;
1735 PyObject *result;
1737 /* XXX Doesn't do coercions... */
1738 func = PyObject_GetAttrString(v, "__pow__");
1739 if (func == NULL)
1740 return NULL;
1741 args = PyTuple_Pack(2, w, z);
1742 if (args == NULL) {
1743 Py_DECREF(func);
1744 return NULL;
1746 result = PyEval_CallObject(func, args);
1747 Py_DECREF(func);
1748 Py_DECREF(args);
1749 return result;
1753 static PyObject *
1754 bin_inplace_power(PyObject *v, PyObject *w)
1756 return PyNumber_InPlacePower(v, w, Py_None);
1760 static PyObject *
1761 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1763 if (z == Py_None) {
1764 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1765 "__rpow__", bin_inplace_power);
1767 else {
1768 /* XXX Doesn't do coercions... */
1769 PyObject *func;
1770 PyObject *args;
1771 PyObject *result;
1773 func = PyObject_GetAttrString(v, "__ipow__");
1774 if (func == NULL) {
1775 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1776 return NULL;
1777 PyErr_Clear();
1778 return instance_pow(v, w, z);
1780 args = PyTuple_Pack(2, w, z);
1781 if (args == NULL) {
1782 Py_DECREF(func);
1783 return NULL;
1785 result = PyEval_CallObject(func, args);
1786 Py_DECREF(func);
1787 Py_DECREF(args);
1788 return result;
1793 /* Map rich comparison operators to their __xx__ namesakes */
1794 #define NAME_OPS 6
1795 static PyObject **name_op = NULL;
1797 static int
1798 init_name_op(void)
1800 int i;
1801 char *_name_op[] = {
1802 "__lt__",
1803 "__le__",
1804 "__eq__",
1805 "__ne__",
1806 "__gt__",
1807 "__ge__",
1810 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1811 if (name_op == NULL)
1812 return -1;
1813 for (i = 0; i < NAME_OPS; ++i) {
1814 name_op[i] = PyString_InternFromString(_name_op[i]);
1815 if (name_op[i] == NULL)
1816 return -1;
1818 return 0;
1821 static PyObject *
1822 half_richcompare(PyObject *v, PyObject *w, int op)
1824 PyObject *method;
1825 PyObject *args;
1826 PyObject *res;
1828 assert(PyInstance_Check(v));
1830 if (name_op == NULL) {
1831 if (init_name_op() < 0)
1832 return NULL;
1834 /* If the instance doesn't define an __getattr__ method, use
1835 instance_getattr2 directly because it will not set an
1836 exception on failure. */
1837 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1838 method = instance_getattr2((PyInstanceObject *)v,
1839 name_op[op]);
1840 else
1841 method = PyObject_GetAttr(v, name_op[op]);
1842 if (method == NULL) {
1843 if (PyErr_Occurred()) {
1844 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1845 return NULL;
1846 PyErr_Clear();
1848 res = Py_NotImplemented;
1849 Py_INCREF(res);
1850 return res;
1853 args = PyTuple_Pack(1, w);
1854 if (args == NULL) {
1855 Py_DECREF(method);
1856 return NULL;
1859 res = PyEval_CallObject(method, args);
1860 Py_DECREF(args);
1861 Py_DECREF(method);
1863 return res;
1866 static PyObject *
1867 instance_richcompare(PyObject *v, PyObject *w, int op)
1869 PyObject *res;
1871 if (PyInstance_Check(v)) {
1872 res = half_richcompare(v, w, op);
1873 if (res != Py_NotImplemented)
1874 return res;
1875 Py_DECREF(res);
1878 if (PyInstance_Check(w)) {
1879 res = half_richcompare(w, v, _Py_SwappedOp[op]);
1880 if (res != Py_NotImplemented)
1881 return res;
1882 Py_DECREF(res);
1885 Py_INCREF(Py_NotImplemented);
1886 return Py_NotImplemented;
1890 /* Get the iterator */
1891 static PyObject *
1892 instance_getiter(PyInstanceObject *self)
1894 PyObject *func;
1896 if (iterstr == NULL) {
1897 iterstr = PyString_InternFromString("__iter__");
1898 if (iterstr == NULL)
1899 return NULL;
1901 if (getitemstr == NULL) {
1902 getitemstr = PyString_InternFromString("__getitem__");
1903 if (getitemstr == NULL)
1904 return NULL;
1907 if ((func = instance_getattr(self, iterstr)) != NULL) {
1908 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1909 Py_DECREF(func);
1910 if (res != NULL && !PyIter_Check(res)) {
1911 PyErr_Format(PyExc_TypeError,
1912 "__iter__ returned non-iterator "
1913 "of type '%.100s'",
1914 res->ob_type->tp_name);
1915 Py_DECREF(res);
1916 res = NULL;
1918 return res;
1920 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1921 return NULL;
1922 PyErr_Clear();
1923 if ((func = instance_getattr(self, getitemstr)) == NULL) {
1924 PyErr_SetString(PyExc_TypeError,
1925 "iteration over non-sequence");
1926 return NULL;
1928 Py_DECREF(func);
1929 return PySeqIter_New((PyObject *)self);
1933 /* Call the iterator's next */
1934 static PyObject *
1935 instance_iternext(PyInstanceObject *self)
1937 PyObject *func;
1939 if (nextstr == NULL)
1940 nextstr = PyString_InternFromString("next");
1942 if ((func = instance_getattr(self, nextstr)) != NULL) {
1943 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1944 Py_DECREF(func);
1945 if (res != NULL) {
1946 return res;
1948 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
1949 PyErr_Clear();
1950 return NULL;
1952 return NULL;
1954 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
1955 return NULL;
1958 static PyObject *
1959 instance_call(PyObject *func, PyObject *arg, PyObject *kw)
1961 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
1962 if (call == NULL) {
1963 PyInstanceObject *inst = (PyInstanceObject*) func;
1964 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1965 return NULL;
1966 PyErr_Clear();
1967 PyErr_Format(PyExc_AttributeError,
1968 "%.200s instance has no __call__ method",
1969 PyString_AsString(inst->in_class->cl_name));
1970 return NULL;
1972 /* We must check and increment the recursion depth here. Scenario:
1973 class A:
1974 pass
1975 A.__call__ = A() # that's right
1976 a = A() # ok
1977 a() # infinite recursion
1978 This bounces between instance_call() and PyObject_Call() without
1979 ever hitting eval_frame() (which has the main recursion check). */
1980 if (Py_EnterRecursiveCall(" in __call__")) {
1981 res = NULL;
1983 else {
1984 res = PyObject_Call(call, arg, kw);
1985 Py_LeaveRecursiveCall();
1987 Py_DECREF(call);
1988 return res;
1992 static PyNumberMethods instance_as_number = {
1993 instance_add, /* nb_add */
1994 instance_sub, /* nb_subtract */
1995 instance_mul, /* nb_multiply */
1996 instance_div, /* nb_divide */
1997 instance_mod, /* nb_remainder */
1998 instance_divmod, /* nb_divmod */
1999 instance_pow, /* nb_power */
2000 (unaryfunc)instance_neg, /* nb_negative */
2001 (unaryfunc)instance_pos, /* nb_positive */
2002 (unaryfunc)instance_abs, /* nb_absolute */
2003 (inquiry)instance_nonzero, /* nb_nonzero */
2004 (unaryfunc)instance_invert, /* nb_invert */
2005 instance_lshift, /* nb_lshift */
2006 instance_rshift, /* nb_rshift */
2007 instance_and, /* nb_and */
2008 instance_xor, /* nb_xor */
2009 instance_or, /* nb_or */
2010 instance_coerce, /* nb_coerce */
2011 (unaryfunc)instance_int, /* nb_int */
2012 (unaryfunc)instance_long, /* nb_long */
2013 (unaryfunc)instance_float, /* nb_float */
2014 (unaryfunc)instance_oct, /* nb_oct */
2015 (unaryfunc)instance_hex, /* nb_hex */
2016 instance_iadd, /* nb_inplace_add */
2017 instance_isub, /* nb_inplace_subtract */
2018 instance_imul, /* nb_inplace_multiply */
2019 instance_idiv, /* nb_inplace_divide */
2020 instance_imod, /* nb_inplace_remainder */
2021 instance_ipow, /* nb_inplace_power */
2022 instance_ilshift, /* nb_inplace_lshift */
2023 instance_irshift, /* nb_inplace_rshift */
2024 instance_iand, /* nb_inplace_and */
2025 instance_ixor, /* nb_inplace_xor */
2026 instance_ior, /* nb_inplace_or */
2027 instance_floordiv, /* nb_floor_divide */
2028 instance_truediv, /* nb_true_divide */
2029 instance_ifloordiv, /* nb_inplace_floor_divide */
2030 instance_itruediv, /* nb_inplace_true_divide */
2031 (lenfunc)instance_index, /* nb_index */
2034 PyTypeObject PyInstance_Type = {
2035 PyObject_HEAD_INIT(&PyType_Type)
2037 "instance",
2038 sizeof(PyInstanceObject),
2040 (destructor)instance_dealloc, /* tp_dealloc */
2041 0, /* tp_print */
2042 0, /* tp_getattr */
2043 0, /* tp_setattr */
2044 instance_compare, /* tp_compare */
2045 (reprfunc)instance_repr, /* tp_repr */
2046 &instance_as_number, /* tp_as_number */
2047 &instance_as_sequence, /* tp_as_sequence */
2048 &instance_as_mapping, /* tp_as_mapping */
2049 (hashfunc)instance_hash, /* tp_hash */
2050 instance_call, /* tp_call */
2051 (reprfunc)instance_str, /* tp_str */
2052 (getattrofunc)instance_getattr, /* tp_getattro */
2053 (setattrofunc)instance_setattr, /* tp_setattro */
2054 0, /* tp_as_buffer */
2055 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2056 instance_doc, /* tp_doc */
2057 (traverseproc)instance_traverse, /* tp_traverse */
2058 0, /* tp_clear */
2059 instance_richcompare, /* tp_richcompare */
2060 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2061 (getiterfunc)instance_getiter, /* tp_iter */
2062 (iternextfunc)instance_iternext, /* tp_iternext */
2063 0, /* tp_methods */
2064 0, /* tp_members */
2065 0, /* tp_getset */
2066 0, /* tp_base */
2067 0, /* tp_dict */
2068 0, /* tp_descr_get */
2069 0, /* tp_descr_set */
2070 0, /* tp_dictoffset */
2071 0, /* tp_init */
2072 0, /* tp_alloc */
2073 instance_new, /* tp_new */
2077 /* Instance method objects are used for two purposes:
2078 (a) as bound instance methods (returned by instancename.methodname)
2079 (b) as unbound methods (returned by ClassName.methodname)
2080 In case (b), im_self is NULL
2083 static PyMethodObject *free_list;
2085 PyObject *
2086 PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
2088 register PyMethodObject *im;
2089 if (!PyCallable_Check(func)) {
2090 PyErr_BadInternalCall();
2091 return NULL;
2093 im = free_list;
2094 if (im != NULL) {
2095 free_list = (PyMethodObject *)(im->im_self);
2096 PyObject_INIT(im, &PyMethod_Type);
2098 else {
2099 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2100 if (im == NULL)
2101 return NULL;
2103 im->im_weakreflist = NULL;
2104 Py_INCREF(func);
2105 im->im_func = func;
2106 Py_XINCREF(self);
2107 im->im_self = self;
2108 Py_XINCREF(klass);
2109 im->im_class = klass;
2110 _PyObject_GC_TRACK(im);
2111 return (PyObject *)im;
2114 /* Descriptors for PyMethod attributes */
2116 /* im_class, im_func and im_self are stored in the PyMethod object */
2118 #define OFF(x) offsetof(PyMethodObject, x)
2120 static PyMemberDef instancemethod_memberlist[] = {
2121 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2122 "the class associated with a method"},
2123 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2124 "the function (or other callable) implementing a method"},
2125 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2126 "the instance to which a method is bound; None for unbound methods"},
2127 {NULL} /* Sentinel */
2130 /* Christian Tismer argued convincingly that method attributes should
2131 (nearly) always override function attributes.
2132 The one exception is __doc__; there's a default __doc__ which
2133 should only be used for the class, not for instances */
2135 static PyObject *
2136 instancemethod_get_doc(PyMethodObject *im, void *context)
2138 static PyObject *docstr;
2139 if (docstr == NULL) {
2140 docstr= PyString_InternFromString("__doc__");
2141 if (docstr == NULL)
2142 return NULL;
2144 return PyObject_GetAttr(im->im_func, docstr);
2147 static PyGetSetDef instancemethod_getset[] = {
2148 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2152 static PyObject *
2153 instancemethod_getattro(PyObject *obj, PyObject *name)
2155 PyMethodObject *im = (PyMethodObject *)obj;
2156 PyTypeObject *tp = obj->ob_type;
2157 PyObject *descr = NULL;
2159 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2160 if (tp->tp_dict == NULL) {
2161 if (PyType_Ready(tp) < 0)
2162 return NULL;
2164 descr = _PyType_Lookup(tp, name);
2167 if (descr != NULL) {
2168 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
2169 if (f != NULL)
2170 return f(descr, obj, (PyObject *)obj->ob_type);
2171 else {
2172 Py_INCREF(descr);
2173 return descr;
2177 return PyObject_GetAttr(im->im_func, name);
2180 PyDoc_STRVAR(instancemethod_doc,
2181 "instancemethod(function, instance, class)\n\
2183 Create an instance method object.");
2185 static PyObject *
2186 instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2188 PyObject *func;
2189 PyObject *self;
2190 PyObject *classObj = NULL;
2192 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2193 &func, &self, &classObj))
2194 return NULL;
2195 if (!PyCallable_Check(func)) {
2196 PyErr_SetString(PyExc_TypeError,
2197 "first argument must be callable");
2198 return NULL;
2200 if (self == Py_None)
2201 self = NULL;
2202 if (self == NULL && classObj == NULL) {
2203 PyErr_SetString(PyExc_TypeError,
2204 "unbound methods must have non-NULL im_class");
2205 return NULL;
2208 return PyMethod_New(func, self, classObj);
2211 static void
2212 instancemethod_dealloc(register PyMethodObject *im)
2214 _PyObject_GC_UNTRACK(im);
2215 if (im->im_weakreflist != NULL)
2216 PyObject_ClearWeakRefs((PyObject *)im);
2217 Py_DECREF(im->im_func);
2218 Py_XDECREF(im->im_self);
2219 Py_XDECREF(im->im_class);
2220 im->im_self = (PyObject *)free_list;
2221 free_list = im;
2224 static int
2225 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2227 int cmp;
2228 cmp = PyObject_Compare(a->im_func, b->im_func);
2229 if (cmp)
2230 return cmp;
2232 if (a->im_self == b->im_self)
2233 return 0;
2234 if (a->im_self == NULL || b->im_self == NULL)
2235 return (a->im_self < b->im_self) ? -1 : 1;
2236 else
2237 return PyObject_Compare(a->im_self, b->im_self);
2240 static PyObject *
2241 instancemethod_repr(PyMethodObject *a)
2243 PyObject *self = a->im_self;
2244 PyObject *func = a->im_func;
2245 PyObject *klass = a->im_class;
2246 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2247 char *sfuncname = "?", *sklassname = "?";
2249 funcname = PyObject_GetAttrString(func, "__name__");
2250 if (funcname == NULL) {
2251 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2252 return NULL;
2253 PyErr_Clear();
2255 else if (!PyString_Check(funcname)) {
2256 Py_DECREF(funcname);
2257 funcname = NULL;
2259 else
2260 sfuncname = PyString_AS_STRING(funcname);
2261 if (klass == NULL)
2262 klassname = NULL;
2263 else {
2264 klassname = PyObject_GetAttrString(klass, "__name__");
2265 if (klassname == NULL) {
2266 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2267 return NULL;
2268 PyErr_Clear();
2270 else if (!PyString_Check(klassname)) {
2271 Py_DECREF(klassname);
2272 klassname = NULL;
2274 else
2275 sklassname = PyString_AS_STRING(klassname);
2277 if (self == NULL)
2278 result = PyString_FromFormat("<unbound method %s.%s>",
2279 sklassname, sfuncname);
2280 else {
2281 /* XXX Shouldn't use repr() here! */
2282 PyObject *selfrepr = PyObject_Repr(self);
2283 if (selfrepr == NULL)
2284 goto fail;
2285 if (!PyString_Check(selfrepr)) {
2286 Py_DECREF(selfrepr);
2287 goto fail;
2289 result = PyString_FromFormat("<bound method %s.%s of %s>",
2290 sklassname, sfuncname,
2291 PyString_AS_STRING(selfrepr));
2292 Py_DECREF(selfrepr);
2294 fail:
2295 Py_XDECREF(funcname);
2296 Py_XDECREF(klassname);
2297 return result;
2300 static long
2301 instancemethod_hash(PyMethodObject *a)
2303 long x, y;
2304 if (a->im_self == NULL)
2305 x = PyObject_Hash(Py_None);
2306 else
2307 x = PyObject_Hash(a->im_self);
2308 if (x == -1)
2309 return -1;
2310 y = PyObject_Hash(a->im_func);
2311 if (y == -1)
2312 return -1;
2313 x = x ^ y;
2314 if (x == -1)
2315 x = -2;
2316 return x;
2319 static int
2320 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2322 Py_VISIT(im->im_func);
2323 Py_VISIT(im->im_self);
2324 Py_VISIT(im->im_class);
2325 return 0;
2328 static void
2329 getclassname(PyObject *klass, char *buf, int bufsize)
2331 PyObject *name;
2333 assert(bufsize > 1);
2334 strcpy(buf, "?"); /* Default outcome */
2335 if (klass == NULL)
2336 return;
2337 name = PyObject_GetAttrString(klass, "__name__");
2338 if (name == NULL) {
2339 /* This function cannot return an exception */
2340 PyErr_Clear();
2341 return;
2343 if (PyString_Check(name)) {
2344 strncpy(buf, PyString_AS_STRING(name), bufsize);
2345 buf[bufsize-1] = '\0';
2347 Py_DECREF(name);
2350 static void
2351 getinstclassname(PyObject *inst, char *buf, int bufsize)
2353 PyObject *klass;
2355 if (inst == NULL) {
2356 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2357 strcpy(buf, "nothing");
2358 return;
2361 klass = PyObject_GetAttrString(inst, "__class__");
2362 if (klass == NULL) {
2363 /* This function cannot return an exception */
2364 PyErr_Clear();
2365 klass = (PyObject *)(inst->ob_type);
2366 Py_INCREF(klass);
2368 getclassname(klass, buf, bufsize);
2369 Py_XDECREF(klass);
2372 static PyObject *
2373 instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2375 PyObject *self = PyMethod_GET_SELF(func);
2376 PyObject *klass = PyMethod_GET_CLASS(func);
2377 PyObject *result;
2379 func = PyMethod_GET_FUNCTION(func);
2380 if (self == NULL) {
2381 /* Unbound methods must be called with an instance of
2382 the class (or a derived class) as first argument */
2383 int ok;
2384 if (PyTuple_Size(arg) >= 1)
2385 self = PyTuple_GET_ITEM(arg, 0);
2386 if (self == NULL)
2387 ok = 0;
2388 else {
2389 ok = PyObject_IsInstance(self, klass);
2390 if (ok < 0)
2391 return NULL;
2393 if (!ok) {
2394 char clsbuf[256];
2395 char instbuf[256];
2396 getclassname(klass, clsbuf, sizeof(clsbuf));
2397 getinstclassname(self, instbuf, sizeof(instbuf));
2398 PyErr_Format(PyExc_TypeError,
2399 "unbound method %s%s must be called with "
2400 "%s instance as first argument "
2401 "(got %s%s instead)",
2402 PyEval_GetFuncName(func),
2403 PyEval_GetFuncDesc(func),
2404 clsbuf,
2405 instbuf,
2406 self == NULL ? "" : " instance");
2407 return NULL;
2409 Py_INCREF(arg);
2411 else {
2412 Py_ssize_t argcount = PyTuple_Size(arg);
2413 PyObject *newarg = PyTuple_New(argcount + 1);
2414 int i;
2415 if (newarg == NULL)
2416 return NULL;
2417 Py_INCREF(self);
2418 PyTuple_SET_ITEM(newarg, 0, self);
2419 for (i = 0; i < argcount; i++) {
2420 PyObject *v = PyTuple_GET_ITEM(arg, i);
2421 Py_XINCREF(v);
2422 PyTuple_SET_ITEM(newarg, i+1, v);
2424 arg = newarg;
2426 result = PyObject_Call((PyObject *)func, arg, kw);
2427 Py_DECREF(arg);
2428 return result;
2431 static PyObject *
2432 instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
2434 /* Don't rebind an already bound method, or an unbound method
2435 of a class that's not a base class of cls. */
2437 if (PyMethod_GET_SELF(meth) != NULL) {
2438 /* Already bound */
2439 Py_INCREF(meth);
2440 return meth;
2442 /* No, it is an unbound method */
2443 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2444 /* Do subclass test. If it fails, return meth unchanged. */
2445 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2446 if (ok < 0)
2447 return NULL;
2448 if (!ok) {
2449 Py_INCREF(meth);
2450 return meth;
2453 /* Bind it to obj */
2454 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
2457 PyTypeObject PyMethod_Type = {
2458 PyObject_HEAD_INIT(&PyType_Type)
2460 "instancemethod",
2461 sizeof(PyMethodObject),
2463 (destructor)instancemethod_dealloc, /* tp_dealloc */
2464 0, /* tp_print */
2465 0, /* tp_getattr */
2466 0, /* tp_setattr */
2467 (cmpfunc)instancemethod_compare, /* tp_compare */
2468 (reprfunc)instancemethod_repr, /* tp_repr */
2469 0, /* tp_as_number */
2470 0, /* tp_as_sequence */
2471 0, /* tp_as_mapping */
2472 (hashfunc)instancemethod_hash, /* tp_hash */
2473 instancemethod_call, /* tp_call */
2474 0, /* tp_str */
2475 instancemethod_getattro, /* tp_getattro */
2476 PyObject_GenericSetAttr, /* tp_setattro */
2477 0, /* tp_as_buffer */
2478 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2479 instancemethod_doc, /* tp_doc */
2480 (traverseproc)instancemethod_traverse, /* tp_traverse */
2481 0, /* tp_clear */
2482 0, /* tp_richcompare */
2483 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2484 0, /* tp_iter */
2485 0, /* tp_iternext */
2486 0, /* tp_methods */
2487 instancemethod_memberlist, /* tp_members */
2488 instancemethod_getset, /* tp_getset */
2489 0, /* tp_base */
2490 0, /* tp_dict */
2491 instancemethod_descr_get, /* tp_descr_get */
2492 0, /* tp_descr_set */
2493 0, /* tp_dictoffset */
2494 0, /* tp_init */
2495 0, /* tp_alloc */
2496 instancemethod_new, /* tp_new */
2499 /* Clear out the free list */
2501 void
2502 PyMethod_Fini(void)
2504 while (free_list) {
2505 PyMethodObject *im = free_list;
2506 free_list = (PyMethodObject *)(im->im_self);
2507 PyObject_GC_Del(im);