Add wrapper for DBEnv.set_tx_timeout method to allow time based DB_RECOVER
[python.git] / Objects / classobject.c
blobc8057e2a2ef4f9334ebfb20cdeaedb044b04b5ec
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 int 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_CallFunction(
85 (PyObject *) base->ob_type,
86 "OOO",
87 name,
88 bases,
89 dict);
90 PyErr_SetString(PyExc_TypeError,
91 "PyClass_New: base must be a class");
92 return NULL;
95 Py_INCREF(bases);
97 op = PyObject_GC_New(PyClassObject, &PyClass_Type);
98 if (op == NULL) {
99 Py_DECREF(bases);
100 return NULL;
102 op->cl_bases = bases;
103 Py_INCREF(dict);
104 op->cl_dict = dict;
105 Py_XINCREF(name);
106 op->cl_name = name;
107 if (getattrstr == NULL) {
108 getattrstr = PyString_InternFromString("__getattr__");
109 setattrstr = PyString_InternFromString("__setattr__");
110 delattrstr = PyString_InternFromString("__delattr__");
112 op->cl_getattr = class_lookup(op, getattrstr, &dummy);
113 op->cl_setattr = class_lookup(op, setattrstr, &dummy);
114 op->cl_delattr = class_lookup(op, delattrstr, &dummy);
115 Py_XINCREF(op->cl_getattr);
116 Py_XINCREF(op->cl_setattr);
117 Py_XINCREF(op->cl_delattr);
118 _PyObject_GC_TRACK(op);
119 return (PyObject *) op;
122 PyObject *
123 PyMethod_Function(PyObject *im)
125 if (!PyMethod_Check(im)) {
126 PyErr_BadInternalCall();
127 return NULL;
129 return ((PyMethodObject *)im)->im_func;
132 PyObject *
133 PyMethod_Self(PyObject *im)
135 if (!PyMethod_Check(im)) {
136 PyErr_BadInternalCall();
137 return NULL;
139 return ((PyMethodObject *)im)->im_self;
142 PyObject *
143 PyMethod_Class(PyObject *im)
145 if (!PyMethod_Check(im)) {
146 PyErr_BadInternalCall();
147 return NULL;
149 return ((PyMethodObject *)im)->im_class;
152 PyDoc_STRVAR(class_doc,
153 "classobj(name, bases, dict)\n\
155 Create a class object. The name must be a string; the second argument\n\
156 a tuple of classes, and the third a dictionary.");
158 static PyObject *
159 class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
161 PyObject *name, *bases, *dict;
162 static const char *kwlist[] = {"name", "bases", "dict", 0};
164 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
165 &name, &bases, &dict))
166 return NULL;
167 return PyClass_New(bases, dict, name);
170 /* Class methods */
172 static void
173 class_dealloc(PyClassObject *op)
175 _PyObject_GC_UNTRACK(op);
176 Py_DECREF(op->cl_bases);
177 Py_DECREF(op->cl_dict);
178 Py_XDECREF(op->cl_name);
179 Py_XDECREF(op->cl_getattr);
180 Py_XDECREF(op->cl_setattr);
181 Py_XDECREF(op->cl_delattr);
182 PyObject_GC_Del(op);
185 static PyObject *
186 class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
188 int i, n;
189 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
190 if (value != NULL) {
191 *pclass = cp;
192 return value;
194 n = PyTuple_Size(cp->cl_bases);
195 for (i = 0; i < n; i++) {
196 /* XXX What if one of the bases is not a class? */
197 PyObject *v = class_lookup(
198 (PyClassObject *)
199 PyTuple_GetItem(cp->cl_bases, i), name, pclass);
200 if (v != NULL)
201 return v;
203 return NULL;
206 static PyObject *
207 class_getattr(register PyClassObject *op, PyObject *name)
209 register PyObject *v;
210 register char *sname = PyString_AsString(name);
211 PyClassObject *class;
212 descrgetfunc f;
214 if (sname[0] == '_' && sname[1] == '_') {
215 if (strcmp(sname, "__dict__") == 0) {
216 if (PyEval_GetRestricted()) {
217 PyErr_SetString(PyExc_RuntimeError,
218 "class.__dict__ not accessible in restricted mode");
219 return NULL;
221 Py_INCREF(op->cl_dict);
222 return op->cl_dict;
224 if (strcmp(sname, "__bases__") == 0) {
225 Py_INCREF(op->cl_bases);
226 return op->cl_bases;
228 if (strcmp(sname, "__name__") == 0) {
229 if (op->cl_name == NULL)
230 v = Py_None;
231 else
232 v = op->cl_name;
233 Py_INCREF(v);
234 return v;
237 v = class_lookup(op, name, &class);
238 if (v == NULL) {
239 PyErr_Format(PyExc_AttributeError,
240 "class %.50s has no attribute '%.400s'",
241 PyString_AS_STRING(op->cl_name), sname);
242 return NULL;
244 f = TP_DESCR_GET(v->ob_type);
245 if (f == NULL)
246 Py_INCREF(v);
247 else
248 v = f(v, (PyObject *)NULL, (PyObject *)op);
249 return v;
252 static void
253 set_slot(PyObject **slot, PyObject *v)
255 PyObject *temp = *slot;
256 Py_XINCREF(v);
257 *slot = v;
258 Py_XDECREF(temp);
261 static void
262 set_attr_slots(PyClassObject *c)
264 PyClassObject *dummy;
266 set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
267 set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
268 set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
271 static char *
272 set_dict(PyClassObject *c, PyObject *v)
274 if (v == NULL || !PyDict_Check(v))
275 return "__dict__ must be a dictionary object";
276 set_slot(&c->cl_dict, v);
277 set_attr_slots(c);
278 return "";
281 static char *
282 set_bases(PyClassObject *c, PyObject *v)
284 int i, n;
286 if (v == NULL || !PyTuple_Check(v))
287 return "__bases__ must be a tuple object";
288 n = PyTuple_Size(v);
289 for (i = 0; i < n; i++) {
290 PyObject *x = PyTuple_GET_ITEM(v, i);
291 if (!PyClass_Check(x))
292 return "__bases__ items must be classes";
293 if (PyClass_IsSubclass(x, (PyObject *)c))
294 return "a __bases__ item causes an inheritance cycle";
296 set_slot(&c->cl_bases, v);
297 set_attr_slots(c);
298 return "";
301 static char *
302 set_name(PyClassObject *c, PyObject *v)
304 if (v == NULL || !PyString_Check(v))
305 return "__name__ must be a string object";
306 if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
307 return "__name__ must not contain null bytes";
308 set_slot(&c->cl_name, v);
309 return "";
312 static int
313 class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
315 char *sname;
316 if (PyEval_GetRestricted()) {
317 PyErr_SetString(PyExc_RuntimeError,
318 "classes are read-only in restricted mode");
319 return -1;
321 sname = PyString_AsString(name);
322 if (sname[0] == '_' && sname[1] == '_') {
323 int n = PyString_Size(name);
324 if (sname[n-1] == '_' && sname[n-2] == '_') {
325 char *err = NULL;
326 if (strcmp(sname, "__dict__") == 0)
327 err = set_dict(op, v);
328 else if (strcmp(sname, "__bases__") == 0)
329 err = set_bases(op, v);
330 else if (strcmp(sname, "__name__") == 0)
331 err = set_name(op, v);
332 else if (strcmp(sname, "__getattr__") == 0)
333 set_slot(&op->cl_getattr, v);
334 else if (strcmp(sname, "__setattr__") == 0)
335 set_slot(&op->cl_setattr, v);
336 else if (strcmp(sname, "__delattr__") == 0)
337 set_slot(&op->cl_delattr, v);
338 /* For the last three, we fall through to update the
339 dictionary as well. */
340 if (err != NULL) {
341 if (*err == '\0')
342 return 0;
343 PyErr_SetString(PyExc_TypeError, err);
344 return -1;
348 if (v == NULL) {
349 int rv = PyDict_DelItem(op->cl_dict, name);
350 if (rv < 0)
351 PyErr_Format(PyExc_AttributeError,
352 "class %.50s has no attribute '%.400s'",
353 PyString_AS_STRING(op->cl_name), sname);
354 return rv;
356 else
357 return PyDict_SetItem(op->cl_dict, name, v);
360 static PyObject *
361 class_repr(PyClassObject *op)
363 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
364 char *name;
365 if (op->cl_name == NULL || !PyString_Check(op->cl_name))
366 name = "?";
367 else
368 name = PyString_AsString(op->cl_name);
369 if (mod == NULL || !PyString_Check(mod))
370 return PyString_FromFormat("<class ?.%s at %p>", name, op);
371 else
372 return PyString_FromFormat("<class %s.%s at %p>",
373 PyString_AsString(mod),
374 name, op);
377 static PyObject *
378 class_str(PyClassObject *op)
380 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
381 PyObject *name = op->cl_name;
382 PyObject *res;
383 int m, n;
385 if (name == NULL || !PyString_Check(name))
386 return class_repr(op);
387 if (mod == NULL || !PyString_Check(mod)) {
388 Py_INCREF(name);
389 return name;
391 m = PyString_Size(mod);
392 n = PyString_Size(name);
393 res = PyString_FromStringAndSize((char *)NULL, m+1+n);
394 if (res != NULL) {
395 char *s = PyString_AsString(res);
396 memcpy(s, PyString_AsString(mod), m);
397 s += m;
398 *s++ = '.';
399 memcpy(s, PyString_AsString(name), n);
401 return res;
404 static int
405 class_traverse(PyClassObject *o, visitproc visit, void *arg)
407 int err;
408 if (o->cl_bases) {
409 err = visit(o->cl_bases, arg);
410 if (err)
411 return err;
413 if (o->cl_dict) {
414 err = visit(o->cl_dict, arg);
415 if (err)
416 return err;
418 if (o->cl_name) {
419 err = visit(o->cl_name, arg);
420 if (err)
421 return err;
423 if (o->cl_getattr) {
424 err = visit(o->cl_getattr, arg);
425 if (err)
426 return err;
428 if (o->cl_setattr) {
429 err = visit(o->cl_setattr, arg);
430 if (err)
431 return err;
433 if (o->cl_delattr) {
434 err = visit(o->cl_delattr, arg);
435 if (err)
436 return err;
438 return 0;
441 PyTypeObject PyClass_Type = {
442 PyObject_HEAD_INIT(&PyType_Type)
444 "classobj",
445 sizeof(PyClassObject),
447 (destructor)class_dealloc, /* tp_dealloc */
448 0, /* tp_print */
449 0, /* tp_getattr */
450 0, /* tp_setattr */
451 0, /* tp_compare */
452 (reprfunc)class_repr, /* tp_repr */
453 0, /* tp_as_number */
454 0, /* tp_as_sequence */
455 0, /* tp_as_mapping */
456 0, /* tp_hash */
457 PyInstance_New, /* tp_call */
458 (reprfunc)class_str, /* tp_str */
459 (getattrofunc)class_getattr, /* tp_getattro */
460 (setattrofunc)class_setattr, /* tp_setattro */
461 0, /* tp_as_buffer */
462 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
463 class_doc, /* tp_doc */
464 (traverseproc)class_traverse, /* tp_traverse */
465 0, /* tp_clear */
466 0, /* tp_richcompare */
467 0, /* tp_weaklistoffset */
468 0, /* tp_iter */
469 0, /* tp_iternext */
470 0, /* tp_methods */
471 0, /* tp_members */
472 0, /* tp_getset */
473 0, /* tp_base */
474 0, /* tp_dict */
475 0, /* tp_descr_get */
476 0, /* tp_descr_set */
477 0, /* tp_dictoffset */
478 0, /* tp_init */
479 0, /* tp_alloc */
480 class_new, /* tp_new */
484 PyClass_IsSubclass(PyObject *class, PyObject *base)
486 int i, n;
487 PyClassObject *cp;
488 if (class == base)
489 return 1;
490 if (PyTuple_Check(base)) {
491 n = PyTuple_GET_SIZE(base);
492 for (i = 0; i < n; i++) {
493 if (PyClass_IsSubclass(class, PyTuple_GET_ITEM(base, i)))
494 return 1;
496 return 0;
498 if (class == NULL || !PyClass_Check(class))
499 return 0;
500 cp = (PyClassObject *)class;
501 n = PyTuple_Size(cp->cl_bases);
502 for (i = 0; i < n; i++) {
503 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
504 return 1;
506 return 0;
510 /* Instance objects */
512 PyObject *
513 PyInstance_NewRaw(PyObject *klass, PyObject *dict)
515 PyInstanceObject *inst;
517 if (!PyClass_Check(klass)) {
518 PyErr_BadInternalCall();
519 return NULL;
521 if (dict == NULL) {
522 dict = PyDict_New();
523 if (dict == NULL)
524 return NULL;
526 else {
527 if (!PyDict_Check(dict)) {
528 PyErr_BadInternalCall();
529 return NULL;
531 Py_INCREF(dict);
533 inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
534 if (inst == NULL) {
535 Py_DECREF(dict);
536 return NULL;
538 inst->in_weakreflist = NULL;
539 Py_INCREF(klass);
540 inst->in_class = (PyClassObject *)klass;
541 inst->in_dict = dict;
542 _PyObject_GC_TRACK(inst);
543 return (PyObject *)inst;
546 PyObject *
547 PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
549 register PyInstanceObject *inst;
550 PyObject *init;
551 static PyObject *initstr;
553 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
554 if (inst == NULL)
555 return NULL;
556 if (initstr == NULL)
557 initstr = PyString_InternFromString("__init__");
558 init = instance_getattr2(inst, initstr);
559 if (init == NULL) {
560 if (PyErr_Occurred()) {
561 Py_DECREF(inst);
562 return NULL;
564 if ((arg != NULL && (!PyTuple_Check(arg) ||
565 PyTuple_Size(arg) != 0))
566 || (kw != NULL && (!PyDict_Check(kw) ||
567 PyDict_Size(kw) != 0))) {
568 PyErr_SetString(PyExc_TypeError,
569 "this constructor takes no arguments");
570 Py_DECREF(inst);
571 inst = NULL;
574 else {
575 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
576 Py_DECREF(init);
577 if (res == NULL) {
578 Py_DECREF(inst);
579 inst = NULL;
581 else {
582 if (res != Py_None) {
583 PyErr_SetString(PyExc_TypeError,
584 "__init__() should return None");
585 Py_DECREF(inst);
586 inst = NULL;
588 Py_DECREF(res);
591 return (PyObject *)inst;
594 /* Instance methods */
596 PyDoc_STRVAR(instance_doc,
597 "instance(class[, dict])\n\
599 Create an instance without calling its __init__() method.\n\
600 The class must be a classic class.\n\
601 If present, dict must be a dictionary or None.");
603 static PyObject *
604 instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
606 PyObject *klass;
607 PyObject *dict = Py_None;
609 if (!PyArg_ParseTuple(args, "O!|O:instance",
610 &PyClass_Type, &klass, &dict))
611 return NULL;
613 if (dict == Py_None)
614 dict = NULL;
615 else if (!PyDict_Check(dict)) {
616 PyErr_SetString(PyExc_TypeError,
617 "instance() second arg must be dictionary or None");
618 return NULL;
620 return PyInstance_NewRaw(klass, dict);
624 static void
625 instance_dealloc(register PyInstanceObject *inst)
627 PyObject *error_type, *error_value, *error_traceback;
628 PyObject *del;
629 static PyObject *delstr;
631 _PyObject_GC_UNTRACK(inst);
632 if (inst->in_weakreflist != NULL)
633 PyObject_ClearWeakRefs((PyObject *) inst);
635 /* Temporarily resurrect the object. */
636 assert(inst->ob_type == &PyInstance_Type);
637 assert(inst->ob_refcnt == 0);
638 inst->ob_refcnt = 1;
640 /* Save the current exception, if any. */
641 PyErr_Fetch(&error_type, &error_value, &error_traceback);
642 /* Execute __del__ method, if any. */
643 if (delstr == NULL)
644 delstr = PyString_InternFromString("__del__");
645 if ((del = instance_getattr2(inst, delstr)) != NULL) {
646 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
647 if (res == NULL)
648 PyErr_WriteUnraisable(del);
649 else
650 Py_DECREF(res);
651 Py_DECREF(del);
653 /* Restore the saved exception. */
654 PyErr_Restore(error_type, error_value, error_traceback);
656 /* Undo the temporary resurrection; can't use DECREF here, it would
657 * cause a recursive call.
659 assert(inst->ob_refcnt > 0);
660 if (--inst->ob_refcnt == 0) {
661 Py_DECREF(inst->in_class);
662 Py_XDECREF(inst->in_dict);
663 PyObject_GC_Del(inst);
665 else {
666 int refcnt = inst->ob_refcnt;
667 /* __del__ resurrected it! Make it look like the original
668 * Py_DECREF never happened.
670 _Py_NewReference((PyObject *)inst);
671 inst->ob_refcnt = refcnt;
672 _PyObject_GC_TRACK(inst);
673 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
674 * we need to undo that. */
675 _Py_DEC_REFTOTAL;
676 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
677 * object chain, so no more to do there.
678 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
679 * _Py_NewReference bumped tp_allocs: both of those need to be
680 * undone.
682 #ifdef COUNT_ALLOCS
683 --inst->ob_type->tp_frees;
684 --inst->ob_type->tp_allocs;
685 #endif
689 static PyObject *
690 instance_getattr1(register PyInstanceObject *inst, PyObject *name)
692 register PyObject *v;
693 register char *sname = PyString_AsString(name);
694 if (sname[0] == '_' && sname[1] == '_') {
695 if (strcmp(sname, "__dict__") == 0) {
696 if (PyEval_GetRestricted()) {
697 PyErr_SetString(PyExc_RuntimeError,
698 "instance.__dict__ not accessible in restricted mode");
699 return NULL;
701 Py_INCREF(inst->in_dict);
702 return inst->in_dict;
704 if (strcmp(sname, "__class__") == 0) {
705 Py_INCREF(inst->in_class);
706 return (PyObject *)inst->in_class;
709 v = instance_getattr2(inst, name);
710 if (v == NULL && !PyErr_Occurred()) {
711 PyErr_Format(PyExc_AttributeError,
712 "%.50s instance has no attribute '%.400s'",
713 PyString_AS_STRING(inst->in_class->cl_name), sname);
715 return v;
718 static PyObject *
719 instance_getattr2(register PyInstanceObject *inst, PyObject *name)
721 register PyObject *v;
722 PyClassObject *class;
723 descrgetfunc f;
725 v = PyDict_GetItem(inst->in_dict, name);
726 if (v != NULL) {
727 Py_INCREF(v);
728 return v;
730 v = class_lookup(inst->in_class, name, &class);
731 if (v != NULL) {
732 Py_INCREF(v);
733 f = TP_DESCR_GET(v->ob_type);
734 if (f != NULL) {
735 PyObject *w = f(v, (PyObject *)inst,
736 (PyObject *)(inst->in_class));
737 Py_DECREF(v);
738 v = w;
741 return v;
744 static PyObject *
745 instance_getattr(register PyInstanceObject *inst, PyObject *name)
747 register PyObject *func, *res;
748 res = instance_getattr1(inst, name);
749 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
750 PyObject *args;
751 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
752 return NULL;
753 PyErr_Clear();
754 args = PyTuple_Pack(2, inst, name);
755 if (args == NULL)
756 return NULL;
757 res = PyEval_CallObject(func, args);
758 Py_DECREF(args);
760 return res;
763 /* See classobject.h comments: this only does dict lookups, and is always
764 * safe to call.
766 PyObject *
767 _PyInstance_Lookup(PyObject *pinst, PyObject *name)
769 PyObject *v;
770 PyClassObject *class;
771 PyInstanceObject *inst; /* pinst cast to the right type */
773 assert(PyInstance_Check(pinst));
774 inst = (PyInstanceObject *)pinst;
776 assert(PyString_Check(name));
778 v = PyDict_GetItem(inst->in_dict, name);
779 if (v == NULL)
780 v = class_lookup(inst->in_class, name, &class);
781 return v;
784 static int
785 instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
787 if (v == NULL) {
788 int rv = PyDict_DelItem(inst->in_dict, name);
789 if (rv < 0)
790 PyErr_Format(PyExc_AttributeError,
791 "%.50s instance has no attribute '%.400s'",
792 PyString_AS_STRING(inst->in_class->cl_name),
793 PyString_AS_STRING(name));
794 return rv;
796 else
797 return PyDict_SetItem(inst->in_dict, name, v);
800 static int
801 instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
803 PyObject *func, *args, *res, *tmp;
804 char *sname = PyString_AsString(name);
805 if (sname[0] == '_' && sname[1] == '_') {
806 int n = PyString_Size(name);
807 if (sname[n-1] == '_' && sname[n-2] == '_') {
808 if (strcmp(sname, "__dict__") == 0) {
809 if (PyEval_GetRestricted()) {
810 PyErr_SetString(PyExc_RuntimeError,
811 "__dict__ not accessible in restricted mode");
812 return -1;
814 if (v == NULL || !PyDict_Check(v)) {
815 PyErr_SetString(PyExc_TypeError,
816 "__dict__ must be set to a dictionary");
817 return -1;
819 tmp = inst->in_dict;
820 Py_INCREF(v);
821 inst->in_dict = v;
822 Py_DECREF(tmp);
823 return 0;
825 if (strcmp(sname, "__class__") == 0) {
826 if (PyEval_GetRestricted()) {
827 PyErr_SetString(PyExc_RuntimeError,
828 "__class__ not accessible in restricted mode");
829 return -1;
831 if (v == NULL || !PyClass_Check(v)) {
832 PyErr_SetString(PyExc_TypeError,
833 "__class__ must be set to a class");
834 return -1;
836 tmp = (PyObject *)(inst->in_class);
837 Py_INCREF(v);
838 inst->in_class = (PyClassObject *)v;
839 Py_DECREF(tmp);
840 return 0;
844 if (v == NULL)
845 func = inst->in_class->cl_delattr;
846 else
847 func = inst->in_class->cl_setattr;
848 if (func == NULL)
849 return instance_setattr1(inst, name, v);
850 if (v == NULL)
851 args = PyTuple_Pack(2, inst, name);
852 else
853 args = PyTuple_Pack(3, inst, name, v);
854 if (args == NULL)
855 return -1;
856 res = PyEval_CallObject(func, args);
857 Py_DECREF(args);
858 if (res == NULL)
859 return -1;
860 Py_DECREF(res);
861 return 0;
864 static PyObject *
865 instance_repr(PyInstanceObject *inst)
867 PyObject *func;
868 PyObject *res;
869 static PyObject *reprstr;
871 if (reprstr == NULL)
872 reprstr = PyString_InternFromString("__repr__");
873 func = instance_getattr(inst, reprstr);
874 if (func == NULL) {
875 PyObject *classname, *mod;
876 char *cname;
877 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
878 return NULL;
879 PyErr_Clear();
880 classname = inst->in_class->cl_name;
881 mod = PyDict_GetItemString(inst->in_class->cl_dict,
882 "__module__");
883 if (classname != NULL && PyString_Check(classname))
884 cname = PyString_AsString(classname);
885 else
886 cname = "?";
887 if (mod == NULL || !PyString_Check(mod))
888 return PyString_FromFormat("<?.%s instance at %p>",
889 cname, inst);
890 else
891 return PyString_FromFormat("<%s.%s instance at %p>",
892 PyString_AsString(mod),
893 cname, inst);
895 res = PyEval_CallObject(func, (PyObject *)NULL);
896 Py_DECREF(func);
897 return res;
900 static PyObject *
901 instance_str(PyInstanceObject *inst)
903 PyObject *func;
904 PyObject *res;
905 static PyObject *strstr;
907 if (strstr == NULL)
908 strstr = PyString_InternFromString("__str__");
909 func = instance_getattr(inst, strstr);
910 if (func == NULL) {
911 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
912 return NULL;
913 PyErr_Clear();
914 return instance_repr(inst);
916 res = PyEval_CallObject(func, (PyObject *)NULL);
917 Py_DECREF(func);
918 return res;
921 static long
922 instance_hash(PyInstanceObject *inst)
924 PyObject *func;
925 PyObject *res;
926 long outcome;
927 static PyObject *hashstr, *eqstr, *cmpstr;
929 if (hashstr == NULL)
930 hashstr = PyString_InternFromString("__hash__");
931 func = instance_getattr(inst, hashstr);
932 if (func == NULL) {
933 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
934 return -1;
935 PyErr_Clear();
936 /* If there is no __eq__ and no __cmp__ method, we hash on the
937 address. If an __eq__ or __cmp__ method exists, there must
938 be a __hash__. */
939 if (eqstr == NULL)
940 eqstr = PyString_InternFromString("__eq__");
941 func = instance_getattr(inst, eqstr);
942 if (func == NULL) {
943 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
944 return -1;
945 PyErr_Clear();
946 if (cmpstr == NULL)
947 cmpstr = PyString_InternFromString("__cmp__");
948 func = instance_getattr(inst, cmpstr);
949 if (func == NULL) {
950 if (!PyErr_ExceptionMatches(
951 PyExc_AttributeError))
952 return -1;
953 PyErr_Clear();
954 return _Py_HashPointer(inst);
957 Py_XDECREF(func);
958 PyErr_SetString(PyExc_TypeError, "unhashable instance");
959 return -1;
961 res = PyEval_CallObject(func, (PyObject *)NULL);
962 Py_DECREF(func);
963 if (res == NULL)
964 return -1;
965 if (PyInt_Check(res)) {
966 outcome = PyInt_AsLong(res);
967 if (outcome == -1)
968 outcome = -2;
970 else {
971 PyErr_SetString(PyExc_TypeError,
972 "__hash__() should return an int");
973 outcome = -1;
975 Py_DECREF(res);
976 return outcome;
979 static int
980 instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
982 int err;
983 if (o->in_class) {
984 err = visit((PyObject *)(o->in_class), arg);
985 if (err)
986 return err;
988 if (o->in_dict) {
989 err = visit(o->in_dict, arg);
990 if (err)
991 return err;
993 return 0;
996 static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
997 static PyObject *iterstr, *nextstr;
999 static int
1000 instance_length(PyInstanceObject *inst)
1002 PyObject *func;
1003 PyObject *res;
1004 int outcome;
1006 if (lenstr == NULL)
1007 lenstr = PyString_InternFromString("__len__");
1008 func = instance_getattr(inst, lenstr);
1009 if (func == NULL)
1010 return -1;
1011 res = PyEval_CallObject(func, (PyObject *)NULL);
1012 Py_DECREF(func);
1013 if (res == NULL)
1014 return -1;
1015 if (PyInt_Check(res)) {
1016 long temp = PyInt_AsLong(res);
1017 outcome = (int)temp;
1018 #if SIZEOF_INT < SIZEOF_LONG
1019 /* Overflow check -- range of PyInt is more than C int */
1020 if (outcome != temp) {
1021 PyErr_SetString(PyExc_OverflowError,
1022 "__len__() should return 0 <= outcome < 2**31");
1023 outcome = -1;
1025 else
1026 #endif
1027 if (outcome < 0)
1028 PyErr_SetString(PyExc_ValueError,
1029 "__len__() should return >= 0");
1031 else {
1032 PyErr_SetString(PyExc_TypeError,
1033 "__len__() should return an int");
1034 outcome = -1;
1036 Py_DECREF(res);
1037 return outcome;
1040 static PyObject *
1041 instance_subscript(PyInstanceObject *inst, PyObject *key)
1043 PyObject *func;
1044 PyObject *arg;
1045 PyObject *res;
1047 if (getitemstr == NULL)
1048 getitemstr = PyString_InternFromString("__getitem__");
1049 func = instance_getattr(inst, getitemstr);
1050 if (func == NULL)
1051 return NULL;
1052 arg = PyTuple_Pack(1, key);
1053 if (arg == NULL) {
1054 Py_DECREF(func);
1055 return NULL;
1057 res = PyEval_CallObject(func, arg);
1058 Py_DECREF(func);
1059 Py_DECREF(arg);
1060 return res;
1063 static int
1064 instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1066 PyObject *func;
1067 PyObject *arg;
1068 PyObject *res;
1070 if (value == NULL) {
1071 if (delitemstr == NULL)
1072 delitemstr = PyString_InternFromString("__delitem__");
1073 func = instance_getattr(inst, delitemstr);
1075 else {
1076 if (setitemstr == NULL)
1077 setitemstr = PyString_InternFromString("__setitem__");
1078 func = instance_getattr(inst, setitemstr);
1080 if (func == NULL)
1081 return -1;
1082 if (value == NULL)
1083 arg = PyTuple_Pack(1, key);
1084 else
1085 arg = PyTuple_Pack(2, key, value);
1086 if (arg == NULL) {
1087 Py_DECREF(func);
1088 return -1;
1090 res = PyEval_CallObject(func, arg);
1091 Py_DECREF(func);
1092 Py_DECREF(arg);
1093 if (res == NULL)
1094 return -1;
1095 Py_DECREF(res);
1096 return 0;
1099 static PyMappingMethods instance_as_mapping = {
1100 (inquiry)instance_length, /* mp_length */
1101 (binaryfunc)instance_subscript, /* mp_subscript */
1102 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
1105 static PyObject *
1106 instance_item(PyInstanceObject *inst, int i)
1108 PyObject *func, *arg, *res;
1110 if (getitemstr == NULL)
1111 getitemstr = PyString_InternFromString("__getitem__");
1112 func = instance_getattr(inst, getitemstr);
1113 if (func == NULL)
1114 return NULL;
1115 arg = Py_BuildValue("(i)", i);
1116 if (arg == NULL) {
1117 Py_DECREF(func);
1118 return NULL;
1120 res = PyEval_CallObject(func, arg);
1121 Py_DECREF(func);
1122 Py_DECREF(arg);
1123 return res;
1126 static PyObject *
1127 sliceobj_from_intint(int i, int j)
1129 PyObject *start, *end, *res;
1131 start = PyInt_FromLong((long)i);
1132 if (!start)
1133 return NULL;
1135 end = PyInt_FromLong((long)j);
1136 if (!end) {
1137 Py_DECREF(start);
1138 return NULL;
1140 res = PySlice_New(start, end, NULL);
1141 Py_DECREF(start);
1142 Py_DECREF(end);
1143 return res;
1147 static PyObject *
1148 instance_slice(PyInstanceObject *inst, int i, int j)
1150 PyObject *func, *arg, *res;
1151 static PyObject *getslicestr;
1153 if (getslicestr == NULL)
1154 getslicestr = PyString_InternFromString("__getslice__");
1155 func = instance_getattr(inst, getslicestr);
1157 if (func == NULL) {
1158 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1159 return NULL;
1160 PyErr_Clear();
1162 if (getitemstr == NULL)
1163 getitemstr = PyString_InternFromString("__getitem__");
1164 func = instance_getattr(inst, getitemstr);
1165 if (func == NULL)
1166 return NULL;
1167 arg = Py_BuildValue("(N)", sliceobj_from_intint(i, j));
1168 } else
1169 arg = Py_BuildValue("(ii)", i, j);
1171 if (arg == NULL) {
1172 Py_DECREF(func);
1173 return NULL;
1175 res = PyEval_CallObject(func, arg);
1176 Py_DECREF(func);
1177 Py_DECREF(arg);
1178 return res;
1181 static int
1182 instance_ass_item(PyInstanceObject *inst, int i, PyObject *item)
1184 PyObject *func, *arg, *res;
1186 if (item == NULL) {
1187 if (delitemstr == NULL)
1188 delitemstr = PyString_InternFromString("__delitem__");
1189 func = instance_getattr(inst, delitemstr);
1191 else {
1192 if (setitemstr == NULL)
1193 setitemstr = PyString_InternFromString("__setitem__");
1194 func = instance_getattr(inst, setitemstr);
1196 if (func == NULL)
1197 return -1;
1198 if (item == NULL)
1199 arg = Py_BuildValue("i", i);
1200 else
1201 arg = Py_BuildValue("(iO)", i, item);
1202 if (arg == NULL) {
1203 Py_DECREF(func);
1204 return -1;
1206 res = PyEval_CallObject(func, arg);
1207 Py_DECREF(func);
1208 Py_DECREF(arg);
1209 if (res == NULL)
1210 return -1;
1211 Py_DECREF(res);
1212 return 0;
1215 static int
1216 instance_ass_slice(PyInstanceObject *inst, int i, int j, PyObject *value)
1218 PyObject *func, *arg, *res;
1219 static PyObject *setslicestr, *delslicestr;
1221 if (value == NULL) {
1222 if (delslicestr == NULL)
1223 delslicestr =
1224 PyString_InternFromString("__delslice__");
1225 func = instance_getattr(inst, delslicestr);
1226 if (func == NULL) {
1227 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1228 return -1;
1229 PyErr_Clear();
1230 if (delitemstr == NULL)
1231 delitemstr =
1232 PyString_InternFromString("__delitem__");
1233 func = instance_getattr(inst, delitemstr);
1234 if (func == NULL)
1235 return -1;
1237 arg = Py_BuildValue("(N)",
1238 sliceobj_from_intint(i, j));
1239 } else
1240 arg = Py_BuildValue("(ii)", i, j);
1242 else {
1243 if (setslicestr == NULL)
1244 setslicestr =
1245 PyString_InternFromString("__setslice__");
1246 func = instance_getattr(inst, setslicestr);
1247 if (func == NULL) {
1248 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1249 return -1;
1250 PyErr_Clear();
1251 if (setitemstr == NULL)
1252 setitemstr =
1253 PyString_InternFromString("__setitem__");
1254 func = instance_getattr(inst, setitemstr);
1255 if (func == NULL)
1256 return -1;
1258 arg = Py_BuildValue("(NO)",
1259 sliceobj_from_intint(i, j), value);
1260 } else
1261 arg = Py_BuildValue("(iiO)", i, j, value);
1263 if (arg == NULL) {
1264 Py_DECREF(func);
1265 return -1;
1267 res = PyEval_CallObject(func, arg);
1268 Py_DECREF(func);
1269 Py_DECREF(arg);
1270 if (res == NULL)
1271 return -1;
1272 Py_DECREF(res);
1273 return 0;
1276 static int
1277 instance_contains(PyInstanceObject *inst, PyObject *member)
1279 static PyObject *__contains__;
1280 PyObject *func;
1282 /* Try __contains__ first.
1283 * If that can't be done, try iterator-based searching.
1286 if(__contains__ == NULL) {
1287 __contains__ = PyString_InternFromString("__contains__");
1288 if(__contains__ == NULL)
1289 return -1;
1291 func = instance_getattr(inst, __contains__);
1292 if (func) {
1293 PyObject *res;
1294 int ret;
1295 PyObject *arg = PyTuple_Pack(1, member);
1296 if(arg == NULL) {
1297 Py_DECREF(func);
1298 return -1;
1300 res = PyEval_CallObject(func, arg);
1301 Py_DECREF(func);
1302 Py_DECREF(arg);
1303 if(res == NULL)
1304 return -1;
1305 ret = PyObject_IsTrue(res);
1306 Py_DECREF(res);
1307 return ret;
1310 /* Couldn't find __contains__. */
1311 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1312 /* Assume the failure was simply due to that there is no
1313 * __contains__ attribute, and try iterating instead.
1315 PyErr_Clear();
1316 return _PySequence_IterSearch((PyObject *)inst, member,
1317 PY_ITERSEARCH_CONTAINS);
1319 else
1320 return -1;
1323 static PySequenceMethods
1324 instance_as_sequence = {
1325 (inquiry)instance_length, /* sq_length */
1326 0, /* sq_concat */
1327 0, /* sq_repeat */
1328 (intargfunc)instance_item, /* sq_item */
1329 (intintargfunc)instance_slice, /* sq_slice */
1330 (intobjargproc)instance_ass_item, /* sq_ass_item */
1331 (intintobjargproc)instance_ass_slice, /* sq_ass_slice */
1332 (objobjproc)instance_contains, /* sq_contains */
1335 static PyObject *
1336 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1338 PyObject *func, *res;
1340 if ((func = instance_getattr(self, methodname)) == NULL)
1341 return NULL;
1342 res = PyEval_CallObject(func, (PyObject *)NULL);
1343 Py_DECREF(func);
1344 return res;
1347 static PyObject *
1348 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1350 PyObject *result;
1351 PyObject *args;
1352 PyObject *func = PyObject_GetAttrString(v, opname);
1353 if (func == NULL) {
1354 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1355 return NULL;
1356 PyErr_Clear();
1357 Py_INCREF(Py_NotImplemented);
1358 return Py_NotImplemented;
1360 args = PyTuple_Pack(1, w);
1361 if (args == NULL) {
1362 Py_DECREF(func);
1363 return NULL;
1365 result = PyEval_CallObject(func, args);
1366 Py_DECREF(args);
1367 Py_DECREF(func);
1368 return result;
1372 static PyObject *coerce_obj;
1374 /* Try one half of a binary operator involving a class instance. */
1375 static PyObject *
1376 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1377 int swapped)
1379 PyObject *args;
1380 PyObject *coercefunc;
1381 PyObject *coerced = NULL;
1382 PyObject *v1;
1383 PyObject *result;
1385 if (!PyInstance_Check(v)) {
1386 Py_INCREF(Py_NotImplemented);
1387 return Py_NotImplemented;
1390 if (coerce_obj == NULL) {
1391 coerce_obj = PyString_InternFromString("__coerce__");
1392 if (coerce_obj == NULL)
1393 return NULL;
1395 coercefunc = PyObject_GetAttr(v, coerce_obj);
1396 if (coercefunc == NULL) {
1397 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1398 return NULL;
1399 PyErr_Clear();
1400 return generic_binary_op(v, w, opname);
1403 args = PyTuple_Pack(1, w);
1404 if (args == NULL) {
1405 Py_DECREF(coercefunc);
1406 return NULL;
1408 coerced = PyEval_CallObject(coercefunc, args);
1409 Py_DECREF(args);
1410 Py_DECREF(coercefunc);
1411 if (coerced == NULL) {
1412 return NULL;
1414 if (coerced == Py_None || coerced == Py_NotImplemented) {
1415 Py_DECREF(coerced);
1416 return generic_binary_op(v, w, opname);
1418 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1419 Py_DECREF(coerced);
1420 PyErr_SetString(PyExc_TypeError,
1421 "coercion should return None or 2-tuple");
1422 return NULL;
1424 v1 = PyTuple_GetItem(coerced, 0);
1425 w = PyTuple_GetItem(coerced, 1);
1426 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1427 /* prevent recursion if __coerce__ returns self as the first
1428 * argument */
1429 result = generic_binary_op(v1, w, opname);
1430 } else {
1431 if (swapped)
1432 result = (thisfunc)(w, v1);
1433 else
1434 result = (thisfunc)(v1, w);
1436 Py_DECREF(coerced);
1437 return result;
1440 /* Implement a binary operator involving at least one class instance. */
1441 static PyObject *
1442 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1443 binaryfunc thisfunc)
1445 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1446 if (result == Py_NotImplemented) {
1447 Py_DECREF(result);
1448 result = half_binop(w, v, ropname, thisfunc, 1);
1450 return result;
1453 static PyObject *
1454 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1455 char *ropname, binaryfunc thisfunc)
1457 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1458 if (result == Py_NotImplemented) {
1459 Py_DECREF(result);
1460 result = do_binop(v, w, opname, ropname, thisfunc);
1462 return result;
1465 static int
1466 instance_coerce(PyObject **pv, PyObject **pw)
1468 PyObject *v = *pv;
1469 PyObject *w = *pw;
1470 PyObject *coercefunc;
1471 PyObject *args;
1472 PyObject *coerced;
1474 if (coerce_obj == NULL) {
1475 coerce_obj = PyString_InternFromString("__coerce__");
1476 if (coerce_obj == NULL)
1477 return -1;
1479 coercefunc = PyObject_GetAttr(v, coerce_obj);
1480 if (coercefunc == NULL) {
1481 /* No __coerce__ method */
1482 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1483 return -1;
1484 PyErr_Clear();
1485 return 1;
1487 /* Has __coerce__ method: call it */
1488 args = PyTuple_Pack(1, w);
1489 if (args == NULL) {
1490 return -1;
1492 coerced = PyEval_CallObject(coercefunc, args);
1493 Py_DECREF(args);
1494 Py_DECREF(coercefunc);
1495 if (coerced == NULL) {
1496 /* __coerce__ call raised an exception */
1497 return -1;
1499 if (coerced == Py_None || coerced == Py_NotImplemented) {
1500 /* __coerce__ says "I can't do it" */
1501 Py_DECREF(coerced);
1502 return 1;
1504 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1505 /* __coerce__ return value is malformed */
1506 Py_DECREF(coerced);
1507 PyErr_SetString(PyExc_TypeError,
1508 "coercion should return None or 2-tuple");
1509 return -1;
1511 /* __coerce__ returned two new values */
1512 *pv = PyTuple_GetItem(coerced, 0);
1513 *pw = PyTuple_GetItem(coerced, 1);
1514 Py_INCREF(*pv);
1515 Py_INCREF(*pw);
1516 Py_DECREF(coerced);
1517 return 0;
1520 #define UNARY(funcname, methodname) \
1521 static PyObject *funcname(PyInstanceObject *self) { \
1522 static PyObject *o; \
1523 if (o == NULL) o = PyString_InternFromString(methodname); \
1524 return generic_unary_op(self, o); \
1527 #define BINARY(f, m, n) \
1528 static PyObject *f(PyObject *v, PyObject *w) { \
1529 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1532 #define BINARY_INPLACE(f, m, n) \
1533 static PyObject *f(PyObject *v, PyObject *w) { \
1534 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1535 "__r" m "__", n); \
1538 UNARY(instance_neg, "__neg__")
1539 UNARY(instance_pos, "__pos__")
1540 UNARY(instance_abs, "__abs__")
1542 BINARY(instance_or, "or", PyNumber_Or)
1543 BINARY(instance_and, "and", PyNumber_And)
1544 BINARY(instance_xor, "xor", PyNumber_Xor)
1545 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1546 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1547 BINARY(instance_add, "add", PyNumber_Add)
1548 BINARY(instance_sub, "sub", PyNumber_Subtract)
1549 BINARY(instance_mul, "mul", PyNumber_Multiply)
1550 BINARY(instance_div, "div", PyNumber_Divide)
1551 BINARY(instance_mod, "mod", PyNumber_Remainder)
1552 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1553 BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1554 BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1556 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1557 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1558 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1559 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1560 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1561 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1562 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1563 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1564 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1565 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1566 BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1567 BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1569 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1570 -2 for an exception;
1571 -1 if v < w;
1572 0 if v == w;
1573 1 if v > w;
1574 2 if this particular 3-way comparison is not implemented or undefined.
1576 static int
1577 half_cmp(PyObject *v, PyObject *w)
1579 static PyObject *cmp_obj;
1580 PyObject *args;
1581 PyObject *cmp_func;
1582 PyObject *result;
1583 long l;
1585 assert(PyInstance_Check(v));
1587 if (cmp_obj == NULL) {
1588 cmp_obj = PyString_InternFromString("__cmp__");
1589 if (cmp_obj == NULL)
1590 return -2;
1593 cmp_func = PyObject_GetAttr(v, cmp_obj);
1594 if (cmp_func == NULL) {
1595 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1596 return -2;
1597 PyErr_Clear();
1598 return 2;
1601 args = PyTuple_Pack(1, w);
1602 if (args == NULL) {
1603 Py_DECREF(cmp_func);
1604 return -2;
1607 result = PyEval_CallObject(cmp_func, args);
1608 Py_DECREF(args);
1609 Py_DECREF(cmp_func);
1611 if (result == NULL)
1612 return -2;
1614 if (result == Py_NotImplemented) {
1615 Py_DECREF(result);
1616 return 2;
1619 l = PyInt_AsLong(result);
1620 Py_DECREF(result);
1621 if (l == -1 && PyErr_Occurred()) {
1622 PyErr_SetString(PyExc_TypeError,
1623 "comparison did not return an int");
1624 return -2;
1627 return l < 0 ? -1 : l > 0 ? 1 : 0;
1630 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1631 We first try a coercion. Return:
1632 -2 for an exception;
1633 -1 if v < w;
1634 0 if v == w;
1635 1 if v > w;
1636 2 if this particular 3-way comparison is not implemented or undefined.
1637 THIS IS ONLY CALLED FROM object.c!
1639 static int
1640 instance_compare(PyObject *v, PyObject *w)
1642 int c;
1644 c = PyNumber_CoerceEx(&v, &w);
1645 if (c < 0)
1646 return -2;
1647 if (c == 0) {
1648 /* If neither is now an instance, use regular comparison */
1649 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1650 c = PyObject_Compare(v, w);
1651 Py_DECREF(v);
1652 Py_DECREF(w);
1653 if (PyErr_Occurred())
1654 return -2;
1655 return c < 0 ? -1 : c > 0 ? 1 : 0;
1658 else {
1659 /* The coercion didn't do anything.
1660 Treat this the same as returning v and w unchanged. */
1661 Py_INCREF(v);
1662 Py_INCREF(w);
1665 if (PyInstance_Check(v)) {
1666 c = half_cmp(v, w);
1667 if (c <= 1) {
1668 Py_DECREF(v);
1669 Py_DECREF(w);
1670 return c;
1673 if (PyInstance_Check(w)) {
1674 c = half_cmp(w, v);
1675 if (c <= 1) {
1676 Py_DECREF(v);
1677 Py_DECREF(w);
1678 if (c >= -1)
1679 c = -c;
1680 return c;
1683 Py_DECREF(v);
1684 Py_DECREF(w);
1685 return 2;
1688 static int
1689 instance_nonzero(PyInstanceObject *self)
1691 PyObject *func, *res;
1692 long outcome;
1693 static PyObject *nonzerostr;
1695 if (nonzerostr == NULL)
1696 nonzerostr = PyString_InternFromString("__nonzero__");
1697 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1698 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1699 return -1;
1700 PyErr_Clear();
1701 if (lenstr == NULL)
1702 lenstr = PyString_InternFromString("__len__");
1703 if ((func = instance_getattr(self, lenstr)) == NULL) {
1704 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1705 return -1;
1706 PyErr_Clear();
1707 /* Fall back to the default behavior:
1708 all instances are nonzero */
1709 return 1;
1712 res = PyEval_CallObject(func, (PyObject *)NULL);
1713 Py_DECREF(func);
1714 if (res == NULL)
1715 return -1;
1716 if (!PyInt_Check(res)) {
1717 Py_DECREF(res);
1718 PyErr_SetString(PyExc_TypeError,
1719 "__nonzero__ should return an int");
1720 return -1;
1722 outcome = PyInt_AsLong(res);
1723 Py_DECREF(res);
1724 if (outcome < 0) {
1725 PyErr_SetString(PyExc_ValueError,
1726 "__nonzero__ should return >= 0");
1727 return -1;
1729 return outcome > 0;
1732 UNARY(instance_invert, "__invert__")
1733 UNARY(instance_int, "__int__")
1734 UNARY(instance_long, "__long__")
1735 UNARY(instance_float, "__float__")
1736 UNARY(instance_oct, "__oct__")
1737 UNARY(instance_hex, "__hex__")
1739 static PyObject *
1740 bin_power(PyObject *v, PyObject *w)
1742 return PyNumber_Power(v, w, Py_None);
1745 /* This version is for ternary calls only (z != None) */
1746 static PyObject *
1747 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1749 if (z == Py_None) {
1750 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1752 else {
1753 PyObject *func;
1754 PyObject *args;
1755 PyObject *result;
1757 /* XXX Doesn't do coercions... */
1758 func = PyObject_GetAttrString(v, "__pow__");
1759 if (func == NULL)
1760 return NULL;
1761 args = PyTuple_Pack(2, w, z);
1762 if (args == NULL) {
1763 Py_DECREF(func);
1764 return NULL;
1766 result = PyEval_CallObject(func, args);
1767 Py_DECREF(func);
1768 Py_DECREF(args);
1769 return result;
1773 static PyObject *
1774 bin_inplace_power(PyObject *v, PyObject *w)
1776 return PyNumber_InPlacePower(v, w, Py_None);
1780 static PyObject *
1781 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1783 if (z == Py_None) {
1784 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1785 "__rpow__", bin_inplace_power);
1787 else {
1788 /* XXX Doesn't do coercions... */
1789 PyObject *func;
1790 PyObject *args;
1791 PyObject *result;
1793 func = PyObject_GetAttrString(v, "__ipow__");
1794 if (func == NULL) {
1795 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1796 return NULL;
1797 PyErr_Clear();
1798 return instance_pow(v, w, z);
1800 args = PyTuple_Pack(2, w, z);
1801 if (args == NULL) {
1802 Py_DECREF(func);
1803 return NULL;
1805 result = PyEval_CallObject(func, args);
1806 Py_DECREF(func);
1807 Py_DECREF(args);
1808 return result;
1813 /* Map rich comparison operators to their __xx__ namesakes */
1814 #define NAME_OPS 6
1815 static PyObject **name_op = NULL;
1817 static int
1818 init_name_op(void)
1820 int i;
1821 char *_name_op[] = {
1822 "__lt__",
1823 "__le__",
1824 "__eq__",
1825 "__ne__",
1826 "__gt__",
1827 "__ge__",
1830 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1831 if (name_op == NULL)
1832 return -1;
1833 for (i = 0; i < NAME_OPS; ++i) {
1834 name_op[i] = PyString_InternFromString(_name_op[i]);
1835 if (name_op[i] == NULL)
1836 return -1;
1838 return 0;
1841 static PyObject *
1842 half_richcompare(PyObject *v, PyObject *w, int op)
1844 PyObject *method;
1845 PyObject *args;
1846 PyObject *res;
1848 assert(PyInstance_Check(v));
1850 if (name_op == NULL) {
1851 if (init_name_op() < 0)
1852 return NULL;
1854 /* If the instance doesn't define an __getattr__ method, use
1855 instance_getattr2 directly because it will not set an
1856 exception on failure. */
1857 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1858 method = instance_getattr2((PyInstanceObject *)v,
1859 name_op[op]);
1860 else
1861 method = PyObject_GetAttr(v, name_op[op]);
1862 if (method == NULL) {
1863 if (PyErr_Occurred()) {
1864 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1865 return NULL;
1866 PyErr_Clear();
1868 res = Py_NotImplemented;
1869 Py_INCREF(res);
1870 return res;
1873 args = PyTuple_Pack(1, w);
1874 if (args == NULL) {
1875 Py_DECREF(method);
1876 return NULL;
1879 res = PyEval_CallObject(method, args);
1880 Py_DECREF(args);
1881 Py_DECREF(method);
1883 return res;
1886 static PyObject *
1887 instance_richcompare(PyObject *v, PyObject *w, int op)
1889 PyObject *res;
1891 if (PyInstance_Check(v)) {
1892 res = half_richcompare(v, w, op);
1893 if (res != Py_NotImplemented)
1894 return res;
1895 Py_DECREF(res);
1898 if (PyInstance_Check(w)) {
1899 res = half_richcompare(w, v, _Py_SwappedOp[op]);
1900 if (res != Py_NotImplemented)
1901 return res;
1902 Py_DECREF(res);
1905 Py_INCREF(Py_NotImplemented);
1906 return Py_NotImplemented;
1910 /* Get the iterator */
1911 static PyObject *
1912 instance_getiter(PyInstanceObject *self)
1914 PyObject *func;
1916 if (iterstr == NULL) {
1917 iterstr = PyString_InternFromString("__iter__");
1918 if (iterstr == NULL)
1919 return NULL;
1921 if (getitemstr == NULL) {
1922 getitemstr = PyString_InternFromString("__getitem__");
1923 if (getitemstr == NULL)
1924 return NULL;
1927 if ((func = instance_getattr(self, iterstr)) != NULL) {
1928 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1929 Py_DECREF(func);
1930 if (res != NULL && !PyIter_Check(res)) {
1931 PyErr_Format(PyExc_TypeError,
1932 "__iter__ returned non-iterator "
1933 "of type '%.100s'",
1934 res->ob_type->tp_name);
1935 Py_DECREF(res);
1936 res = NULL;
1938 return res;
1940 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1941 return NULL;
1942 PyErr_Clear();
1943 if ((func = instance_getattr(self, getitemstr)) == NULL) {
1944 PyErr_SetString(PyExc_TypeError,
1945 "iteration over non-sequence");
1946 return NULL;
1948 Py_DECREF(func);
1949 return PySeqIter_New((PyObject *)self);
1953 /* Call the iterator's next */
1954 static PyObject *
1955 instance_iternext(PyInstanceObject *self)
1957 PyObject *func;
1959 if (nextstr == NULL)
1960 nextstr = PyString_InternFromString("next");
1962 if ((func = instance_getattr(self, nextstr)) != NULL) {
1963 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1964 Py_DECREF(func);
1965 if (res != NULL) {
1966 return res;
1968 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
1969 PyErr_Clear();
1970 return NULL;
1972 return NULL;
1974 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
1975 return NULL;
1978 static PyObject *
1979 instance_call(PyObject *func, PyObject *arg, PyObject *kw)
1981 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
1982 if (call == NULL) {
1983 PyInstanceObject *inst = (PyInstanceObject*) func;
1984 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1985 return NULL;
1986 PyErr_Clear();
1987 PyErr_Format(PyExc_AttributeError,
1988 "%.200s instance has no __call__ method",
1989 PyString_AsString(inst->in_class->cl_name));
1990 return NULL;
1992 /* We must check and increment the recursion depth here. Scenario:
1993 class A:
1994 pass
1995 A.__call__ = A() # that's right
1996 a = A() # ok
1997 a() # infinite recursion
1998 This bounces between instance_call() and PyObject_Call() without
1999 ever hitting eval_frame() (which has the main recursion check). */
2000 if (Py_EnterRecursiveCall(" in __call__")) {
2001 res = NULL;
2003 else {
2004 res = PyObject_Call(call, arg, kw);
2005 Py_LeaveRecursiveCall();
2007 Py_DECREF(call);
2008 return res;
2012 static PyNumberMethods instance_as_number = {
2013 (binaryfunc)instance_add, /* nb_add */
2014 (binaryfunc)instance_sub, /* nb_subtract */
2015 (binaryfunc)instance_mul, /* nb_multiply */
2016 (binaryfunc)instance_div, /* nb_divide */
2017 (binaryfunc)instance_mod, /* nb_remainder */
2018 (binaryfunc)instance_divmod, /* nb_divmod */
2019 (ternaryfunc)instance_pow, /* nb_power */
2020 (unaryfunc)instance_neg, /* nb_negative */
2021 (unaryfunc)instance_pos, /* nb_positive */
2022 (unaryfunc)instance_abs, /* nb_absolute */
2023 (inquiry)instance_nonzero, /* nb_nonzero */
2024 (unaryfunc)instance_invert, /* nb_invert */
2025 (binaryfunc)instance_lshift, /* nb_lshift */
2026 (binaryfunc)instance_rshift, /* nb_rshift */
2027 (binaryfunc)instance_and, /* nb_and */
2028 (binaryfunc)instance_xor, /* nb_xor */
2029 (binaryfunc)instance_or, /* nb_or */
2030 (coercion)instance_coerce, /* nb_coerce */
2031 (unaryfunc)instance_int, /* nb_int */
2032 (unaryfunc)instance_long, /* nb_long */
2033 (unaryfunc)instance_float, /* nb_float */
2034 (unaryfunc)instance_oct, /* nb_oct */
2035 (unaryfunc)instance_hex, /* nb_hex */
2036 (binaryfunc)instance_iadd, /* nb_inplace_add */
2037 (binaryfunc)instance_isub, /* nb_inplace_subtract */
2038 (binaryfunc)instance_imul, /* nb_inplace_multiply */
2039 (binaryfunc)instance_idiv, /* nb_inplace_divide */
2040 (binaryfunc)instance_imod, /* nb_inplace_remainder */
2041 (ternaryfunc)instance_ipow, /* nb_inplace_power */
2042 (binaryfunc)instance_ilshift, /* nb_inplace_lshift */
2043 (binaryfunc)instance_irshift, /* nb_inplace_rshift */
2044 (binaryfunc)instance_iand, /* nb_inplace_and */
2045 (binaryfunc)instance_ixor, /* nb_inplace_xor */
2046 (binaryfunc)instance_ior, /* nb_inplace_or */
2047 (binaryfunc)instance_floordiv, /* nb_floor_divide */
2048 (binaryfunc)instance_truediv, /* nb_true_divide */
2049 (binaryfunc)instance_ifloordiv, /* nb_inplace_floor_divide */
2050 (binaryfunc)instance_itruediv, /* nb_inplace_true_divide */
2053 PyTypeObject PyInstance_Type = {
2054 PyObject_HEAD_INIT(&PyType_Type)
2056 "instance",
2057 sizeof(PyInstanceObject),
2059 (destructor)instance_dealloc, /* tp_dealloc */
2060 0, /* tp_print */
2061 0, /* tp_getattr */
2062 0, /* tp_setattr */
2063 instance_compare, /* tp_compare */
2064 (reprfunc)instance_repr, /* tp_repr */
2065 &instance_as_number, /* tp_as_number */
2066 &instance_as_sequence, /* tp_as_sequence */
2067 &instance_as_mapping, /* tp_as_mapping */
2068 (hashfunc)instance_hash, /* tp_hash */
2069 instance_call, /* tp_call */
2070 (reprfunc)instance_str, /* tp_str */
2071 (getattrofunc)instance_getattr, /* tp_getattro */
2072 (setattrofunc)instance_setattr, /* tp_setattro */
2073 0, /* tp_as_buffer */
2074 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2075 instance_doc, /* tp_doc */
2076 (traverseproc)instance_traverse, /* tp_traverse */
2077 0, /* tp_clear */
2078 instance_richcompare, /* tp_richcompare */
2079 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2080 (getiterfunc)instance_getiter, /* tp_iter */
2081 (iternextfunc)instance_iternext, /* tp_iternext */
2082 0, /* tp_methods */
2083 0, /* tp_members */
2084 0, /* tp_getset */
2085 0, /* tp_base */
2086 0, /* tp_dict */
2087 0, /* tp_descr_get */
2088 0, /* tp_descr_set */
2089 0, /* tp_dictoffset */
2090 0, /* tp_init */
2091 0, /* tp_alloc */
2092 instance_new, /* tp_new */
2096 /* Instance method objects are used for two purposes:
2097 (a) as bound instance methods (returned by instancename.methodname)
2098 (b) as unbound methods (returned by ClassName.methodname)
2099 In case (b), im_self is NULL
2102 static PyMethodObject *free_list;
2104 PyObject *
2105 PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
2107 register PyMethodObject *im;
2108 if (!PyCallable_Check(func)) {
2109 PyErr_BadInternalCall();
2110 return NULL;
2112 im = free_list;
2113 if (im != NULL) {
2114 free_list = (PyMethodObject *)(im->im_self);
2115 PyObject_INIT(im, &PyMethod_Type);
2117 else {
2118 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2119 if (im == NULL)
2120 return NULL;
2122 im->im_weakreflist = NULL;
2123 Py_INCREF(func);
2124 im->im_func = func;
2125 Py_XINCREF(self);
2126 im->im_self = self;
2127 Py_XINCREF(class);
2128 im->im_class = class;
2129 _PyObject_GC_TRACK(im);
2130 return (PyObject *)im;
2133 /* Descriptors for PyMethod attributes */
2135 /* im_class, im_func and im_self are stored in the PyMethod object */
2137 #define OFF(x) offsetof(PyMethodObject, x)
2139 static PyMemberDef instancemethod_memberlist[] = {
2140 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2141 "the class associated with a method"},
2142 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2143 "the function (or other callable) implementing a method"},
2144 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2145 "the instance to which a method is bound; None for unbound methods"},
2146 {NULL} /* Sentinel */
2149 /* Christian Tismer argued convincingly that method attributes should
2150 (nearly) always override function attributes.
2151 The one exception is __doc__; there's a default __doc__ which
2152 should only be used for the class, not for instances */
2154 static PyObject *
2155 instancemethod_get_doc(PyMethodObject *im, void *context)
2157 static PyObject *docstr;
2158 if (docstr == NULL) {
2159 docstr= PyString_InternFromString("__doc__");
2160 if (docstr == NULL)
2161 return NULL;
2163 return PyObject_GetAttr(im->im_func, docstr);
2166 static PyGetSetDef instancemethod_getset[] = {
2167 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2171 static PyObject *
2172 instancemethod_getattro(PyObject *obj, PyObject *name)
2174 PyMethodObject *im = (PyMethodObject *)obj;
2175 PyTypeObject *tp = obj->ob_type;
2176 PyObject *descr = NULL;
2178 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2179 if (tp->tp_dict == NULL) {
2180 if (PyType_Ready(tp) < 0)
2181 return NULL;
2183 descr = _PyType_Lookup(tp, name);
2186 if (descr != NULL) {
2187 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
2188 if (f != NULL)
2189 return f(descr, obj, (PyObject *)obj->ob_type);
2190 else {
2191 Py_INCREF(descr);
2192 return descr;
2196 return PyObject_GetAttr(im->im_func, name);
2199 PyDoc_STRVAR(instancemethod_doc,
2200 "instancemethod(function, instance, class)\n\
2202 Create an instance method object.");
2204 static PyObject *
2205 instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2207 PyObject *func;
2208 PyObject *self;
2209 PyObject *classObj = NULL;
2211 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2212 &func, &self, &classObj))
2213 return NULL;
2214 if (!PyCallable_Check(func)) {
2215 PyErr_SetString(PyExc_TypeError,
2216 "first argument must be callable");
2217 return NULL;
2219 if (self == Py_None)
2220 self = NULL;
2221 if (self == NULL && classObj == NULL) {
2222 PyErr_SetString(PyExc_TypeError,
2223 "unbound methods must have non-NULL im_class");
2224 return NULL;
2227 return PyMethod_New(func, self, classObj);
2230 static void
2231 instancemethod_dealloc(register PyMethodObject *im)
2233 _PyObject_GC_UNTRACK(im);
2234 if (im->im_weakreflist != NULL)
2235 PyObject_ClearWeakRefs((PyObject *)im);
2236 Py_DECREF(im->im_func);
2237 Py_XDECREF(im->im_self);
2238 Py_XDECREF(im->im_class);
2239 im->im_self = (PyObject *)free_list;
2240 free_list = im;
2243 static int
2244 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2246 if (a->im_self != b->im_self)
2247 return (a->im_self < b->im_self) ? -1 : 1;
2248 return PyObject_Compare(a->im_func, b->im_func);
2251 static PyObject *
2252 instancemethod_repr(PyMethodObject *a)
2254 PyObject *self = a->im_self;
2255 PyObject *func = a->im_func;
2256 PyObject *klass = a->im_class;
2257 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2258 char *sfuncname = "?", *sklassname = "?";
2260 funcname = PyObject_GetAttrString(func, "__name__");
2261 if (funcname == NULL) {
2262 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2263 return NULL;
2264 PyErr_Clear();
2266 else if (!PyString_Check(funcname)) {
2267 Py_DECREF(funcname);
2268 funcname = NULL;
2270 else
2271 sfuncname = PyString_AS_STRING(funcname);
2272 if (klass == NULL)
2273 klassname = NULL;
2274 else {
2275 klassname = PyObject_GetAttrString(klass, "__name__");
2276 if (klassname == NULL) {
2277 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2278 return NULL;
2279 PyErr_Clear();
2281 else if (!PyString_Check(klassname)) {
2282 Py_DECREF(klassname);
2283 klassname = NULL;
2285 else
2286 sklassname = PyString_AS_STRING(klassname);
2288 if (self == NULL)
2289 result = PyString_FromFormat("<unbound method %s.%s>",
2290 sklassname, sfuncname);
2291 else {
2292 /* XXX Shouldn't use repr() here! */
2293 PyObject *selfrepr = PyObject_Repr(self);
2294 if (selfrepr == NULL)
2295 goto fail;
2296 if (!PyString_Check(selfrepr)) {
2297 Py_DECREF(selfrepr);
2298 goto fail;
2300 result = PyString_FromFormat("<bound method %s.%s of %s>",
2301 sklassname, sfuncname,
2302 PyString_AS_STRING(selfrepr));
2303 Py_DECREF(selfrepr);
2305 fail:
2306 Py_XDECREF(funcname);
2307 Py_XDECREF(klassname);
2308 return result;
2311 static long
2312 instancemethod_hash(PyMethodObject *a)
2314 long x, y;
2315 if (a->im_self == NULL)
2316 x = PyObject_Hash(Py_None);
2317 else
2318 x = PyObject_Hash(a->im_self);
2319 if (x == -1)
2320 return -1;
2321 y = PyObject_Hash(a->im_func);
2322 if (y == -1)
2323 return -1;
2324 return x ^ y;
2327 static int
2328 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2330 int err;
2331 if (im->im_func) {
2332 err = visit(im->im_func, arg);
2333 if (err)
2334 return err;
2336 if (im->im_self) {
2337 err = visit(im->im_self, arg);
2338 if (err)
2339 return err;
2341 if (im->im_class) {
2342 err = visit(im->im_class, arg);
2343 if (err)
2344 return err;
2346 return 0;
2349 static void
2350 getclassname(PyObject *class, char *buf, int bufsize)
2352 PyObject *name;
2354 assert(bufsize > 1);
2355 strcpy(buf, "?"); /* Default outcome */
2356 if (class == NULL)
2357 return;
2358 name = PyObject_GetAttrString(class, "__name__");
2359 if (name == NULL) {
2360 /* This function cannot return an exception */
2361 PyErr_Clear();
2362 return;
2364 if (PyString_Check(name)) {
2365 strncpy(buf, PyString_AS_STRING(name), bufsize);
2366 buf[bufsize-1] = '\0';
2368 Py_DECREF(name);
2371 static void
2372 getinstclassname(PyObject *inst, char *buf, int bufsize)
2374 PyObject *class;
2376 if (inst == NULL) {
2377 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2378 strcpy(buf, "nothing");
2379 return;
2382 class = PyObject_GetAttrString(inst, "__class__");
2383 if (class == NULL) {
2384 /* This function cannot return an exception */
2385 PyErr_Clear();
2386 class = (PyObject *)(inst->ob_type);
2387 Py_INCREF(class);
2389 getclassname(class, buf, bufsize);
2390 Py_XDECREF(class);
2393 static PyObject *
2394 instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2396 PyObject *self = PyMethod_GET_SELF(func);
2397 PyObject *class = PyMethod_GET_CLASS(func);
2398 PyObject *result;
2400 func = PyMethod_GET_FUNCTION(func);
2401 if (self == NULL) {
2402 /* Unbound methods must be called with an instance of
2403 the class (or a derived class) as first argument */
2404 int ok;
2405 if (PyTuple_Size(arg) >= 1)
2406 self = PyTuple_GET_ITEM(arg, 0);
2407 if (self == NULL)
2408 ok = 0;
2409 else {
2410 ok = PyObject_IsInstance(self, class);
2411 if (ok < 0)
2412 return NULL;
2414 if (!ok) {
2415 char clsbuf[256];
2416 char instbuf[256];
2417 getclassname(class, clsbuf, sizeof(clsbuf));
2418 getinstclassname(self, instbuf, sizeof(instbuf));
2419 PyErr_Format(PyExc_TypeError,
2420 "unbound method %s%s must be called with "
2421 "%s instance as first argument "
2422 "(got %s%s instead)",
2423 PyEval_GetFuncName(func),
2424 PyEval_GetFuncDesc(func),
2425 clsbuf,
2426 instbuf,
2427 self == NULL ? "" : " instance");
2428 return NULL;
2430 Py_INCREF(arg);
2432 else {
2433 int argcount = PyTuple_Size(arg);
2434 PyObject *newarg = PyTuple_New(argcount + 1);
2435 int i;
2436 if (newarg == NULL)
2437 return NULL;
2438 Py_INCREF(self);
2439 PyTuple_SET_ITEM(newarg, 0, self);
2440 for (i = 0; i < argcount; i++) {
2441 PyObject *v = PyTuple_GET_ITEM(arg, i);
2442 Py_XINCREF(v);
2443 PyTuple_SET_ITEM(newarg, i+1, v);
2445 arg = newarg;
2447 result = PyObject_Call((PyObject *)func, arg, kw);
2448 Py_DECREF(arg);
2449 return result;
2452 static PyObject *
2453 instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
2455 /* Don't rebind an already bound method, or an unbound method
2456 of a class that's not a base class of cls. */
2458 if (PyMethod_GET_SELF(meth) != NULL) {
2459 /* Already bound */
2460 Py_INCREF(meth);
2461 return meth;
2463 /* No, it is an unbound method */
2464 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2465 /* Do subclass test. If it fails, return meth unchanged. */
2466 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2467 if (ok < 0)
2468 return NULL;
2469 if (!ok) {
2470 Py_INCREF(meth);
2471 return meth;
2474 /* Bind it to obj */
2475 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
2478 PyTypeObject PyMethod_Type = {
2479 PyObject_HEAD_INIT(&PyType_Type)
2481 "instancemethod",
2482 sizeof(PyMethodObject),
2484 (destructor)instancemethod_dealloc, /* tp_dealloc */
2485 0, /* tp_print */
2486 0, /* tp_getattr */
2487 0, /* tp_setattr */
2488 (cmpfunc)instancemethod_compare, /* tp_compare */
2489 (reprfunc)instancemethod_repr, /* tp_repr */
2490 0, /* tp_as_number */
2491 0, /* tp_as_sequence */
2492 0, /* tp_as_mapping */
2493 (hashfunc)instancemethod_hash, /* tp_hash */
2494 instancemethod_call, /* tp_call */
2495 0, /* tp_str */
2496 (getattrofunc)instancemethod_getattro, /* tp_getattro */
2497 PyObject_GenericSetAttr, /* tp_setattro */
2498 0, /* tp_as_buffer */
2499 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2500 instancemethod_doc, /* tp_doc */
2501 (traverseproc)instancemethod_traverse, /* tp_traverse */
2502 0, /* tp_clear */
2503 0, /* tp_richcompare */
2504 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2505 0, /* tp_iter */
2506 0, /* tp_iternext */
2507 0, /* tp_methods */
2508 instancemethod_memberlist, /* tp_members */
2509 instancemethod_getset, /* tp_getset */
2510 0, /* tp_base */
2511 0, /* tp_dict */
2512 instancemethod_descr_get, /* tp_descr_get */
2513 0, /* tp_descr_set */
2514 0, /* tp_dictoffset */
2515 0, /* tp_init */
2516 0, /* tp_alloc */
2517 instancemethod_new, /* tp_new */
2520 /* Clear out the free list */
2522 void
2523 PyMethod_Fini(void)
2525 while (free_list) {
2526 PyMethodObject *im = free_list;
2527 free_list = (PyMethodObject *)(im->im_self);
2528 PyObject_GC_Del(im);