AddressList.__str__(): Get rid of useless, and broken method. Closes
[python/dscho.git] / Objects / classobject.c
blob9375e07370756def639f1a4353c294adf3d1076f
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 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, the original decref dropped _Py_RefTotal,
674 * but _Py_NewReference bumped it again, so that's a wash.
675 * If Py_TRACE_REFS, _Py_NewReference re-added self to the
676 * object chain, so no more to do there either.
677 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
678 * _Py_NewReference bumped tp_allocs: both of those need to
679 * be undone.
681 #ifdef COUNT_ALLOCS
682 --inst->ob_type->tp_frees;
683 --inst->ob_type->tp_allocs;
684 #endif
688 static PyObject *
689 instance_getattr1(register PyInstanceObject *inst, PyObject *name)
691 register PyObject *v;
692 register char *sname = PyString_AsString(name);
693 if (sname[0] == '_' && sname[1] == '_') {
694 if (strcmp(sname, "__dict__") == 0) {
695 if (PyEval_GetRestricted()) {
696 PyErr_SetString(PyExc_RuntimeError,
697 "instance.__dict__ not accessible in restricted mode");
698 return NULL;
700 Py_INCREF(inst->in_dict);
701 return inst->in_dict;
703 if (strcmp(sname, "__class__") == 0) {
704 Py_INCREF(inst->in_class);
705 return (PyObject *)inst->in_class;
708 v = instance_getattr2(inst, name);
709 if (v == NULL && !PyErr_Occurred()) {
710 PyErr_Format(PyExc_AttributeError,
711 "%.50s instance has no attribute '%.400s'",
712 PyString_AS_STRING(inst->in_class->cl_name), sname);
714 return v;
717 static PyObject *
718 instance_getattr2(register PyInstanceObject *inst, PyObject *name)
720 register PyObject *v;
721 PyClassObject *class;
722 descrgetfunc f;
724 v = PyDict_GetItem(inst->in_dict, name);
725 if (v != NULL) {
726 Py_INCREF(v);
727 return v;
729 v = class_lookup(inst->in_class, name, &class);
730 if (v != NULL) {
731 Py_INCREF(v);
732 f = TP_DESCR_GET(v->ob_type);
733 if (f != NULL) {
734 PyObject *w = f(v, (PyObject *)inst,
735 (PyObject *)(inst->in_class));
736 Py_DECREF(v);
737 v = w;
740 return v;
743 static PyObject *
744 instance_getattr(register PyInstanceObject *inst, PyObject *name)
746 register PyObject *func, *res;
747 res = instance_getattr1(inst, name);
748 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
749 PyObject *args;
750 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
751 return NULL;
752 PyErr_Clear();
753 args = Py_BuildValue("(OO)", inst, name);
754 if (args == NULL)
755 return NULL;
756 res = PyEval_CallObject(func, args);
757 Py_DECREF(args);
759 return res;
762 /* See classobject.h comments: this only does dict lookups, and is always
763 * safe to call.
765 PyObject *
766 _PyInstance_Lookup(PyObject *pinst, PyObject *name)
768 PyObject *v;
769 PyClassObject *class;
770 PyInstanceObject *inst; /* pinst cast to the right type */
772 assert(PyInstance_Check(pinst));
773 inst = (PyInstanceObject *)pinst;
775 assert(PyString_Check(name));
777 v = PyDict_GetItem(inst->in_dict, name);
778 if (v == NULL)
779 v = class_lookup(inst->in_class, name, &class);
780 return v;
783 static int
784 instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
786 if (v == NULL) {
787 int rv = PyDict_DelItem(inst->in_dict, name);
788 if (rv < 0)
789 PyErr_Format(PyExc_AttributeError,
790 "%.50s instance has no attribute '%.400s'",
791 PyString_AS_STRING(inst->in_class->cl_name),
792 PyString_AS_STRING(name));
793 return rv;
795 else
796 return PyDict_SetItem(inst->in_dict, name, v);
799 static int
800 instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
802 PyObject *func, *args, *res, *tmp;
803 char *sname = PyString_AsString(name);
804 if (sname[0] == '_' && sname[1] == '_') {
805 int n = PyString_Size(name);
806 if (sname[n-1] == '_' && sname[n-2] == '_') {
807 if (strcmp(sname, "__dict__") == 0) {
808 if (PyEval_GetRestricted()) {
809 PyErr_SetString(PyExc_RuntimeError,
810 "__dict__ not accessible in restricted mode");
811 return -1;
813 if (v == NULL || !PyDict_Check(v)) {
814 PyErr_SetString(PyExc_TypeError,
815 "__dict__ must be set to a dictionary");
816 return -1;
818 tmp = inst->in_dict;
819 Py_INCREF(v);
820 inst->in_dict = v;
821 Py_DECREF(tmp);
822 return 0;
824 if (strcmp(sname, "__class__") == 0) {
825 if (PyEval_GetRestricted()) {
826 PyErr_SetString(PyExc_RuntimeError,
827 "__class__ not accessible in restricted mode");
828 return -1;
830 if (v == NULL || !PyClass_Check(v)) {
831 PyErr_SetString(PyExc_TypeError,
832 "__class__ must be set to a class");
833 return -1;
835 tmp = (PyObject *)(inst->in_class);
836 Py_INCREF(v);
837 inst->in_class = (PyClassObject *)v;
838 Py_DECREF(tmp);
839 return 0;
843 if (v == NULL)
844 func = inst->in_class->cl_delattr;
845 else
846 func = inst->in_class->cl_setattr;
847 if (func == NULL)
848 return instance_setattr1(inst, name, v);
849 if (v == NULL)
850 args = Py_BuildValue("(OO)", inst, name);
851 else
852 args = Py_BuildValue("(OOO)", inst, name, v);
853 if (args == NULL)
854 return -1;
855 res = PyEval_CallObject(func, args);
856 Py_DECREF(args);
857 if (res == NULL)
858 return -1;
859 Py_DECREF(res);
860 return 0;
863 static PyObject *
864 instance_repr(PyInstanceObject *inst)
866 PyObject *func;
867 PyObject *res;
868 static PyObject *reprstr;
870 if (reprstr == NULL)
871 reprstr = PyString_InternFromString("__repr__");
872 func = instance_getattr(inst, reprstr);
873 if (func == NULL) {
874 PyObject *classname, *mod;
875 char *cname;
876 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
877 return NULL;
878 PyErr_Clear();
879 classname = inst->in_class->cl_name;
880 mod = PyDict_GetItemString(inst->in_class->cl_dict,
881 "__module__");
882 if (classname != NULL && PyString_Check(classname))
883 cname = PyString_AsString(classname);
884 else
885 cname = "?";
886 if (mod == NULL || !PyString_Check(mod))
887 return PyString_FromFormat("<?.%s instance at %p>",
888 cname, inst);
889 else
890 return PyString_FromFormat("<%s.%s instance at %p>",
891 PyString_AsString(mod),
892 cname, inst);
894 res = PyEval_CallObject(func, (PyObject *)NULL);
895 Py_DECREF(func);
896 return res;
899 static PyObject *
900 instance_str(PyInstanceObject *inst)
902 PyObject *func;
903 PyObject *res;
904 static PyObject *strstr;
906 if (strstr == NULL)
907 strstr = PyString_InternFromString("__str__");
908 func = instance_getattr(inst, strstr);
909 if (func == NULL) {
910 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
911 return NULL;
912 PyErr_Clear();
913 return instance_repr(inst);
915 res = PyEval_CallObject(func, (PyObject *)NULL);
916 Py_DECREF(func);
917 return res;
920 static long
921 instance_hash(PyInstanceObject *inst)
923 PyObject *func;
924 PyObject *res;
925 long outcome;
926 static PyObject *hashstr, *eqstr, *cmpstr;
928 if (hashstr == NULL)
929 hashstr = PyString_InternFromString("__hash__");
930 func = instance_getattr(inst, hashstr);
931 if (func == NULL) {
932 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
933 return -1;
934 PyErr_Clear();
935 /* If there is no __eq__ and no __cmp__ method, we hash on the
936 address. If an __eq__ or __cmp__ method exists, there must
937 be a __hash__. */
938 if (eqstr == NULL)
939 eqstr = PyString_InternFromString("__eq__");
940 func = instance_getattr(inst, eqstr);
941 if (func == NULL) {
942 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
943 return -1;
944 PyErr_Clear();
945 if (cmpstr == NULL)
946 cmpstr = PyString_InternFromString("__cmp__");
947 func = instance_getattr(inst, cmpstr);
948 if (func == NULL) {
949 if (!PyErr_ExceptionMatches(
950 PyExc_AttributeError))
951 return -1;
952 PyErr_Clear();
953 return _Py_HashPointer(inst);
956 PyErr_SetString(PyExc_TypeError, "unhashable instance");
957 return -1;
959 res = PyEval_CallObject(func, (PyObject *)NULL);
960 Py_DECREF(func);
961 if (res == NULL)
962 return -1;
963 if (PyInt_Check(res)) {
964 outcome = PyInt_AsLong(res);
965 if (outcome == -1)
966 outcome = -2;
968 else {
969 PyErr_SetString(PyExc_TypeError,
970 "__hash__() should return an int");
971 outcome = -1;
973 Py_DECREF(res);
974 return outcome;
977 static int
978 instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
980 int err;
981 if (o->in_class) {
982 err = visit((PyObject *)(o->in_class), arg);
983 if (err)
984 return err;
986 if (o->in_dict) {
987 err = visit(o->in_dict, arg);
988 if (err)
989 return err;
991 return 0;
994 static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
995 static PyObject *iterstr, *nextstr;
997 static int
998 instance_length(PyInstanceObject *inst)
1000 PyObject *func;
1001 PyObject *res;
1002 int outcome;
1004 if (lenstr == NULL)
1005 lenstr = PyString_InternFromString("__len__");
1006 func = instance_getattr(inst, lenstr);
1007 if (func == NULL)
1008 return -1;
1009 res = PyEval_CallObject(func, (PyObject *)NULL);
1010 Py_DECREF(func);
1011 if (res == NULL)
1012 return -1;
1013 if (PyInt_Check(res)) {
1014 outcome = PyInt_AsLong(res);
1015 if (outcome < 0)
1016 PyErr_SetString(PyExc_ValueError,
1017 "__len__() should return >= 0");
1019 else {
1020 PyErr_SetString(PyExc_TypeError,
1021 "__len__() should return an int");
1022 outcome = -1;
1024 Py_DECREF(res);
1025 return outcome;
1028 static PyObject *
1029 instance_subscript(PyInstanceObject *inst, PyObject *key)
1031 PyObject *func;
1032 PyObject *arg;
1033 PyObject *res;
1035 if (getitemstr == NULL)
1036 getitemstr = PyString_InternFromString("__getitem__");
1037 func = instance_getattr(inst, getitemstr);
1038 if (func == NULL)
1039 return NULL;
1040 arg = Py_BuildValue("(O)", key);
1041 if (arg == NULL) {
1042 Py_DECREF(func);
1043 return NULL;
1045 res = PyEval_CallObject(func, arg);
1046 Py_DECREF(func);
1047 Py_DECREF(arg);
1048 return res;
1051 static int
1052 instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1054 PyObject *func;
1055 PyObject *arg;
1056 PyObject *res;
1058 if (value == NULL) {
1059 if (delitemstr == NULL)
1060 delitemstr = PyString_InternFromString("__delitem__");
1061 func = instance_getattr(inst, delitemstr);
1063 else {
1064 if (setitemstr == NULL)
1065 setitemstr = PyString_InternFromString("__setitem__");
1066 func = instance_getattr(inst, setitemstr);
1068 if (func == NULL)
1069 return -1;
1070 if (value == NULL)
1071 arg = Py_BuildValue("(O)", key);
1072 else
1073 arg = Py_BuildValue("(OO)", key, value);
1074 if (arg == NULL) {
1075 Py_DECREF(func);
1076 return -1;
1078 res = PyEval_CallObject(func, arg);
1079 Py_DECREF(func);
1080 Py_DECREF(arg);
1081 if (res == NULL)
1082 return -1;
1083 Py_DECREF(res);
1084 return 0;
1087 static PyMappingMethods instance_as_mapping = {
1088 (inquiry)instance_length, /* mp_length */
1089 (binaryfunc)instance_subscript, /* mp_subscript */
1090 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
1093 static PyObject *
1094 instance_item(PyInstanceObject *inst, int i)
1096 PyObject *func, *arg, *res;
1098 if (getitemstr == NULL)
1099 getitemstr = PyString_InternFromString("__getitem__");
1100 func = instance_getattr(inst, getitemstr);
1101 if (func == NULL)
1102 return NULL;
1103 arg = Py_BuildValue("(i)", i);
1104 if (arg == NULL) {
1105 Py_DECREF(func);
1106 return NULL;
1108 res = PyEval_CallObject(func, arg);
1109 Py_DECREF(func);
1110 Py_DECREF(arg);
1111 return res;
1114 static PyObject *
1115 sliceobj_from_intint(int i, int j)
1117 PyObject *start, *end, *res;
1119 start = PyInt_FromLong((long)i);
1120 if (!start)
1121 return NULL;
1123 end = PyInt_FromLong((long)j);
1124 if (!end) {
1125 Py_DECREF(start);
1126 return NULL;
1128 res = PySlice_New(start, end, NULL);
1129 Py_DECREF(start);
1130 Py_DECREF(end);
1131 return res;
1135 static PyObject *
1136 instance_slice(PyInstanceObject *inst, int i, int j)
1138 PyObject *func, *arg, *res;
1139 static PyObject *getslicestr;
1141 if (getslicestr == NULL)
1142 getslicestr = PyString_InternFromString("__getslice__");
1143 func = instance_getattr(inst, getslicestr);
1145 if (func == NULL) {
1146 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1147 return NULL;
1148 PyErr_Clear();
1150 if (getitemstr == NULL)
1151 getitemstr = PyString_InternFromString("__getitem__");
1152 func = instance_getattr(inst, getitemstr);
1153 if (func == NULL)
1154 return NULL;
1155 arg = Py_BuildValue("(N)", sliceobj_from_intint(i, j));
1156 } else
1157 arg = Py_BuildValue("(ii)", i, j);
1159 if (arg == NULL) {
1160 Py_DECREF(func);
1161 return NULL;
1163 res = PyEval_CallObject(func, arg);
1164 Py_DECREF(func);
1165 Py_DECREF(arg);
1166 return res;
1169 static int
1170 instance_ass_item(PyInstanceObject *inst, int i, PyObject *item)
1172 PyObject *func, *arg, *res;
1174 if (item == NULL) {
1175 if (delitemstr == NULL)
1176 delitemstr = PyString_InternFromString("__delitem__");
1177 func = instance_getattr(inst, delitemstr);
1179 else {
1180 if (setitemstr == NULL)
1181 setitemstr = PyString_InternFromString("__setitem__");
1182 func = instance_getattr(inst, setitemstr);
1184 if (func == NULL)
1185 return -1;
1186 if (item == NULL)
1187 arg = Py_BuildValue("i", i);
1188 else
1189 arg = Py_BuildValue("(iO)", i, item);
1190 if (arg == NULL) {
1191 Py_DECREF(func);
1192 return -1;
1194 res = PyEval_CallObject(func, arg);
1195 Py_DECREF(func);
1196 Py_DECREF(arg);
1197 if (res == NULL)
1198 return -1;
1199 Py_DECREF(res);
1200 return 0;
1203 static int
1204 instance_ass_slice(PyInstanceObject *inst, int i, int j, PyObject *value)
1206 PyObject *func, *arg, *res;
1207 static PyObject *setslicestr, *delslicestr;
1209 if (value == NULL) {
1210 if (delslicestr == NULL)
1211 delslicestr =
1212 PyString_InternFromString("__delslice__");
1213 func = instance_getattr(inst, delslicestr);
1214 if (func == NULL) {
1215 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1216 return -1;
1217 PyErr_Clear();
1218 if (delitemstr == NULL)
1219 delitemstr =
1220 PyString_InternFromString("__delitem__");
1221 func = instance_getattr(inst, delitemstr);
1222 if (func == NULL)
1223 return -1;
1225 arg = Py_BuildValue("(N)",
1226 sliceobj_from_intint(i, j));
1227 } else
1228 arg = Py_BuildValue("(ii)", i, j);
1230 else {
1231 if (setslicestr == NULL)
1232 setslicestr =
1233 PyString_InternFromString("__setslice__");
1234 func = instance_getattr(inst, setslicestr);
1235 if (func == NULL) {
1236 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1237 return -1;
1238 PyErr_Clear();
1239 if (setitemstr == NULL)
1240 setitemstr =
1241 PyString_InternFromString("__setitem__");
1242 func = instance_getattr(inst, setitemstr);
1243 if (func == NULL)
1244 return -1;
1246 arg = Py_BuildValue("(NO)",
1247 sliceobj_from_intint(i, j), value);
1248 } else
1249 arg = Py_BuildValue("(iiO)", i, j, value);
1251 if (arg == NULL) {
1252 Py_DECREF(func);
1253 return -1;
1255 res = PyEval_CallObject(func, arg);
1256 Py_DECREF(func);
1257 Py_DECREF(arg);
1258 if (res == NULL)
1259 return -1;
1260 Py_DECREF(res);
1261 return 0;
1264 static int
1265 instance_contains(PyInstanceObject *inst, PyObject *member)
1267 static PyObject *__contains__;
1268 PyObject *func;
1270 /* Try __contains__ first.
1271 * If that can't be done, try iterator-based searching.
1274 if(__contains__ == NULL) {
1275 __contains__ = PyString_InternFromString("__contains__");
1276 if(__contains__ == NULL)
1277 return -1;
1279 func = instance_getattr(inst, __contains__);
1280 if (func) {
1281 PyObject *res;
1282 int ret;
1283 PyObject *arg = Py_BuildValue("(O)", member);
1284 if(arg == NULL) {
1285 Py_DECREF(func);
1286 return -1;
1288 res = PyEval_CallObject(func, arg);
1289 Py_DECREF(func);
1290 Py_DECREF(arg);
1291 if(res == NULL)
1292 return -1;
1293 ret = PyObject_IsTrue(res);
1294 Py_DECREF(res);
1295 return ret;
1298 /* Couldn't find __contains__. */
1299 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1300 /* Assume the failure was simply due to that there is no
1301 * __contains__ attribute, and try iterating instead.
1303 PyErr_Clear();
1304 return _PySequence_IterSearch((PyObject *)inst, member,
1305 PY_ITERSEARCH_CONTAINS);
1307 else
1308 return -1;
1311 static PySequenceMethods
1312 instance_as_sequence = {
1313 (inquiry)instance_length, /* sq_length */
1314 0, /* sq_concat */
1315 0, /* sq_repeat */
1316 (intargfunc)instance_item, /* sq_item */
1317 (intintargfunc)instance_slice, /* sq_slice */
1318 (intobjargproc)instance_ass_item, /* sq_ass_item */
1319 (intintobjargproc)instance_ass_slice, /* sq_ass_slice */
1320 (objobjproc)instance_contains, /* sq_contains */
1323 static PyObject *
1324 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1326 PyObject *func, *res;
1328 if ((func = instance_getattr(self, methodname)) == NULL)
1329 return NULL;
1330 res = PyEval_CallObject(func, (PyObject *)NULL);
1331 Py_DECREF(func);
1332 return res;
1335 static PyObject *
1336 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1338 PyObject *result;
1339 PyObject *args;
1340 PyObject *func = PyObject_GetAttrString(v, opname);
1341 if (func == NULL) {
1342 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1343 return NULL;
1344 PyErr_Clear();
1345 Py_INCREF(Py_NotImplemented);
1346 return Py_NotImplemented;
1348 args = Py_BuildValue("(O)", w);
1349 if (args == NULL) {
1350 Py_DECREF(func);
1351 return NULL;
1353 result = PyEval_CallObject(func, args);
1354 Py_DECREF(args);
1355 Py_DECREF(func);
1356 return result;
1360 static PyObject *coerce_obj;
1362 /* Try one half of a binary operator involving a class instance. */
1363 static PyObject *
1364 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1365 int swapped)
1367 PyObject *args;
1368 PyObject *coercefunc;
1369 PyObject *coerced = NULL;
1370 PyObject *v1;
1371 PyObject *result;
1373 if (!PyInstance_Check(v)) {
1374 Py_INCREF(Py_NotImplemented);
1375 return Py_NotImplemented;
1378 if (coerce_obj == NULL) {
1379 coerce_obj = PyString_InternFromString("__coerce__");
1380 if (coerce_obj == NULL)
1381 return NULL;
1383 coercefunc = PyObject_GetAttr(v, coerce_obj);
1384 if (coercefunc == NULL) {
1385 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1386 return NULL;
1387 PyErr_Clear();
1388 return generic_binary_op(v, w, opname);
1391 args = Py_BuildValue("(O)", w);
1392 if (args == NULL) {
1393 Py_DECREF(coercefunc);
1394 return NULL;
1396 coerced = PyEval_CallObject(coercefunc, args);
1397 Py_DECREF(args);
1398 Py_DECREF(coercefunc);
1399 if (coerced == NULL) {
1400 return NULL;
1402 if (coerced == Py_None || coerced == Py_NotImplemented) {
1403 Py_DECREF(coerced);
1404 return generic_binary_op(v, w, opname);
1406 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1407 Py_DECREF(coerced);
1408 PyErr_SetString(PyExc_TypeError,
1409 "coercion should return None or 2-tuple");
1410 return NULL;
1412 v1 = PyTuple_GetItem(coerced, 0);
1413 w = PyTuple_GetItem(coerced, 1);
1414 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1415 /* prevent recursion if __coerce__ returns self as the first
1416 * argument */
1417 result = generic_binary_op(v1, w, opname);
1418 } else {
1419 if (swapped)
1420 result = (thisfunc)(w, v1);
1421 else
1422 result = (thisfunc)(v1, w);
1424 Py_DECREF(coerced);
1425 return result;
1428 /* Implement a binary operator involving at least one class instance. */
1429 static PyObject *
1430 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1431 binaryfunc thisfunc)
1433 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1434 if (result == Py_NotImplemented) {
1435 Py_DECREF(result);
1436 result = half_binop(w, v, ropname, thisfunc, 1);
1438 return result;
1441 static PyObject *
1442 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1443 char *ropname, binaryfunc thisfunc)
1445 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1446 if (result == Py_NotImplemented) {
1447 Py_DECREF(result);
1448 result = do_binop(v, w, opname, ropname, thisfunc);
1450 return result;
1453 static int
1454 instance_coerce(PyObject **pv, PyObject **pw)
1456 PyObject *v = *pv;
1457 PyObject *w = *pw;
1458 PyObject *coercefunc;
1459 PyObject *args;
1460 PyObject *coerced;
1462 if (coerce_obj == NULL) {
1463 coerce_obj = PyString_InternFromString("__coerce__");
1464 if (coerce_obj == NULL)
1465 return -1;
1467 coercefunc = PyObject_GetAttr(v, coerce_obj);
1468 if (coercefunc == NULL) {
1469 /* No __coerce__ method */
1470 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1471 return -1;
1472 PyErr_Clear();
1473 return 1;
1475 /* Has __coerce__ method: call it */
1476 args = Py_BuildValue("(O)", w);
1477 if (args == NULL) {
1478 return -1;
1480 coerced = PyEval_CallObject(coercefunc, args);
1481 Py_DECREF(args);
1482 Py_DECREF(coercefunc);
1483 if (coerced == NULL) {
1484 /* __coerce__ call raised an exception */
1485 return -1;
1487 if (coerced == Py_None || coerced == Py_NotImplemented) {
1488 /* __coerce__ says "I can't do it" */
1489 Py_DECREF(coerced);
1490 return 1;
1492 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1493 /* __coerce__ return value is malformed */
1494 Py_DECREF(coerced);
1495 PyErr_SetString(PyExc_TypeError,
1496 "coercion should return None or 2-tuple");
1497 return -1;
1499 /* __coerce__ returned two new values */
1500 *pv = PyTuple_GetItem(coerced, 0);
1501 *pw = PyTuple_GetItem(coerced, 1);
1502 Py_INCREF(*pv);
1503 Py_INCREF(*pw);
1504 Py_DECREF(coerced);
1505 return 0;
1508 #define UNARY(funcname, methodname) \
1509 static PyObject *funcname(PyInstanceObject *self) { \
1510 static PyObject *o; \
1511 if (o == NULL) o = PyString_InternFromString(methodname); \
1512 return generic_unary_op(self, o); \
1515 #define BINARY(f, m, n) \
1516 static PyObject *f(PyObject *v, PyObject *w) { \
1517 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1520 #define BINARY_INPLACE(f, m, n) \
1521 static PyObject *f(PyObject *v, PyObject *w) { \
1522 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1523 "__r" m "__", n); \
1526 UNARY(instance_neg, "__neg__")
1527 UNARY(instance_pos, "__pos__")
1528 UNARY(instance_abs, "__abs__")
1530 BINARY(instance_or, "or", PyNumber_Or)
1531 BINARY(instance_and, "and", PyNumber_And)
1532 BINARY(instance_xor, "xor", PyNumber_Xor)
1533 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1534 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1535 BINARY(instance_add, "add", PyNumber_Add)
1536 BINARY(instance_sub, "sub", PyNumber_Subtract)
1537 BINARY(instance_mul, "mul", PyNumber_Multiply)
1538 BINARY(instance_div, "div", PyNumber_Divide)
1539 BINARY(instance_mod, "mod", PyNumber_Remainder)
1540 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1541 BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1542 BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1544 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1545 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1546 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1547 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1548 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1549 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1550 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1551 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1552 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1553 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1554 BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1555 BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1557 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1558 -2 for an exception;
1559 -1 if v < w;
1560 0 if v == w;
1561 1 if v > w;
1562 2 if this particular 3-way comparison is not implemented or undefined.
1564 static int
1565 half_cmp(PyObject *v, PyObject *w)
1567 static PyObject *cmp_obj;
1568 PyObject *args;
1569 PyObject *cmp_func;
1570 PyObject *result;
1571 long l;
1573 assert(PyInstance_Check(v));
1575 if (cmp_obj == NULL) {
1576 cmp_obj = PyString_InternFromString("__cmp__");
1577 if (cmp_obj == NULL)
1578 return -2;
1581 cmp_func = PyObject_GetAttr(v, cmp_obj);
1582 if (cmp_func == NULL) {
1583 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1584 return -2;
1585 PyErr_Clear();
1586 return 2;
1589 args = Py_BuildValue("(O)", w);
1590 if (args == NULL) {
1591 Py_DECREF(cmp_func);
1592 return -2;
1595 result = PyEval_CallObject(cmp_func, args);
1596 Py_DECREF(args);
1597 Py_DECREF(cmp_func);
1599 if (result == NULL)
1600 return -2;
1602 if (result == Py_NotImplemented) {
1603 Py_DECREF(result);
1604 return 2;
1607 l = PyInt_AsLong(result);
1608 Py_DECREF(result);
1609 if (l == -1 && PyErr_Occurred()) {
1610 PyErr_SetString(PyExc_TypeError,
1611 "comparison did not return an int");
1612 return -2;
1615 return l < 0 ? -1 : l > 0 ? 1 : 0;
1618 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1619 We first try a coercion. Return:
1620 -2 for an exception;
1621 -1 if v < w;
1622 0 if v == w;
1623 1 if v > w;
1624 2 if this particular 3-way comparison is not implemented or undefined.
1625 THIS IS ONLY CALLED FROM object.c!
1627 static int
1628 instance_compare(PyObject *v, PyObject *w)
1630 int c;
1632 c = PyNumber_CoerceEx(&v, &w);
1633 if (c < 0)
1634 return -2;
1635 if (c == 0) {
1636 /* If neither is now an instance, use regular comparison */
1637 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1638 c = PyObject_Compare(v, w);
1639 Py_DECREF(v);
1640 Py_DECREF(w);
1641 if (PyErr_Occurred())
1642 return -2;
1643 return c < 0 ? -1 : c > 0 ? 1 : 0;
1646 else {
1647 /* The coercion didn't do anything.
1648 Treat this the same as returning v and w unchanged. */
1649 Py_INCREF(v);
1650 Py_INCREF(w);
1653 if (PyInstance_Check(v)) {
1654 c = half_cmp(v, w);
1655 if (c <= 1) {
1656 Py_DECREF(v);
1657 Py_DECREF(w);
1658 return c;
1661 if (PyInstance_Check(w)) {
1662 c = half_cmp(w, v);
1663 if (c <= 1) {
1664 Py_DECREF(v);
1665 Py_DECREF(w);
1666 if (c >= -1)
1667 c = -c;
1668 return c;
1671 Py_DECREF(v);
1672 Py_DECREF(w);
1673 return 2;
1676 static int
1677 instance_nonzero(PyInstanceObject *self)
1679 PyObject *func, *res;
1680 long outcome;
1681 static PyObject *nonzerostr;
1683 if (nonzerostr == NULL)
1684 nonzerostr = PyString_InternFromString("__nonzero__");
1685 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1686 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1687 return -1;
1688 PyErr_Clear();
1689 if (lenstr == NULL)
1690 lenstr = PyString_InternFromString("__len__");
1691 if ((func = instance_getattr(self, lenstr)) == NULL) {
1692 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1693 return -1;
1694 PyErr_Clear();
1695 /* Fall back to the default behavior:
1696 all instances are nonzero */
1697 return 1;
1700 res = PyEval_CallObject(func, (PyObject *)NULL);
1701 Py_DECREF(func);
1702 if (res == NULL)
1703 return -1;
1704 if (!PyInt_Check(res)) {
1705 Py_DECREF(res);
1706 PyErr_SetString(PyExc_TypeError,
1707 "__nonzero__ should return an int");
1708 return -1;
1710 outcome = PyInt_AsLong(res);
1711 Py_DECREF(res);
1712 if (outcome < 0) {
1713 PyErr_SetString(PyExc_ValueError,
1714 "__nonzero__ should return >= 0");
1715 return -1;
1717 return outcome > 0;
1720 UNARY(instance_invert, "__invert__")
1721 UNARY(instance_int, "__int__")
1722 UNARY(instance_long, "__long__")
1723 UNARY(instance_float, "__float__")
1724 UNARY(instance_oct, "__oct__")
1725 UNARY(instance_hex, "__hex__")
1727 static PyObject *
1728 bin_power(PyObject *v, PyObject *w)
1730 return PyNumber_Power(v, w, Py_None);
1733 /* This version is for ternary calls only (z != None) */
1734 static PyObject *
1735 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1737 if (z == Py_None) {
1738 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1740 else {
1741 PyObject *func;
1742 PyObject *args;
1743 PyObject *result;
1745 /* XXX Doesn't do coercions... */
1746 func = PyObject_GetAttrString(v, "__pow__");
1747 if (func == NULL)
1748 return NULL;
1749 args = Py_BuildValue("(OO)", w, z);
1750 if (args == NULL) {
1751 Py_DECREF(func);
1752 return NULL;
1754 result = PyEval_CallObject(func, args);
1755 Py_DECREF(func);
1756 Py_DECREF(args);
1757 return result;
1761 static PyObject *
1762 bin_inplace_power(PyObject *v, PyObject *w)
1764 return PyNumber_InPlacePower(v, w, Py_None);
1768 static PyObject *
1769 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1771 if (z == Py_None) {
1772 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1773 "__rpow__", bin_inplace_power);
1775 else {
1776 /* XXX Doesn't do coercions... */
1777 PyObject *func;
1778 PyObject *args;
1779 PyObject *result;
1781 func = PyObject_GetAttrString(v, "__ipow__");
1782 if (func == NULL) {
1783 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1784 return NULL;
1785 PyErr_Clear();
1786 return instance_pow(v, w, z);
1788 args = Py_BuildValue("(OO)", w, z);
1789 if (args == NULL) {
1790 Py_DECREF(func);
1791 return NULL;
1793 result = PyEval_CallObject(func, args);
1794 Py_DECREF(func);
1795 Py_DECREF(args);
1796 return result;
1801 /* Map rich comparison operators to their __xx__ namesakes */
1802 #define NAME_OPS 6
1803 static PyObject **name_op = NULL;
1805 static int
1806 init_name_op(void)
1808 int i;
1809 char *_name_op[] = {
1810 "__lt__",
1811 "__le__",
1812 "__eq__",
1813 "__ne__",
1814 "__gt__",
1815 "__ge__",
1818 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1819 if (name_op == NULL)
1820 return -1;
1821 for (i = 0; i < NAME_OPS; ++i) {
1822 name_op[i] = PyString_InternFromString(_name_op[i]);
1823 if (name_op[i] == NULL)
1824 return -1;
1826 return 0;
1829 static PyObject *
1830 half_richcompare(PyObject *v, PyObject *w, int op)
1832 PyObject *method;
1833 PyObject *args;
1834 PyObject *res;
1836 assert(PyInstance_Check(v));
1838 if (name_op == NULL) {
1839 if (init_name_op() < 0)
1840 return NULL;
1842 /* If the instance doesn't define an __getattr__ method, use
1843 instance_getattr2 directly because it will not set an
1844 exception on failure. */
1845 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1846 method = instance_getattr2((PyInstanceObject *)v,
1847 name_op[op]);
1848 else
1849 method = PyObject_GetAttr(v, name_op[op]);
1850 if (method == NULL) {
1851 if (PyErr_Occurred()) {
1852 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1853 return NULL;
1854 PyErr_Clear();
1856 res = Py_NotImplemented;
1857 Py_INCREF(res);
1858 return res;
1861 args = Py_BuildValue("(O)", w);
1862 if (args == NULL) {
1863 Py_DECREF(method);
1864 return NULL;
1867 res = PyEval_CallObject(method, args);
1868 Py_DECREF(args);
1869 Py_DECREF(method);
1871 return res;
1874 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1875 static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
1877 static PyObject *
1878 instance_richcompare(PyObject *v, PyObject *w, int op)
1880 PyObject *res;
1882 if (PyInstance_Check(v)) {
1883 res = half_richcompare(v, w, op);
1884 if (res != Py_NotImplemented)
1885 return res;
1886 Py_DECREF(res);
1889 if (PyInstance_Check(w)) {
1890 res = half_richcompare(w, v, swapped_op[op]);
1891 if (res != Py_NotImplemented)
1892 return res;
1893 Py_DECREF(res);
1896 Py_INCREF(Py_NotImplemented);
1897 return Py_NotImplemented;
1901 /* Get the iterator */
1902 static PyObject *
1903 instance_getiter(PyInstanceObject *self)
1905 PyObject *func;
1907 if (iterstr == NULL) {
1908 iterstr = PyString_InternFromString("__iter__");
1909 if (iterstr == NULL)
1910 return NULL;
1912 if (getitemstr == NULL) {
1913 getitemstr = PyString_InternFromString("__getitem__");
1914 if (getitemstr == NULL)
1915 return NULL;
1918 if ((func = instance_getattr(self, iterstr)) != NULL) {
1919 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1920 Py_DECREF(func);
1921 if (res != NULL && !PyIter_Check(res)) {
1922 PyErr_Format(PyExc_TypeError,
1923 "__iter__ returned non-iterator "
1924 "of type '%.100s'",
1925 res->ob_type->tp_name);
1926 Py_DECREF(res);
1927 res = NULL;
1929 return res;
1931 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1932 return NULL;
1933 PyErr_Clear();
1934 if ((func = instance_getattr(self, getitemstr)) == NULL) {
1935 PyErr_SetString(PyExc_TypeError,
1936 "iteration over non-sequence");
1937 return NULL;
1939 Py_DECREF(func);
1940 return PySeqIter_New((PyObject *)self);
1944 /* Call the iterator's next */
1945 static PyObject *
1946 instance_iternext(PyInstanceObject *self)
1948 PyObject *func;
1950 if (nextstr == NULL)
1951 nextstr = PyString_InternFromString("next");
1953 if ((func = instance_getattr(self, nextstr)) != NULL) {
1954 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1955 Py_DECREF(func);
1956 if (res != NULL) {
1957 return res;
1959 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
1960 PyErr_Clear();
1961 return NULL;
1963 return NULL;
1965 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
1966 return NULL;
1969 static PyObject *
1970 instance_call(PyObject *func, PyObject *arg, PyObject *kw)
1972 PyThreadState *tstate = PyThreadState_GET();
1973 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
1974 if (call == NULL) {
1975 PyInstanceObject *inst = (PyInstanceObject*) func;
1976 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1977 return NULL;
1978 PyErr_Clear();
1979 PyErr_Format(PyExc_AttributeError,
1980 "%.200s instance has no __call__ method",
1981 PyString_AsString(inst->in_class->cl_name));
1982 return NULL;
1984 /* We must check and increment the recursion depth here. Scenario:
1985 class A:
1986 pass
1987 A.__call__ = A() # that's right
1988 a = A() # ok
1989 a() # infinite recursion
1990 This bounces between instance_call() and PyObject_Call() without
1991 ever hitting eval_frame() (which has the main recursion check). */
1992 if (tstate->recursion_depth++ > Py_GetRecursionLimit()) {
1993 PyErr_SetString(PyExc_RuntimeError,
1994 "maximum __call__ recursion depth exceeded");
1995 res = NULL;
1997 else
1998 res = PyObject_Call(call, arg, kw);
1999 tstate->recursion_depth--;
2000 Py_DECREF(call);
2001 return res;
2005 static PyNumberMethods instance_as_number = {
2006 (binaryfunc)instance_add, /* nb_add */
2007 (binaryfunc)instance_sub, /* nb_subtract */
2008 (binaryfunc)instance_mul, /* nb_multiply */
2009 (binaryfunc)instance_div, /* nb_divide */
2010 (binaryfunc)instance_mod, /* nb_remainder */
2011 (binaryfunc)instance_divmod, /* nb_divmod */
2012 (ternaryfunc)instance_pow, /* nb_power */
2013 (unaryfunc)instance_neg, /* nb_negative */
2014 (unaryfunc)instance_pos, /* nb_positive */
2015 (unaryfunc)instance_abs, /* nb_absolute */
2016 (inquiry)instance_nonzero, /* nb_nonzero */
2017 (unaryfunc)instance_invert, /* nb_invert */
2018 (binaryfunc)instance_lshift, /* nb_lshift */
2019 (binaryfunc)instance_rshift, /* nb_rshift */
2020 (binaryfunc)instance_and, /* nb_and */
2021 (binaryfunc)instance_xor, /* nb_xor */
2022 (binaryfunc)instance_or, /* nb_or */
2023 (coercion)instance_coerce, /* nb_coerce */
2024 (unaryfunc)instance_int, /* nb_int */
2025 (unaryfunc)instance_long, /* nb_long */
2026 (unaryfunc)instance_float, /* nb_float */
2027 (unaryfunc)instance_oct, /* nb_oct */
2028 (unaryfunc)instance_hex, /* nb_hex */
2029 (binaryfunc)instance_iadd, /* nb_inplace_add */
2030 (binaryfunc)instance_isub, /* nb_inplace_subtract */
2031 (binaryfunc)instance_imul, /* nb_inplace_multiply */
2032 (binaryfunc)instance_idiv, /* nb_inplace_divide */
2033 (binaryfunc)instance_imod, /* nb_inplace_remainder */
2034 (ternaryfunc)instance_ipow, /* nb_inplace_power */
2035 (binaryfunc)instance_ilshift, /* nb_inplace_lshift */
2036 (binaryfunc)instance_irshift, /* nb_inplace_rshift */
2037 (binaryfunc)instance_iand, /* nb_inplace_and */
2038 (binaryfunc)instance_ixor, /* nb_inplace_xor */
2039 (binaryfunc)instance_ior, /* nb_inplace_or */
2040 (binaryfunc)instance_floordiv, /* nb_floor_divide */
2041 (binaryfunc)instance_truediv, /* nb_true_divide */
2042 (binaryfunc)instance_ifloordiv, /* nb_inplace_floor_divide */
2043 (binaryfunc)instance_itruediv, /* nb_inplace_true_divide */
2046 PyTypeObject PyInstance_Type = {
2047 PyObject_HEAD_INIT(&PyType_Type)
2049 "instance",
2050 sizeof(PyInstanceObject),
2052 (destructor)instance_dealloc, /* tp_dealloc */
2053 0, /* tp_print */
2054 0, /* tp_getattr */
2055 0, /* tp_setattr */
2056 instance_compare, /* tp_compare */
2057 (reprfunc)instance_repr, /* tp_repr */
2058 &instance_as_number, /* tp_as_number */
2059 &instance_as_sequence, /* tp_as_sequence */
2060 &instance_as_mapping, /* tp_as_mapping */
2061 (hashfunc)instance_hash, /* tp_hash */
2062 instance_call, /* tp_call */
2063 (reprfunc)instance_str, /* tp_str */
2064 (getattrofunc)instance_getattr, /* tp_getattro */
2065 (setattrofunc)instance_setattr, /* tp_setattro */
2066 0, /* tp_as_buffer */
2067 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2068 instance_doc, /* tp_doc */
2069 (traverseproc)instance_traverse, /* tp_traverse */
2070 0, /* tp_clear */
2071 instance_richcompare, /* tp_richcompare */
2072 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2073 (getiterfunc)instance_getiter, /* tp_iter */
2074 (iternextfunc)instance_iternext, /* tp_iternext */
2075 0, /* tp_methods */
2076 0, /* tp_members */
2077 0, /* tp_getset */
2078 0, /* tp_base */
2079 0, /* tp_dict */
2080 0, /* tp_descr_get */
2081 0, /* tp_descr_set */
2082 0, /* tp_dictoffset */
2083 0, /* tp_init */
2084 0, /* tp_alloc */
2085 instance_new, /* tp_new */
2089 /* Instance method objects are used for two purposes:
2090 (a) as bound instance methods (returned by instancename.methodname)
2091 (b) as unbound methods (returned by ClassName.methodname)
2092 In case (b), im_self is NULL
2095 static PyMethodObject *free_list;
2097 PyObject *
2098 PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
2100 register PyMethodObject *im;
2101 if (!PyCallable_Check(func)) {
2102 PyErr_BadInternalCall();
2103 return NULL;
2105 im = free_list;
2106 if (im != NULL) {
2107 free_list = (PyMethodObject *)(im->im_self);
2108 PyObject_INIT(im, &PyMethod_Type);
2110 else {
2111 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2112 if (im == NULL)
2113 return NULL;
2115 im->im_weakreflist = NULL;
2116 Py_INCREF(func);
2117 im->im_func = func;
2118 Py_XINCREF(self);
2119 im->im_self = self;
2120 Py_XINCREF(class);
2121 im->im_class = class;
2122 _PyObject_GC_TRACK(im);
2123 return (PyObject *)im;
2126 /* Descriptors for PyMethod attributes */
2128 /* im_class, im_func and im_self are stored in the PyMethod object */
2130 #define OFF(x) offsetof(PyMethodObject, x)
2132 static PyMemberDef instancemethod_memberlist[] = {
2133 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2134 "the class associated with a method"},
2135 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2136 "the function (or other callable) implementing a method"},
2137 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2138 "the instance to which a method is bound; None for unbound methods"},
2139 {NULL} /* Sentinel */
2142 /* The getattr() implementation for PyMethod objects is similar to
2143 PyObject_GenericGetAttr(), but instead of looking in __dict__ it
2144 asks im_self for the attribute. Then the error handling is a bit
2145 different because we want to preserve the exception raised by the
2146 delegate, unless we have an alternative from our class. */
2148 static PyObject *
2149 instancemethod_getattro(PyObject *obj, PyObject *name)
2151 PyMethodObject *im = (PyMethodObject *)obj;
2152 PyTypeObject *tp = obj->ob_type;
2153 PyObject *descr = NULL, *res;
2154 descrgetfunc f = NULL;
2156 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2157 if (tp->tp_dict == NULL) {
2158 if (PyType_Ready(tp) < 0)
2159 return NULL;
2161 descr = _PyType_Lookup(tp, name);
2164 f = NULL;
2165 if (descr != NULL) {
2166 f = TP_DESCR_GET(descr->ob_type);
2167 if (f != NULL && PyDescr_IsData(descr))
2168 return f(descr, obj, (PyObject *)obj->ob_type);
2171 res = PyObject_GetAttr(im->im_func, name);
2172 if (res != NULL || !PyErr_ExceptionMatches(PyExc_AttributeError))
2173 return res;
2175 if (f != NULL) {
2176 PyErr_Clear();
2177 return f(descr, obj, (PyObject *)obj->ob_type);
2180 if (descr != NULL) {
2181 PyErr_Clear();
2182 Py_INCREF(descr);
2183 return descr;
2186 assert(PyErr_Occurred());
2187 return NULL;
2190 PyDoc_STRVAR(instancemethod_doc,
2191 "instancemethod(function, instance, class)\n\
2193 Create an instance method object.");
2195 static PyObject *
2196 instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2198 PyObject *func;
2199 PyObject *self;
2200 PyObject *classObj = NULL;
2202 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2203 &func, &self, &classObj))
2204 return NULL;
2205 if (!PyCallable_Check(func)) {
2206 PyErr_SetString(PyExc_TypeError,
2207 "first argument must be callable");
2208 return NULL;
2210 if (self == Py_None)
2211 self = NULL;
2212 return PyMethod_New(func, self, classObj);
2215 static void
2216 instancemethod_dealloc(register PyMethodObject *im)
2218 _PyObject_GC_UNTRACK(im);
2219 if (im->im_weakreflist != NULL)
2220 PyObject_ClearWeakRefs((PyObject *)im);
2221 Py_DECREF(im->im_func);
2222 Py_XDECREF(im->im_self);
2223 Py_XDECREF(im->im_class);
2224 im->im_self = (PyObject *)free_list;
2225 free_list = im;
2228 static int
2229 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2231 if (a->im_self != b->im_self)
2232 return (a->im_self < b->im_self) ? -1 : 1;
2233 return PyObject_Compare(a->im_func, b->im_func);
2236 static PyObject *
2237 instancemethod_repr(PyMethodObject *a)
2239 PyObject *self = a->im_self;
2240 PyObject *func = a->im_func;
2241 PyObject *klass = a->im_class;
2242 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2243 char *sfuncname = "?", *sklassname = "?";
2245 funcname = PyObject_GetAttrString(func, "__name__");
2246 if (funcname == NULL) {
2247 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2248 return NULL;
2249 PyErr_Clear();
2251 else if (!PyString_Check(funcname)) {
2252 Py_DECREF(funcname);
2253 funcname = NULL;
2255 else
2256 sfuncname = PyString_AS_STRING(funcname);
2257 if (klass == NULL)
2258 klassname = NULL;
2259 else {
2260 klassname = PyObject_GetAttrString(klass, "__name__");
2261 if (klassname == NULL) {
2262 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2263 return NULL;
2264 PyErr_Clear();
2266 else if (!PyString_Check(klassname)) {
2267 Py_DECREF(klassname);
2268 klassname = NULL;
2270 else
2271 sklassname = PyString_AS_STRING(klassname);
2273 if (self == NULL)
2274 result = PyString_FromFormat("<unbound method %s.%s>",
2275 sklassname, sfuncname);
2276 else {
2277 /* XXX Shouldn't use repr() here! */
2278 PyObject *selfrepr = PyObject_Repr(self);
2279 if (selfrepr == NULL)
2280 goto fail;
2281 if (!PyString_Check(selfrepr)) {
2282 Py_DECREF(selfrepr);
2283 goto fail;
2285 result = PyString_FromFormat("<bound method %s.%s of %s>",
2286 sklassname, sfuncname,
2287 PyString_AS_STRING(selfrepr));
2288 Py_DECREF(selfrepr);
2290 fail:
2291 Py_XDECREF(funcname);
2292 Py_XDECREF(klassname);
2293 return result;
2296 static long
2297 instancemethod_hash(PyMethodObject *a)
2299 long x, y;
2300 if (a->im_self == NULL)
2301 x = PyObject_Hash(Py_None);
2302 else
2303 x = PyObject_Hash(a->im_self);
2304 if (x == -1)
2305 return -1;
2306 y = PyObject_Hash(a->im_func);
2307 if (y == -1)
2308 return -1;
2309 return x ^ y;
2312 static int
2313 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2315 int err;
2316 if (im->im_func) {
2317 err = visit(im->im_func, arg);
2318 if (err)
2319 return err;
2321 if (im->im_self) {
2322 err = visit(im->im_self, arg);
2323 if (err)
2324 return err;
2326 if (im->im_class) {
2327 err = visit(im->im_class, arg);
2328 if (err)
2329 return err;
2331 return 0;
2334 static void
2335 getclassname(PyObject *class, char *buf, int bufsize)
2337 PyObject *name;
2339 assert(bufsize > 1);
2340 strcpy(buf, "?"); /* Default outcome */
2341 if (class == NULL)
2342 return;
2343 name = PyObject_GetAttrString(class, "__name__");
2344 if (name == NULL) {
2345 /* This function cannot return an exception */
2346 PyErr_Clear();
2347 return;
2349 if (PyString_Check(name)) {
2350 strncpy(buf, PyString_AS_STRING(name), bufsize);
2351 buf[bufsize-1] = '\0';
2353 Py_DECREF(name);
2356 static void
2357 getinstclassname(PyObject *inst, char *buf, int bufsize)
2359 PyObject *class;
2361 if (inst == NULL) {
2362 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2363 strcpy(buf, "nothing");
2364 return;
2367 class = PyObject_GetAttrString(inst, "__class__");
2368 if (class == NULL) {
2369 /* This function cannot return an exception */
2370 PyErr_Clear();
2371 class = (PyObject *)(inst->ob_type);
2372 Py_INCREF(class);
2374 getclassname(class, buf, bufsize);
2375 Py_XDECREF(class);
2378 static PyObject *
2379 instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2381 PyObject *self = PyMethod_GET_SELF(func);
2382 PyObject *class = PyMethod_GET_CLASS(func);
2383 PyObject *result;
2385 func = PyMethod_GET_FUNCTION(func);
2386 if (self == NULL) {
2387 /* Unbound methods must be called with an instance of
2388 the class (or a derived class) as first argument */
2389 int ok;
2390 if (PyTuple_Size(arg) >= 1)
2391 self = PyTuple_GET_ITEM(arg, 0);
2392 if (self == NULL)
2393 ok = 0;
2394 else {
2395 ok = PyObject_IsInstance(self, class);
2396 if (ok < 0)
2397 return NULL;
2399 if (!ok) {
2400 char clsbuf[256];
2401 char instbuf[256];
2402 getclassname(class, clsbuf, sizeof(clsbuf));
2403 getinstclassname(self, instbuf, sizeof(instbuf));
2404 PyErr_Format(PyExc_TypeError,
2405 "unbound method %s%s must be called with "
2406 "%s instance as first argument "
2407 "(got %s%s instead)",
2408 PyEval_GetFuncName(func),
2409 PyEval_GetFuncDesc(func),
2410 clsbuf,
2411 instbuf,
2412 self == NULL ? "" : " instance");
2413 return NULL;
2415 Py_INCREF(arg);
2417 else {
2418 int argcount = PyTuple_Size(arg);
2419 PyObject *newarg = PyTuple_New(argcount + 1);
2420 int i;
2421 if (newarg == NULL)
2422 return NULL;
2423 Py_INCREF(self);
2424 PyTuple_SET_ITEM(newarg, 0, self);
2425 for (i = 0; i < argcount; i++) {
2426 PyObject *v = PyTuple_GET_ITEM(arg, i);
2427 Py_XINCREF(v);
2428 PyTuple_SET_ITEM(newarg, i+1, v);
2430 arg = newarg;
2432 result = PyObject_Call((PyObject *)func, arg, kw);
2433 Py_DECREF(arg);
2434 return result;
2437 static PyObject *
2438 instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
2440 /* Don't rebind an already bound method, or an unbound method
2441 of a class that's not a base class of cls. */
2443 if (PyMethod_GET_SELF(meth) != NULL) {
2444 /* Already bound */
2445 Py_INCREF(meth);
2446 return meth;
2448 /* No, it is an unbound method */
2449 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2450 /* Do subclass test. If it fails, return meth unchanged. */
2451 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2452 if (ok < 0)
2453 return NULL;
2454 if (!ok) {
2455 Py_INCREF(meth);
2456 return meth;
2459 /* Bind it to obj */
2460 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
2463 PyTypeObject PyMethod_Type = {
2464 PyObject_HEAD_INIT(&PyType_Type)
2466 "instancemethod",
2467 sizeof(PyMethodObject),
2469 (destructor)instancemethod_dealloc, /* tp_dealloc */
2470 0, /* tp_print */
2471 0, /* tp_getattr */
2472 0, /* tp_setattr */
2473 (cmpfunc)instancemethod_compare, /* tp_compare */
2474 (reprfunc)instancemethod_repr, /* tp_repr */
2475 0, /* tp_as_number */
2476 0, /* tp_as_sequence */
2477 0, /* tp_as_mapping */
2478 (hashfunc)instancemethod_hash, /* tp_hash */
2479 instancemethod_call, /* tp_call */
2480 0, /* tp_str */
2481 (getattrofunc)instancemethod_getattro, /* tp_getattro */
2482 PyObject_GenericSetAttr, /* tp_setattro */
2483 0, /* tp_as_buffer */
2484 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2485 instancemethod_doc, /* tp_doc */
2486 (traverseproc)instancemethod_traverse, /* tp_traverse */
2487 0, /* tp_clear */
2488 0, /* tp_richcompare */
2489 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2490 0, /* tp_iter */
2491 0, /* tp_iternext */
2492 0, /* tp_methods */
2493 instancemethod_memberlist, /* tp_members */
2494 0, /* tp_getset */
2495 0, /* tp_base */
2496 0, /* tp_dict */
2497 instancemethod_descr_get, /* tp_descr_get */
2498 0, /* tp_descr_set */
2499 0, /* tp_dictoffset */
2500 0, /* tp_init */
2501 0, /* tp_alloc */
2502 instancemethod_new, /* tp_new */
2505 /* Clear out the free list */
2507 void
2508 PyMethod_Fini(void)
2510 while (free_list) {
2511 PyMethodObject *im = free_list;
2512 free_list = (PyMethodObject *)(im->im_self);
2513 PyObject_GC_Del(im);