- Got rid of newmodule.c
[python/dscho.git] / Objects / classobject.c
blob88bd20c29e5b3bc33eb730eee873d35e9d1c5392
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 (class == NULL || !PyClass_Check(class))
491 return 0;
492 cp = (PyClassObject *)class;
493 n = PyTuple_Size(cp->cl_bases);
494 for (i = 0; i < n; i++) {
495 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
496 return 1;
498 return 0;
502 /* Instance objects */
504 PyObject *
505 PyInstance_NewRaw(PyObject *klass, PyObject *dict)
507 PyInstanceObject *inst;
509 if (!PyClass_Check(klass)) {
510 PyErr_BadInternalCall();
511 return NULL;
513 if (dict == NULL) {
514 dict = PyDict_New();
515 if (dict == NULL)
516 return NULL;
518 else {
519 if (!PyDict_Check(dict)) {
520 PyErr_BadInternalCall();
521 return NULL;
523 Py_INCREF(dict);
525 inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
526 if (inst == NULL) {
527 Py_DECREF(dict);
528 return NULL;
530 inst->in_weakreflist = NULL;
531 Py_INCREF(klass);
532 inst->in_class = (PyClassObject *)klass;
533 inst->in_dict = dict;
534 _PyObject_GC_TRACK(inst);
535 return (PyObject *)inst;
538 PyObject *
539 PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
541 register PyInstanceObject *inst;
542 PyObject *init;
543 static PyObject *initstr;
545 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
546 if (inst == NULL)
547 return NULL;
548 if (initstr == NULL)
549 initstr = PyString_InternFromString("__init__");
550 init = instance_getattr2(inst, initstr);
551 if (init == NULL) {
552 if ((arg != NULL && (!PyTuple_Check(arg) ||
553 PyTuple_Size(arg) != 0))
554 || (kw != NULL && (!PyDict_Check(kw) ||
555 PyDict_Size(kw) != 0))) {
556 PyErr_SetString(PyExc_TypeError,
557 "this constructor takes no arguments");
558 Py_DECREF(inst);
559 inst = NULL;
562 else {
563 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
564 Py_DECREF(init);
565 if (res == NULL) {
566 Py_DECREF(inst);
567 inst = NULL;
569 else {
570 if (res != Py_None) {
571 PyErr_SetString(PyExc_TypeError,
572 "__init__() should return None");
573 Py_DECREF(inst);
574 inst = NULL;
576 Py_DECREF(res);
579 return (PyObject *)inst;
582 /* Instance methods */
584 PyDoc_STRVAR(instance_doc,
585 "instance(class[, dict])\n\
587 Create an instance without calling its __init__() method.\n\
588 The class must be a classic class.\n\
589 If present, dict must be a dictionary or None.");
591 static PyObject *
592 instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
594 PyObject *klass;
595 PyObject *dict = Py_None;
597 if (!PyArg_ParseTuple(args, "O!|O:instance",
598 &PyClass_Type, &klass, &dict))
599 return NULL;
601 if (dict == Py_None)
602 dict = NULL;
603 else if (!PyDict_Check(dict)) {
604 PyErr_SetString(PyExc_TypeError,
605 "instance() second arg must be dictionary or None");
606 return NULL;
608 return PyInstance_NewRaw(klass, dict);
612 static void
613 instance_dealloc(register PyInstanceObject *inst)
615 PyObject *error_type, *error_value, *error_traceback;
616 PyObject *del;
617 static PyObject *delstr;
618 #ifdef Py_REF_DEBUG
619 extern long _Py_RefTotal;
620 #endif
621 _PyObject_GC_UNTRACK(inst);
622 if (inst->in_weakreflist != NULL)
623 PyObject_ClearWeakRefs((PyObject *) inst);
625 /* Temporarily resurrect the object. */
626 #ifdef Py_TRACE_REFS
627 #ifndef Py_REF_DEBUG
628 # error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
629 #endif
630 /* much too complicated if Py_TRACE_REFS defined */
631 inst->ob_type = &PyInstance_Type;
632 _Py_NewReference((PyObject *)inst);
633 #ifdef COUNT_ALLOCS
634 /* compensate for boost in _Py_NewReference; note that
635 * _Py_RefTotal was also boosted; we'll knock that down later.
637 inst->ob_type->tp_allocs--;
638 #endif
639 #else /* !Py_TRACE_REFS */
640 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
641 Py_INCREF(inst);
642 #endif /* !Py_TRACE_REFS */
644 /* Save the current exception, if any. */
645 PyErr_Fetch(&error_type, &error_value, &error_traceback);
646 /* Execute __del__ method, if any. */
647 if (delstr == NULL)
648 delstr = PyString_InternFromString("__del__");
649 if ((del = instance_getattr2(inst, delstr)) != NULL) {
650 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
651 if (res == NULL)
652 PyErr_WriteUnraisable(del);
653 else
654 Py_DECREF(res);
655 Py_DECREF(del);
657 /* Restore the saved exception. */
658 PyErr_Restore(error_type, error_value, error_traceback);
659 /* Undo the temporary resurrection; can't use DECREF here, it would
660 * cause a recursive call.
662 #ifdef Py_REF_DEBUG
663 /* _Py_RefTotal was boosted either by _Py_NewReference or
664 * Py_INCREF above.
666 _Py_RefTotal--;
667 #endif
668 if (--inst->ob_refcnt > 0) {
669 #ifdef COUNT_ALLOCS
670 inst->ob_type->tp_frees--;
671 #endif
672 _PyObject_GC_TRACK(inst);
673 return; /* __del__ added a reference; don't delete now */
675 #ifdef Py_TRACE_REFS
676 _Py_ForgetReference((PyObject *)inst);
677 #ifdef COUNT_ALLOCS
678 /* compensate for increment in _Py_ForgetReference */
679 inst->ob_type->tp_frees--;
680 #endif
681 #ifndef WITH_CYCLE_GC
682 inst->ob_type = NULL;
683 #endif
684 #endif
685 Py_DECREF(inst->in_class);
686 Py_XDECREF(inst->in_dict);
687 PyObject_GC_Del(inst);
690 static PyObject *
691 instance_getattr1(register PyInstanceObject *inst, PyObject *name)
693 register PyObject *v;
694 register char *sname = PyString_AsString(name);
695 if (sname[0] == '_' && sname[1] == '_') {
696 if (strcmp(sname, "__dict__") == 0) {
697 if (PyEval_GetRestricted()) {
698 PyErr_SetString(PyExc_RuntimeError,
699 "instance.__dict__ not accessible in restricted mode");
700 return NULL;
702 Py_INCREF(inst->in_dict);
703 return inst->in_dict;
705 if (strcmp(sname, "__class__") == 0) {
706 Py_INCREF(inst->in_class);
707 return (PyObject *)inst->in_class;
710 v = instance_getattr2(inst, name);
711 if (v == NULL) {
712 PyErr_Format(PyExc_AttributeError,
713 "%.50s instance has no attribute '%.400s'",
714 PyString_AS_STRING(inst->in_class->cl_name), sname);
716 return v;
719 static PyObject *
720 instance_getattr2(register PyInstanceObject *inst, PyObject *name)
722 register PyObject *v;
723 PyClassObject *class;
724 descrgetfunc f;
726 v = PyDict_GetItem(inst->in_dict, name);
727 if (v != NULL) {
728 Py_INCREF(v);
729 return v;
731 v = class_lookup(inst->in_class, name, &class);
732 if (v != NULL) {
733 Py_INCREF(v);
734 f = TP_DESCR_GET(v->ob_type);
735 if (f != NULL) {
736 PyObject *w = f(v, (PyObject *)inst,
737 (PyObject *)(inst->in_class));
738 Py_DECREF(v);
739 v = w;
742 return v;
745 static PyObject *
746 instance_getattr(register PyInstanceObject *inst, PyObject *name)
748 register PyObject *func, *res;
749 res = instance_getattr1(inst, name);
750 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
751 PyObject *args;
752 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
753 return NULL;
754 PyErr_Clear();
755 args = Py_BuildValue("(OO)", inst, name);
756 if (args == NULL)
757 return NULL;
758 res = PyEval_CallObject(func, args);
759 Py_DECREF(args);
761 return res;
764 static int
765 instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
767 if (v == NULL) {
768 int rv = PyDict_DelItem(inst->in_dict, name);
769 if (rv < 0)
770 PyErr_Format(PyExc_AttributeError,
771 "%.50s instance has no attribute '%.400s'",
772 PyString_AS_STRING(inst->in_class->cl_name),
773 PyString_AS_STRING(name));
774 return rv;
776 else
777 return PyDict_SetItem(inst->in_dict, name, v);
780 static int
781 instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
783 PyObject *func, *args, *res, *tmp;
784 char *sname = PyString_AsString(name);
785 if (sname[0] == '_' && sname[1] == '_') {
786 int n = PyString_Size(name);
787 if (sname[n-1] == '_' && sname[n-2] == '_') {
788 if (strcmp(sname, "__dict__") == 0) {
789 if (PyEval_GetRestricted()) {
790 PyErr_SetString(PyExc_RuntimeError,
791 "__dict__ not accessible in restricted mode");
792 return -1;
794 if (v == NULL || !PyDict_Check(v)) {
795 PyErr_SetString(PyExc_TypeError,
796 "__dict__ must be set to a dictionary");
797 return -1;
799 tmp = inst->in_dict;
800 Py_INCREF(v);
801 inst->in_dict = v;
802 Py_DECREF(tmp);
803 return 0;
805 if (strcmp(sname, "__class__") == 0) {
806 if (PyEval_GetRestricted()) {
807 PyErr_SetString(PyExc_RuntimeError,
808 "__class__ not accessible in restricted mode");
809 return -1;
811 if (v == NULL || !PyClass_Check(v)) {
812 PyErr_SetString(PyExc_TypeError,
813 "__class__ must be set to a class");
814 return -1;
816 tmp = (PyObject *)(inst->in_class);
817 Py_INCREF(v);
818 inst->in_class = (PyClassObject *)v;
819 Py_DECREF(tmp);
820 return 0;
824 if (v == NULL)
825 func = inst->in_class->cl_delattr;
826 else
827 func = inst->in_class->cl_setattr;
828 if (func == NULL)
829 return instance_setattr1(inst, name, v);
830 if (v == NULL)
831 args = Py_BuildValue("(OO)", inst, name);
832 else
833 args = Py_BuildValue("(OOO)", inst, name, v);
834 if (args == NULL)
835 return -1;
836 res = PyEval_CallObject(func, args);
837 Py_DECREF(args);
838 if (res == NULL)
839 return -1;
840 Py_DECREF(res);
841 return 0;
844 static PyObject *
845 instance_repr(PyInstanceObject *inst)
847 PyObject *func;
848 PyObject *res;
849 static PyObject *reprstr;
851 if (reprstr == NULL)
852 reprstr = PyString_InternFromString("__repr__");
853 func = instance_getattr(inst, reprstr);
854 if (func == NULL) {
855 PyObject *classname, *mod;
856 char *cname;
857 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
858 return NULL;
859 PyErr_Clear();
860 classname = inst->in_class->cl_name;
861 mod = PyDict_GetItemString(inst->in_class->cl_dict,
862 "__module__");
863 if (classname != NULL && PyString_Check(classname))
864 cname = PyString_AsString(classname);
865 else
866 cname = "?";
867 if (mod == NULL || !PyString_Check(mod))
868 return PyString_FromFormat("<?.%s instance at %p>",
869 cname, inst);
870 else
871 return PyString_FromFormat("<%s.%s instance at %p>",
872 PyString_AsString(mod),
873 cname, inst);
875 res = PyEval_CallObject(func, (PyObject *)NULL);
876 Py_DECREF(func);
877 return res;
880 static PyObject *
881 instance_str(PyInstanceObject *inst)
883 PyObject *func;
884 PyObject *res;
885 static PyObject *strstr;
887 if (strstr == NULL)
888 strstr = PyString_InternFromString("__str__");
889 func = instance_getattr(inst, strstr);
890 if (func == NULL) {
891 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
892 return NULL;
893 PyErr_Clear();
894 return instance_repr(inst);
896 res = PyEval_CallObject(func, (PyObject *)NULL);
897 Py_DECREF(func);
898 return res;
901 static long
902 instance_hash(PyInstanceObject *inst)
904 PyObject *func;
905 PyObject *res;
906 long outcome;
907 static PyObject *hashstr, *eqstr, *cmpstr;
909 if (hashstr == NULL)
910 hashstr = PyString_InternFromString("__hash__");
911 func = instance_getattr(inst, hashstr);
912 if (func == NULL) {
913 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
914 return -1;
915 PyErr_Clear();
916 /* If there is no __eq__ and no __cmp__ method, we hash on the
917 address. If an __eq__ or __cmp__ method exists, there must
918 be a __hash__. */
919 if (eqstr == NULL)
920 eqstr = PyString_InternFromString("__eq__");
921 func = instance_getattr(inst, eqstr);
922 if (func == NULL) {
923 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
924 return -1;
925 PyErr_Clear();
926 if (cmpstr == NULL)
927 cmpstr = PyString_InternFromString("__cmp__");
928 func = instance_getattr(inst, cmpstr);
929 if (func == NULL) {
930 if (!PyErr_ExceptionMatches(
931 PyExc_AttributeError))
932 return -1;
933 PyErr_Clear();
934 return _Py_HashPointer(inst);
937 PyErr_SetString(PyExc_TypeError, "unhashable instance");
938 return -1;
940 res = PyEval_CallObject(func, (PyObject *)NULL);
941 Py_DECREF(func);
942 if (res == NULL)
943 return -1;
944 if (PyInt_Check(res)) {
945 outcome = PyInt_AsLong(res);
946 if (outcome == -1)
947 outcome = -2;
949 else {
950 PyErr_SetString(PyExc_TypeError,
951 "__hash__() should return an int");
952 outcome = -1;
954 Py_DECREF(res);
955 return outcome;
958 static int
959 instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
961 int err;
962 if (o->in_class) {
963 err = visit((PyObject *)(o->in_class), arg);
964 if (err)
965 return err;
967 if (o->in_dict) {
968 err = visit(o->in_dict, arg);
969 if (err)
970 return err;
972 return 0;
975 static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
976 static PyObject *iterstr, *nextstr;
978 static int
979 instance_length(PyInstanceObject *inst)
981 PyObject *func;
982 PyObject *res;
983 int outcome;
985 if (lenstr == NULL)
986 lenstr = PyString_InternFromString("__len__");
987 func = instance_getattr(inst, lenstr);
988 if (func == NULL)
989 return -1;
990 res = PyEval_CallObject(func, (PyObject *)NULL);
991 Py_DECREF(func);
992 if (res == NULL)
993 return -1;
994 if (PyInt_Check(res)) {
995 outcome = PyInt_AsLong(res);
996 if (outcome < 0)
997 PyErr_SetString(PyExc_ValueError,
998 "__len__() should return >= 0");
1000 else {
1001 PyErr_SetString(PyExc_TypeError,
1002 "__len__() should return an int");
1003 outcome = -1;
1005 Py_DECREF(res);
1006 return outcome;
1009 static PyObject *
1010 instance_subscript(PyInstanceObject *inst, PyObject *key)
1012 PyObject *func;
1013 PyObject *arg;
1014 PyObject *res;
1016 if (getitemstr == NULL)
1017 getitemstr = PyString_InternFromString("__getitem__");
1018 func = instance_getattr(inst, getitemstr);
1019 if (func == NULL)
1020 return NULL;
1021 arg = Py_BuildValue("(O)", key);
1022 if (arg == NULL) {
1023 Py_DECREF(func);
1024 return NULL;
1026 res = PyEval_CallObject(func, arg);
1027 Py_DECREF(func);
1028 Py_DECREF(arg);
1029 return res;
1032 static int
1033 instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1035 PyObject *func;
1036 PyObject *arg;
1037 PyObject *res;
1039 if (value == NULL) {
1040 if (delitemstr == NULL)
1041 delitemstr = PyString_InternFromString("__delitem__");
1042 func = instance_getattr(inst, delitemstr);
1044 else {
1045 if (setitemstr == NULL)
1046 setitemstr = PyString_InternFromString("__setitem__");
1047 func = instance_getattr(inst, setitemstr);
1049 if (func == NULL)
1050 return -1;
1051 if (value == NULL)
1052 arg = Py_BuildValue("(O)", key);
1053 else
1054 arg = Py_BuildValue("(OO)", key, value);
1055 if (arg == NULL) {
1056 Py_DECREF(func);
1057 return -1;
1059 res = PyEval_CallObject(func, arg);
1060 Py_DECREF(func);
1061 Py_DECREF(arg);
1062 if (res == NULL)
1063 return -1;
1064 Py_DECREF(res);
1065 return 0;
1068 static PyMappingMethods instance_as_mapping = {
1069 (inquiry)instance_length, /* mp_length */
1070 (binaryfunc)instance_subscript, /* mp_subscript */
1071 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
1074 static PyObject *
1075 instance_item(PyInstanceObject *inst, int i)
1077 PyObject *func, *arg, *res;
1079 if (getitemstr == NULL)
1080 getitemstr = PyString_InternFromString("__getitem__");
1081 func = instance_getattr(inst, getitemstr);
1082 if (func == NULL)
1083 return NULL;
1084 arg = Py_BuildValue("(i)", i);
1085 if (arg == NULL) {
1086 Py_DECREF(func);
1087 return NULL;
1089 res = PyEval_CallObject(func, arg);
1090 Py_DECREF(func);
1091 Py_DECREF(arg);
1092 return res;
1095 static PyObject *
1096 sliceobj_from_intint(int i, int j)
1098 PyObject *start, *end, *res;
1100 start = PyInt_FromLong((long)i);
1101 if (!start)
1102 return NULL;
1104 end = PyInt_FromLong((long)j);
1105 if (!end) {
1106 Py_DECREF(start);
1107 return NULL;
1109 res = PySlice_New(start, end, NULL);
1110 Py_DECREF(start);
1111 Py_DECREF(end);
1112 return res;
1116 static PyObject *
1117 instance_slice(PyInstanceObject *inst, int i, int j)
1119 PyObject *func, *arg, *res;
1120 static PyObject *getslicestr;
1122 if (getslicestr == NULL)
1123 getslicestr = PyString_InternFromString("__getslice__");
1124 func = instance_getattr(inst, getslicestr);
1126 if (func == NULL) {
1127 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1128 return NULL;
1129 PyErr_Clear();
1131 if (getitemstr == NULL)
1132 getitemstr = PyString_InternFromString("__getitem__");
1133 func = instance_getattr(inst, getitemstr);
1134 if (func == NULL)
1135 return NULL;
1136 arg = Py_BuildValue("(N)", sliceobj_from_intint(i, j));
1137 } else
1138 arg = Py_BuildValue("(ii)", i, j);
1140 if (arg == NULL) {
1141 Py_DECREF(func);
1142 return NULL;
1144 res = PyEval_CallObject(func, arg);
1145 Py_DECREF(func);
1146 Py_DECREF(arg);
1147 return res;
1150 static int
1151 instance_ass_item(PyInstanceObject *inst, int i, PyObject *item)
1153 PyObject *func, *arg, *res;
1155 if (item == NULL) {
1156 if (delitemstr == NULL)
1157 delitemstr = PyString_InternFromString("__delitem__");
1158 func = instance_getattr(inst, delitemstr);
1160 else {
1161 if (setitemstr == NULL)
1162 setitemstr = PyString_InternFromString("__setitem__");
1163 func = instance_getattr(inst, setitemstr);
1165 if (func == NULL)
1166 return -1;
1167 if (item == NULL)
1168 arg = Py_BuildValue("i", i);
1169 else
1170 arg = Py_BuildValue("(iO)", i, item);
1171 if (arg == NULL) {
1172 Py_DECREF(func);
1173 return -1;
1175 res = PyEval_CallObject(func, arg);
1176 Py_DECREF(func);
1177 Py_DECREF(arg);
1178 if (res == NULL)
1179 return -1;
1180 Py_DECREF(res);
1181 return 0;
1184 static int
1185 instance_ass_slice(PyInstanceObject *inst, int i, int j, PyObject *value)
1187 PyObject *func, *arg, *res;
1188 static PyObject *setslicestr, *delslicestr;
1190 if (value == NULL) {
1191 if (delslicestr == NULL)
1192 delslicestr =
1193 PyString_InternFromString("__delslice__");
1194 func = instance_getattr(inst, delslicestr);
1195 if (func == NULL) {
1196 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1197 return -1;
1198 PyErr_Clear();
1199 if (delitemstr == NULL)
1200 delitemstr =
1201 PyString_InternFromString("__delitem__");
1202 func = instance_getattr(inst, delitemstr);
1203 if (func == NULL)
1204 return -1;
1206 arg = Py_BuildValue("(N)",
1207 sliceobj_from_intint(i, j));
1208 } else
1209 arg = Py_BuildValue("(ii)", i, j);
1211 else {
1212 if (setslicestr == NULL)
1213 setslicestr =
1214 PyString_InternFromString("__setslice__");
1215 func = instance_getattr(inst, setslicestr);
1216 if (func == NULL) {
1217 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1218 return -1;
1219 PyErr_Clear();
1220 if (setitemstr == NULL)
1221 setitemstr =
1222 PyString_InternFromString("__setitem__");
1223 func = instance_getattr(inst, setitemstr);
1224 if (func == NULL)
1225 return -1;
1227 arg = Py_BuildValue("(NO)",
1228 sliceobj_from_intint(i, j), value);
1229 } else
1230 arg = Py_BuildValue("(iiO)", i, j, value);
1232 if (arg == NULL) {
1233 Py_DECREF(func);
1234 return -1;
1236 res = PyEval_CallObject(func, arg);
1237 Py_DECREF(func);
1238 Py_DECREF(arg);
1239 if (res == NULL)
1240 return -1;
1241 Py_DECREF(res);
1242 return 0;
1245 static int
1246 instance_contains(PyInstanceObject *inst, PyObject *member)
1248 static PyObject *__contains__;
1249 PyObject *func;
1251 /* Try __contains__ first.
1252 * If that can't be done, try iterator-based searching.
1255 if(__contains__ == NULL) {
1256 __contains__ = PyString_InternFromString("__contains__");
1257 if(__contains__ == NULL)
1258 return -1;
1260 func = instance_getattr(inst, __contains__);
1261 if (func) {
1262 PyObject *res;
1263 int ret;
1264 PyObject *arg = Py_BuildValue("(O)", member);
1265 if(arg == NULL) {
1266 Py_DECREF(func);
1267 return -1;
1269 res = PyEval_CallObject(func, arg);
1270 Py_DECREF(func);
1271 Py_DECREF(arg);
1272 if(res == NULL)
1273 return -1;
1274 ret = PyObject_IsTrue(res);
1275 Py_DECREF(res);
1276 return ret;
1279 /* Couldn't find __contains__. */
1280 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1281 /* Assume the failure was simply due to that there is no
1282 * __contains__ attribute, and try iterating instead.
1284 PyErr_Clear();
1285 return _PySequence_IterSearch((PyObject *)inst, member,
1286 PY_ITERSEARCH_CONTAINS);
1288 else
1289 return -1;
1292 static PySequenceMethods
1293 instance_as_sequence = {
1294 (inquiry)instance_length, /* sq_length */
1295 0, /* sq_concat */
1296 0, /* sq_repeat */
1297 (intargfunc)instance_item, /* sq_item */
1298 (intintargfunc)instance_slice, /* sq_slice */
1299 (intobjargproc)instance_ass_item, /* sq_ass_item */
1300 (intintobjargproc)instance_ass_slice, /* sq_ass_slice */
1301 (objobjproc)instance_contains, /* sq_contains */
1304 static PyObject *
1305 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1307 PyObject *func, *res;
1309 if ((func = instance_getattr(self, methodname)) == NULL)
1310 return NULL;
1311 res = PyEval_CallObject(func, (PyObject *)NULL);
1312 Py_DECREF(func);
1313 return res;
1316 static PyObject *
1317 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1319 PyObject *result;
1320 PyObject *args;
1321 PyObject *func = PyObject_GetAttrString(v, opname);
1322 if (func == NULL) {
1323 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1324 return NULL;
1325 PyErr_Clear();
1326 Py_INCREF(Py_NotImplemented);
1327 return Py_NotImplemented;
1329 args = Py_BuildValue("(O)", w);
1330 if (args == NULL) {
1331 Py_DECREF(func);
1332 return NULL;
1334 result = PyEval_CallObject(func, args);
1335 Py_DECREF(args);
1336 Py_DECREF(func);
1337 return result;
1341 static PyObject *coerce_obj;
1343 /* Try one half of a binary operator involving a class instance. */
1344 static PyObject *
1345 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1346 int swapped)
1348 PyObject *args;
1349 PyObject *coercefunc;
1350 PyObject *coerced = NULL;
1351 PyObject *v1;
1352 PyObject *result;
1354 if (!PyInstance_Check(v)) {
1355 Py_INCREF(Py_NotImplemented);
1356 return Py_NotImplemented;
1359 if (coerce_obj == NULL) {
1360 coerce_obj = PyString_InternFromString("__coerce__");
1361 if (coerce_obj == NULL)
1362 return NULL;
1364 coercefunc = PyObject_GetAttr(v, coerce_obj);
1365 if (coercefunc == NULL) {
1366 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1367 return NULL;
1368 PyErr_Clear();
1369 return generic_binary_op(v, w, opname);
1372 args = Py_BuildValue("(O)", w);
1373 if (args == NULL) {
1374 return NULL;
1376 coerced = PyEval_CallObject(coercefunc, args);
1377 Py_DECREF(args);
1378 Py_DECREF(coercefunc);
1379 if (coerced == NULL) {
1380 return NULL;
1382 if (coerced == Py_None || coerced == Py_NotImplemented) {
1383 Py_DECREF(coerced);
1384 return generic_binary_op(v, w, opname);
1386 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1387 Py_DECREF(coerced);
1388 PyErr_SetString(PyExc_TypeError,
1389 "coercion should return None or 2-tuple");
1390 return NULL;
1392 v1 = PyTuple_GetItem(coerced, 0);
1393 w = PyTuple_GetItem(coerced, 1);
1394 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1395 /* prevent recursion if __coerce__ returns self as the first
1396 * argument */
1397 result = generic_binary_op(v1, w, opname);
1398 } else {
1399 if (swapped)
1400 result = (thisfunc)(w, v1);
1401 else
1402 result = (thisfunc)(v1, w);
1404 Py_DECREF(coerced);
1405 return result;
1408 /* Implement a binary operator involving at least one class instance. */
1409 static PyObject *
1410 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1411 binaryfunc thisfunc)
1413 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1414 if (result == Py_NotImplemented) {
1415 Py_DECREF(result);
1416 result = half_binop(w, v, ropname, thisfunc, 1);
1418 return result;
1421 static PyObject *
1422 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1423 char *ropname, binaryfunc thisfunc)
1425 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1426 if (result == Py_NotImplemented) {
1427 Py_DECREF(result);
1428 result = do_binop(v, w, opname, ropname, thisfunc);
1430 return result;
1433 static int
1434 instance_coerce(PyObject **pv, PyObject **pw)
1436 PyObject *v = *pv;
1437 PyObject *w = *pw;
1438 PyObject *coercefunc;
1439 PyObject *args;
1440 PyObject *coerced;
1442 if (coerce_obj == NULL) {
1443 coerce_obj = PyString_InternFromString("__coerce__");
1444 if (coerce_obj == NULL)
1445 return -1;
1447 coercefunc = PyObject_GetAttr(v, coerce_obj);
1448 if (coercefunc == NULL) {
1449 /* No __coerce__ method */
1450 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1451 return -1;
1452 PyErr_Clear();
1453 return 1;
1455 /* Has __coerce__ method: call it */
1456 args = Py_BuildValue("(O)", w);
1457 if (args == NULL) {
1458 return -1;
1460 coerced = PyEval_CallObject(coercefunc, args);
1461 Py_DECREF(args);
1462 Py_DECREF(coercefunc);
1463 if (coerced == NULL) {
1464 /* __coerce__ call raised an exception */
1465 return -1;
1467 if (coerced == Py_None || coerced == Py_NotImplemented) {
1468 /* __coerce__ says "I can't do it" */
1469 Py_DECREF(coerced);
1470 return 1;
1472 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1473 /* __coerce__ return value is malformed */
1474 Py_DECREF(coerced);
1475 PyErr_SetString(PyExc_TypeError,
1476 "coercion should return None or 2-tuple");
1477 return -1;
1479 /* __coerce__ returned two new values */
1480 *pv = PyTuple_GetItem(coerced, 0);
1481 *pw = PyTuple_GetItem(coerced, 1);
1482 Py_INCREF(*pv);
1483 Py_INCREF(*pw);
1484 Py_DECREF(coerced);
1485 return 0;
1488 #define UNARY(funcname, methodname) \
1489 static PyObject *funcname(PyInstanceObject *self) { \
1490 static PyObject *o; \
1491 if (o == NULL) o = PyString_InternFromString(methodname); \
1492 return generic_unary_op(self, o); \
1495 #define BINARY(f, m, n) \
1496 static PyObject *f(PyObject *v, PyObject *w) { \
1497 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1500 #define BINARY_INPLACE(f, m, n) \
1501 static PyObject *f(PyObject *v, PyObject *w) { \
1502 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1503 "__r" m "__", n); \
1506 UNARY(instance_neg, "__neg__")
1507 UNARY(instance_pos, "__pos__")
1508 UNARY(instance_abs, "__abs__")
1510 BINARY(instance_or, "or", PyNumber_Or)
1511 BINARY(instance_and, "and", PyNumber_And)
1512 BINARY(instance_xor, "xor", PyNumber_Xor)
1513 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1514 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1515 BINARY(instance_add, "add", PyNumber_Add)
1516 BINARY(instance_sub, "sub", PyNumber_Subtract)
1517 BINARY(instance_mul, "mul", PyNumber_Multiply)
1518 BINARY(instance_div, "div", PyNumber_Divide)
1519 BINARY(instance_mod, "mod", PyNumber_Remainder)
1520 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1521 BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1522 BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1524 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1525 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1526 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1527 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1528 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1529 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1530 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1531 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1532 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1533 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1534 BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1535 BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1537 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1538 -2 for an exception;
1539 -1 if v < w;
1540 0 if v == w;
1541 1 if v > w;
1542 2 if this particular 3-way comparison is not implemented or undefined.
1544 static int
1545 half_cmp(PyObject *v, PyObject *w)
1547 static PyObject *cmp_obj;
1548 PyObject *args;
1549 PyObject *cmp_func;
1550 PyObject *result;
1551 long l;
1553 assert(PyInstance_Check(v));
1555 if (cmp_obj == NULL) {
1556 cmp_obj = PyString_InternFromString("__cmp__");
1557 if (cmp_obj == NULL)
1558 return -2;
1561 cmp_func = PyObject_GetAttr(v, cmp_obj);
1562 if (cmp_func == NULL) {
1563 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1564 return -2;
1565 PyErr_Clear();
1566 return 2;
1569 args = Py_BuildValue("(O)", w);
1570 if (args == NULL)
1571 return -2;
1573 result = PyEval_CallObject(cmp_func, args);
1574 Py_DECREF(args);
1575 Py_DECREF(cmp_func);
1577 if (result == NULL)
1578 return -2;
1580 if (result == Py_NotImplemented) {
1581 Py_DECREF(result);
1582 return 2;
1585 l = PyInt_AsLong(result);
1586 Py_DECREF(result);
1587 if (l == -1 && PyErr_Occurred()) {
1588 PyErr_SetString(PyExc_TypeError,
1589 "comparison did not return an int");
1590 return -2;
1593 return l < 0 ? -1 : l > 0 ? 1 : 0;
1596 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1597 We first try a coercion. Return:
1598 -2 for an exception;
1599 -1 if v < w;
1600 0 if v == w;
1601 1 if v > w;
1602 2 if this particular 3-way comparison is not implemented or undefined.
1603 THIS IS ONLY CALLED FROM object.c!
1605 static int
1606 instance_compare(PyObject *v, PyObject *w)
1608 int c;
1610 c = PyNumber_CoerceEx(&v, &w);
1611 if (c < 0)
1612 return -2;
1613 if (c == 0) {
1614 /* If neither is now an instance, use regular comparison */
1615 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1616 c = PyObject_Compare(v, w);
1617 Py_DECREF(v);
1618 Py_DECREF(w);
1619 if (PyErr_Occurred())
1620 return -2;
1621 return c < 0 ? -1 : c > 0 ? 1 : 0;
1624 else {
1625 /* The coercion didn't do anything.
1626 Treat this the same as returning v and w unchanged. */
1627 Py_INCREF(v);
1628 Py_INCREF(w);
1631 if (PyInstance_Check(v)) {
1632 c = half_cmp(v, w);
1633 if (c <= 1) {
1634 Py_DECREF(v);
1635 Py_DECREF(w);
1636 return c;
1639 if (PyInstance_Check(w)) {
1640 c = half_cmp(w, v);
1641 if (c <= 1) {
1642 Py_DECREF(v);
1643 Py_DECREF(w);
1644 if (c >= -1)
1645 c = -c;
1646 return c;
1649 Py_DECREF(v);
1650 Py_DECREF(w);
1651 return 2;
1654 static int
1655 instance_nonzero(PyInstanceObject *self)
1657 PyObject *func, *res;
1658 long outcome;
1659 static PyObject *nonzerostr;
1661 if (nonzerostr == NULL)
1662 nonzerostr = PyString_InternFromString("__nonzero__");
1663 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1664 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1665 return -1;
1666 PyErr_Clear();
1667 if (lenstr == NULL)
1668 lenstr = PyString_InternFromString("__len__");
1669 if ((func = instance_getattr(self, lenstr)) == NULL) {
1670 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1671 return -1;
1672 PyErr_Clear();
1673 /* Fall back to the default behavior:
1674 all instances are nonzero */
1675 return 1;
1678 res = PyEval_CallObject(func, (PyObject *)NULL);
1679 Py_DECREF(func);
1680 if (res == NULL)
1681 return -1;
1682 if (!PyInt_Check(res)) {
1683 Py_DECREF(res);
1684 PyErr_SetString(PyExc_TypeError,
1685 "__nonzero__ should return an int");
1686 return -1;
1688 outcome = PyInt_AsLong(res);
1689 Py_DECREF(res);
1690 if (outcome < 0) {
1691 PyErr_SetString(PyExc_ValueError,
1692 "__nonzero__ should return >= 0");
1693 return -1;
1695 return outcome > 0;
1698 UNARY(instance_invert, "__invert__")
1699 UNARY(instance_int, "__int__")
1700 UNARY(instance_long, "__long__")
1701 UNARY(instance_float, "__float__")
1702 UNARY(instance_oct, "__oct__")
1703 UNARY(instance_hex, "__hex__")
1705 static PyObject *
1706 bin_power(PyObject *v, PyObject *w)
1708 return PyNumber_Power(v, w, Py_None);
1711 /* This version is for ternary calls only (z != None) */
1712 static PyObject *
1713 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1715 if (z == Py_None) {
1716 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1718 else {
1719 PyObject *func;
1720 PyObject *args;
1721 PyObject *result;
1723 /* XXX Doesn't do coercions... */
1724 func = PyObject_GetAttrString(v, "__pow__");
1725 if (func == NULL)
1726 return NULL;
1727 args = Py_BuildValue("(OO)", w, z);
1728 if (args == NULL) {
1729 Py_DECREF(func);
1730 return NULL;
1732 result = PyEval_CallObject(func, args);
1733 Py_DECREF(func);
1734 Py_DECREF(args);
1735 return result;
1739 static PyObject *
1740 bin_inplace_power(PyObject *v, PyObject *w)
1742 return PyNumber_InPlacePower(v, w, Py_None);
1746 static PyObject *
1747 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1749 if (z == Py_None) {
1750 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1751 "__rpow__", bin_inplace_power);
1753 else {
1754 /* XXX Doesn't do coercions... */
1755 PyObject *func;
1756 PyObject *args;
1757 PyObject *result;
1759 func = PyObject_GetAttrString(v, "__ipow__");
1760 if (func == NULL) {
1761 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1762 return NULL;
1763 PyErr_Clear();
1764 return instance_pow(v, w, z);
1766 args = Py_BuildValue("(OO)", w, z);
1767 if (args == NULL) {
1768 Py_DECREF(func);
1769 return NULL;
1771 result = PyEval_CallObject(func, args);
1772 Py_DECREF(func);
1773 Py_DECREF(args);
1774 return result;
1779 /* Map rich comparison operators to their __xx__ namesakes */
1780 #define NAME_OPS 6
1781 static PyObject **name_op = NULL;
1783 static int
1784 init_name_op(void)
1786 int i;
1787 char *_name_op[] = {
1788 "__lt__",
1789 "__le__",
1790 "__eq__",
1791 "__ne__",
1792 "__gt__",
1793 "__ge__",
1796 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1797 if (name_op == NULL)
1798 return -1;
1799 for (i = 0; i < NAME_OPS; ++i) {
1800 name_op[i] = PyString_InternFromString(_name_op[i]);
1801 if (name_op[i] == NULL)
1802 return -1;
1804 return 0;
1807 static PyObject *
1808 half_richcompare(PyObject *v, PyObject *w, int op)
1810 PyObject *method;
1811 PyObject *args;
1812 PyObject *res;
1814 assert(PyInstance_Check(v));
1816 if (name_op == NULL) {
1817 if (init_name_op() < 0)
1818 return NULL;
1820 /* If the instance doesn't define an __getattr__ method, use
1821 instance_getattr2 directly because it will not set an
1822 exception on failure. */
1823 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL) {
1824 method = instance_getattr2((PyInstanceObject *)v,
1825 name_op[op]);
1826 if (method == NULL) {
1827 assert(!PyErr_Occurred());
1828 res = Py_NotImplemented;
1829 Py_INCREF(res);
1830 return res;
1832 } else {
1833 method = PyObject_GetAttr(v, name_op[op]);
1834 if (method == NULL) {
1835 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1836 return NULL;
1837 PyErr_Clear();
1838 res = Py_NotImplemented;
1839 Py_INCREF(res);
1840 return res;
1844 args = Py_BuildValue("(O)", w);
1845 if (args == NULL) {
1846 Py_DECREF(method);
1847 return NULL;
1850 res = PyEval_CallObject(method, args);
1851 Py_DECREF(args);
1852 Py_DECREF(method);
1854 return res;
1857 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1858 static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
1860 static PyObject *
1861 instance_richcompare(PyObject *v, PyObject *w, int op)
1863 PyObject *res;
1865 if (PyInstance_Check(v)) {
1866 res = half_richcompare(v, w, op);
1867 if (res != Py_NotImplemented)
1868 return res;
1869 Py_DECREF(res);
1872 if (PyInstance_Check(w)) {
1873 res = half_richcompare(w, v, swapped_op[op]);
1874 if (res != Py_NotImplemented)
1875 return res;
1876 Py_DECREF(res);
1879 Py_INCREF(Py_NotImplemented);
1880 return Py_NotImplemented;
1884 /* Get the iterator */
1885 static PyObject *
1886 instance_getiter(PyInstanceObject *self)
1888 PyObject *func;
1890 if (iterstr == NULL) {
1891 iterstr = PyString_InternFromString("__iter__");
1892 if (iterstr == NULL)
1893 return NULL;
1895 if (getitemstr == NULL) {
1896 getitemstr = PyString_InternFromString("__getitem__");
1897 if (getitemstr == NULL)
1898 return NULL;
1901 if ((func = instance_getattr(self, iterstr)) != NULL) {
1902 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1903 Py_DECREF(func);
1904 if (res != NULL && !PyIter_Check(res)) {
1905 PyErr_Format(PyExc_TypeError,
1906 "__iter__ returned non-iterator "
1907 "of type '%.100s'",
1908 res->ob_type->tp_name);
1909 Py_DECREF(res);
1910 res = NULL;
1912 return res;
1914 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1915 return NULL;
1916 PyErr_Clear();
1917 if ((func = instance_getattr(self, getitemstr)) == NULL) {
1918 PyErr_SetString(PyExc_TypeError,
1919 "iteration over non-sequence");
1920 return NULL;
1922 Py_DECREF(func);
1923 return PySeqIter_New((PyObject *)self);
1927 /* Call the iterator's next */
1928 static PyObject *
1929 instance_iternext(PyInstanceObject *self)
1931 PyObject *func;
1933 if (nextstr == NULL)
1934 nextstr = PyString_InternFromString("next");
1936 if ((func = instance_getattr(self, nextstr)) != NULL) {
1937 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1938 Py_DECREF(func);
1939 if (res != NULL) {
1940 return res;
1942 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
1943 PyErr_Clear();
1944 return NULL;
1946 return NULL;
1948 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
1949 return NULL;
1952 static PyObject *
1953 instance_call(PyObject *func, PyObject *arg, PyObject *kw)
1955 PyThreadState *tstate = PyThreadState_GET();
1956 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
1957 if (call == NULL) {
1958 PyInstanceObject *inst = (PyInstanceObject*) func;
1959 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1960 return NULL;
1961 PyErr_Clear();
1962 PyErr_Format(PyExc_AttributeError,
1963 "%.200s instance has no __call__ method",
1964 PyString_AsString(inst->in_class->cl_name));
1965 return NULL;
1967 /* We must check and increment the recursion depth here. Scenario:
1968 class A:
1969 pass
1970 A.__call__ = A() # that's right
1971 a = A() # ok
1972 a() # infinite recursion
1973 This bounces between instance_call() and PyObject_Call() without
1974 ever hitting eval_frame() (which has the main recursion check). */
1975 if (tstate->recursion_depth++ > Py_GetRecursionLimit()) {
1976 PyErr_SetString(PyExc_RuntimeError,
1977 "maximum __call__ recursion depth exceeded");
1978 res = NULL;
1980 else
1981 res = PyObject_Call(call, arg, kw);
1982 tstate->recursion_depth--;
1983 Py_DECREF(call);
1984 return res;
1988 static PyNumberMethods instance_as_number = {
1989 (binaryfunc)instance_add, /* nb_add */
1990 (binaryfunc)instance_sub, /* nb_subtract */
1991 (binaryfunc)instance_mul, /* nb_multiply */
1992 (binaryfunc)instance_div, /* nb_divide */
1993 (binaryfunc)instance_mod, /* nb_remainder */
1994 (binaryfunc)instance_divmod, /* nb_divmod */
1995 (ternaryfunc)instance_pow, /* nb_power */
1996 (unaryfunc)instance_neg, /* nb_negative */
1997 (unaryfunc)instance_pos, /* nb_positive */
1998 (unaryfunc)instance_abs, /* nb_absolute */
1999 (inquiry)instance_nonzero, /* nb_nonzero */
2000 (unaryfunc)instance_invert, /* nb_invert */
2001 (binaryfunc)instance_lshift, /* nb_lshift */
2002 (binaryfunc)instance_rshift, /* nb_rshift */
2003 (binaryfunc)instance_and, /* nb_and */
2004 (binaryfunc)instance_xor, /* nb_xor */
2005 (binaryfunc)instance_or, /* nb_or */
2006 (coercion)instance_coerce, /* nb_coerce */
2007 (unaryfunc)instance_int, /* nb_int */
2008 (unaryfunc)instance_long, /* nb_long */
2009 (unaryfunc)instance_float, /* nb_float */
2010 (unaryfunc)instance_oct, /* nb_oct */
2011 (unaryfunc)instance_hex, /* nb_hex */
2012 (binaryfunc)instance_iadd, /* nb_inplace_add */
2013 (binaryfunc)instance_isub, /* nb_inplace_subtract */
2014 (binaryfunc)instance_imul, /* nb_inplace_multiply */
2015 (binaryfunc)instance_idiv, /* nb_inplace_divide */
2016 (binaryfunc)instance_imod, /* nb_inplace_remainder */
2017 (ternaryfunc)instance_ipow, /* nb_inplace_power */
2018 (binaryfunc)instance_ilshift, /* nb_inplace_lshift */
2019 (binaryfunc)instance_irshift, /* nb_inplace_rshift */
2020 (binaryfunc)instance_iand, /* nb_inplace_and */
2021 (binaryfunc)instance_ixor, /* nb_inplace_xor */
2022 (binaryfunc)instance_ior, /* nb_inplace_or */
2023 (binaryfunc)instance_floordiv, /* nb_floor_divide */
2024 (binaryfunc)instance_truediv, /* nb_true_divide */
2025 (binaryfunc)instance_ifloordiv, /* nb_inplace_floor_divide */
2026 (binaryfunc)instance_itruediv, /* nb_inplace_true_divide */
2029 PyTypeObject PyInstance_Type = {
2030 PyObject_HEAD_INIT(&PyType_Type)
2032 "instance",
2033 sizeof(PyInstanceObject),
2035 (destructor)instance_dealloc, /* tp_dealloc */
2036 0, /* tp_print */
2037 0, /* tp_getattr */
2038 0, /* tp_setattr */
2039 instance_compare, /* tp_compare */
2040 (reprfunc)instance_repr, /* tp_repr */
2041 &instance_as_number, /* tp_as_number */
2042 &instance_as_sequence, /* tp_as_sequence */
2043 &instance_as_mapping, /* tp_as_mapping */
2044 (hashfunc)instance_hash, /* tp_hash */
2045 instance_call, /* tp_call */
2046 (reprfunc)instance_str, /* tp_str */
2047 (getattrofunc)instance_getattr, /* tp_getattro */
2048 (setattrofunc)instance_setattr, /* tp_setattro */
2049 0, /* tp_as_buffer */
2050 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2051 instance_doc, /* tp_doc */
2052 (traverseproc)instance_traverse, /* tp_traverse */
2053 0, /* tp_clear */
2054 instance_richcompare, /* tp_richcompare */
2055 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2056 (getiterfunc)instance_getiter, /* tp_iter */
2057 (iternextfunc)instance_iternext, /* tp_iternext */
2058 0, /* tp_methods */
2059 0, /* tp_members */
2060 0, /* tp_getset */
2061 0, /* tp_base */
2062 0, /* tp_dict */
2063 0, /* tp_descr_get */
2064 0, /* tp_descr_set */
2065 0, /* tp_dictoffset */
2066 0, /* tp_init */
2067 0, /* tp_alloc */
2068 instance_new, /* tp_new */
2072 /* Instance method objects are used for two purposes:
2073 (a) as bound instance methods (returned by instancename.methodname)
2074 (b) as unbound methods (returned by ClassName.methodname)
2075 In case (b), im_self is NULL
2078 static PyMethodObject *free_list;
2080 PyObject *
2081 PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
2083 register PyMethodObject *im;
2084 if (!PyCallable_Check(func)) {
2085 PyErr_BadInternalCall();
2086 return NULL;
2088 im = free_list;
2089 if (im != NULL) {
2090 free_list = (PyMethodObject *)(im->im_self);
2091 PyObject_INIT(im, &PyMethod_Type);
2093 else {
2094 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2095 if (im == NULL)
2096 return NULL;
2098 im->im_weakreflist = NULL;
2099 Py_INCREF(func);
2100 im->im_func = func;
2101 Py_XINCREF(self);
2102 im->im_self = self;
2103 Py_XINCREF(class);
2104 im->im_class = class;
2105 _PyObject_GC_TRACK(im);
2106 return (PyObject *)im;
2109 /* Descriptors for PyMethod attributes */
2111 /* im_class, im_func and im_self are stored in the PyMethod object */
2113 #define OFF(x) offsetof(PyMethodObject, x)
2115 static PyMemberDef instancemethod_memberlist[] = {
2116 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2117 "the class associated with a method"},
2118 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2119 "the function (or other callable) implementing a method"},
2120 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2121 "the instance to which a method is bound; None for unbound methods"},
2122 {NULL} /* Sentinel */
2125 /* The getattr() implementation for PyMethod objects is similar to
2126 PyObject_GenericGetAttr(), but instead of looking in __dict__ it
2127 asks im_self for the attribute. Then the error handling is a bit
2128 different because we want to preserve the exception raised by the
2129 delegate, unless we have an alternative from our class. */
2131 static PyObject *
2132 instancemethod_getattro(PyObject *obj, PyObject *name)
2134 PyMethodObject *im = (PyMethodObject *)obj;
2135 PyTypeObject *tp = obj->ob_type;
2136 PyObject *descr = NULL, *res;
2137 descrgetfunc f = NULL;
2139 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2140 if (tp->tp_dict == NULL) {
2141 if (PyType_Ready(tp) < 0)
2142 return NULL;
2144 descr = _PyType_Lookup(tp, name);
2147 f = NULL;
2148 if (descr != NULL) {
2149 f = TP_DESCR_GET(descr->ob_type);
2150 if (f != NULL && PyDescr_IsData(descr))
2151 return f(descr, obj, (PyObject *)obj->ob_type);
2154 res = PyObject_GetAttr(im->im_func, name);
2155 if (res != NULL || !PyErr_ExceptionMatches(PyExc_AttributeError))
2156 return res;
2158 if (f != NULL) {
2159 PyErr_Clear();
2160 return f(descr, obj, (PyObject *)obj->ob_type);
2163 if (descr != NULL) {
2164 PyErr_Clear();
2165 Py_INCREF(descr);
2166 return descr;
2169 assert(PyErr_Occurred());
2170 return NULL;
2173 PyDoc_STRVAR(instancemethod_doc,
2174 "instancemethod(function, instance, class)\n\
2176 Create an instance method object.");
2178 static PyObject *
2179 instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2181 PyObject *func;
2182 PyObject *self;
2183 PyObject *classObj;
2185 if (!PyArg_ParseTuple(args, "OOO:instancemethod",
2186 &func, &self, &classObj))
2187 return NULL;
2188 if (!PyCallable_Check(func)) {
2189 PyErr_SetString(PyExc_TypeError,
2190 "first argument must be callable");
2191 return NULL;
2193 if (self == Py_None)
2194 self = NULL;
2195 return PyMethod_New(func, self, classObj);
2198 static void
2199 instancemethod_dealloc(register PyMethodObject *im)
2201 _PyObject_GC_UNTRACK(im);
2202 if (im->im_weakreflist != NULL)
2203 PyObject_ClearWeakRefs((PyObject *)im);
2204 Py_DECREF(im->im_func);
2205 Py_XDECREF(im->im_self);
2206 Py_XDECREF(im->im_class);
2207 im->im_self = (PyObject *)free_list;
2208 free_list = im;
2211 static int
2212 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2214 if (a->im_self != b->im_self)
2215 return (a->im_self < b->im_self) ? -1 : 1;
2216 return PyObject_Compare(a->im_func, b->im_func);
2219 static PyObject *
2220 instancemethod_repr(PyMethodObject *a)
2222 PyObject *self = a->im_self;
2223 PyObject *func = a->im_func;
2224 PyObject *klass = a->im_class;
2225 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2226 char *sfuncname = "?", *sklassname = "?";
2228 funcname = PyObject_GetAttrString(func, "__name__");
2229 if (funcname == NULL) {
2230 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2231 return NULL;
2232 PyErr_Clear();
2234 else if (!PyString_Check(funcname)) {
2235 Py_DECREF(funcname);
2236 funcname = NULL;
2238 else
2239 sfuncname = PyString_AS_STRING(funcname);
2240 if (klass == NULL)
2241 klassname = NULL;
2242 else {
2243 klassname = PyObject_GetAttrString(klass, "__name__");
2244 if (klassname == NULL) {
2245 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2246 return NULL;
2247 PyErr_Clear();
2249 else if (!PyString_Check(klassname)) {
2250 Py_DECREF(klassname);
2251 klassname = NULL;
2253 else
2254 sklassname = PyString_AS_STRING(klassname);
2256 if (self == NULL)
2257 result = PyString_FromFormat("<unbound method %s.%s>",
2258 sklassname, sfuncname);
2259 else {
2260 /* XXX Shouldn't use repr() here! */
2261 PyObject *selfrepr = PyObject_Repr(self);
2262 if (selfrepr == NULL)
2263 goto fail;
2264 if (!PyString_Check(selfrepr)) {
2265 Py_DECREF(selfrepr);
2266 goto fail;
2268 result = PyString_FromFormat("<bound method %s.%s of %s>",
2269 sklassname, sfuncname,
2270 PyString_AS_STRING(selfrepr));
2271 Py_DECREF(selfrepr);
2273 fail:
2274 Py_XDECREF(funcname);
2275 Py_XDECREF(klassname);
2276 return result;
2279 static long
2280 instancemethod_hash(PyMethodObject *a)
2282 long x, y;
2283 if (a->im_self == NULL)
2284 x = PyObject_Hash(Py_None);
2285 else
2286 x = PyObject_Hash(a->im_self);
2287 if (x == -1)
2288 return -1;
2289 y = PyObject_Hash(a->im_func);
2290 if (y == -1)
2291 return -1;
2292 return x ^ y;
2295 static int
2296 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2298 int err;
2299 if (im->im_func) {
2300 err = visit(im->im_func, arg);
2301 if (err)
2302 return err;
2304 if (im->im_self) {
2305 err = visit(im->im_self, arg);
2306 if (err)
2307 return err;
2309 if (im->im_class) {
2310 err = visit(im->im_class, arg);
2311 if (err)
2312 return err;
2314 return 0;
2317 static char *
2318 getclassname(PyObject *class)
2320 PyObject *name;
2322 if (class == NULL)
2323 name = NULL;
2324 else
2325 name = PyObject_GetAttrString(class, "__name__");
2326 if (name == NULL) {
2327 /* This function cannot return an exception */
2328 PyErr_Clear();
2329 return "?";
2331 if (!PyString_Check(name)) {
2332 Py_DECREF(name);
2333 return "?";
2335 PyString_InternInPlace(&name);
2336 Py_DECREF(name);
2337 return PyString_AS_STRING(name);
2340 static char *
2341 getinstclassname(PyObject *inst)
2343 PyObject *class;
2344 char *name;
2346 if (inst == NULL)
2347 return "nothing";
2349 class = PyObject_GetAttrString(inst, "__class__");
2350 if (class == NULL) {
2351 /* This function cannot return an exception */
2352 PyErr_Clear();
2353 class = (PyObject *)(inst->ob_type);
2354 Py_INCREF(class);
2356 name = getclassname(class);
2357 Py_XDECREF(class);
2358 return name;
2361 static PyObject *
2362 instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2364 PyObject *self = PyMethod_GET_SELF(func);
2365 PyObject *class = PyMethod_GET_CLASS(func);
2366 PyObject *result;
2368 func = PyMethod_GET_FUNCTION(func);
2369 if (self == NULL) {
2370 /* Unbound methods must be called with an instance of
2371 the class (or a derived class) as first argument */
2372 int ok;
2373 if (PyTuple_Size(arg) >= 1)
2374 self = PyTuple_GET_ITEM(arg, 0);
2375 if (self == NULL)
2376 ok = 0;
2377 else {
2378 ok = PyObject_IsInstance(self, class);
2379 if (ok < 0)
2380 return NULL;
2382 if (!ok) {
2383 PyErr_Format(PyExc_TypeError,
2384 "unbound method %s%s must be called with "
2385 "%s instance as first argument "
2386 "(got %s%s instead)",
2387 PyEval_GetFuncName(func),
2388 PyEval_GetFuncDesc(func),
2389 getclassname(class),
2390 getinstclassname(self),
2391 self == NULL ? "" : " instance");
2392 return NULL;
2394 Py_INCREF(arg);
2396 else {
2397 int argcount = PyTuple_Size(arg);
2398 PyObject *newarg = PyTuple_New(argcount + 1);
2399 int i;
2400 if (newarg == NULL)
2401 return NULL;
2402 Py_INCREF(self);
2403 PyTuple_SET_ITEM(newarg, 0, self);
2404 for (i = 0; i < argcount; i++) {
2405 PyObject *v = PyTuple_GET_ITEM(arg, i);
2406 Py_XINCREF(v);
2407 PyTuple_SET_ITEM(newarg, i+1, v);
2409 arg = newarg;
2411 result = PyObject_Call((PyObject *)func, arg, kw);
2412 Py_DECREF(arg);
2413 return result;
2416 static PyObject *
2417 instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *class)
2419 /* Don't rebind an already bound method, or an unbound method
2420 of a class that's not a base class of class */
2421 if (PyMethod_GET_SELF(meth) != NULL ||
2422 (PyMethod_GET_CLASS(meth) != NULL &&
2423 !PyObject_IsSubclass(class, PyMethod_GET_CLASS(meth)))) {
2424 Py_INCREF(meth);
2425 return meth;
2427 if (obj == Py_None)
2428 obj = NULL;
2429 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, class);
2432 PyTypeObject PyMethod_Type = {
2433 PyObject_HEAD_INIT(&PyType_Type)
2435 "instancemethod",
2436 sizeof(PyMethodObject),
2438 (destructor)instancemethod_dealloc, /* tp_dealloc */
2439 0, /* tp_print */
2440 0, /* tp_getattr */
2441 0, /* tp_setattr */
2442 (cmpfunc)instancemethod_compare, /* tp_compare */
2443 (reprfunc)instancemethod_repr, /* tp_repr */
2444 0, /* tp_as_number */
2445 0, /* tp_as_sequence */
2446 0, /* tp_as_mapping */
2447 (hashfunc)instancemethod_hash, /* tp_hash */
2448 instancemethod_call, /* tp_call */
2449 0, /* tp_str */
2450 (getattrofunc)instancemethod_getattro, /* tp_getattro */
2451 PyObject_GenericSetAttr, /* tp_setattro */
2452 0, /* tp_as_buffer */
2453 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2454 instancemethod_doc, /* tp_doc */
2455 (traverseproc)instancemethod_traverse, /* tp_traverse */
2456 0, /* tp_clear */
2457 0, /* tp_richcompare */
2458 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2459 0, /* tp_iter */
2460 0, /* tp_iternext */
2461 0, /* tp_methods */
2462 instancemethod_memberlist, /* tp_members */
2463 0, /* tp_getset */
2464 0, /* tp_base */
2465 0, /* tp_dict */
2466 instancemethod_descr_get, /* tp_descr_get */
2467 0, /* tp_descr_set */
2468 0, /* tp_dictoffset */
2469 0, /* tp_init */
2470 0, /* tp_alloc */
2471 instancemethod_new, /* tp_new */
2474 /* Clear out the free list */
2476 void
2477 PyMethod_Fini(void)
2479 while (free_list) {
2480 PyMethodObject *im = free_list;
2481 free_list = (PyMethodObject *)(im->im_self);
2482 PyObject_GC_Del(im);