This commit was manufactured by cvs2svn to create tag 'r22a4-fork'.
[python/dscho.git] / Objects / classobject.c
blobdf10aa20ee573c7be42ae1e7848567850c58f1ec
2 /* Class object implementation */
4 #include "Python.h"
5 #include "structmember.h"
8 /* Forward */
9 static PyObject *class_lookup(PyClassObject *, PyObject *,
10 PyClassObject **);
11 static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
12 static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
14 static PyObject *getattrstr, *setattrstr, *delattrstr;
17 PyObject *
18 PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
19 /* bases is NULL or tuple of classobjects! */
21 PyClassObject *op, *dummy;
22 static PyObject *docstr, *modstr, *namestr;
23 if (docstr == NULL) {
24 docstr= PyString_InternFromString("__doc__");
25 if (docstr == NULL)
26 return NULL;
28 if (modstr == NULL) {
29 modstr= PyString_InternFromString("__module__");
30 if (modstr == NULL)
31 return NULL;
33 if (namestr == NULL) {
34 namestr= PyString_InternFromString("__name__");
35 if (namestr == NULL)
36 return NULL;
38 if (name == NULL || !PyString_Check(name)) {
39 PyErr_SetString(PyExc_TypeError,
40 "PyClass_New: name must be a string");
41 return NULL;
43 if (dict == NULL || !PyDict_Check(dict)) {
44 PyErr_SetString(PyExc_TypeError,
45 "PyClass_New: dict must be a dictionary");
46 return NULL;
48 if (PyDict_GetItem(dict, docstr) == NULL) {
49 if (PyDict_SetItem(dict, docstr, Py_None) < 0)
50 return NULL;
52 if (PyDict_GetItem(dict, modstr) == NULL) {
53 PyObject *globals = PyEval_GetGlobals();
54 if (globals != NULL) {
55 PyObject *modname = PyDict_GetItem(globals, namestr);
56 if (modname != NULL) {
57 if (PyDict_SetItem(dict, modstr, modname) < 0)
58 return NULL;
62 if (bases == NULL) {
63 bases = PyTuple_New(0);
64 if (bases == NULL)
65 return NULL;
67 else {
68 int i, n;
69 PyObject *base;
70 if (!PyTuple_Check(bases)) {
71 PyErr_SetString(PyExc_TypeError,
72 "PyClass_New: bases must be a tuple");
73 return NULL;
75 n = PyTuple_Size(bases);
76 for (i = 0; i < n; i++) {
77 base = PyTuple_GET_ITEM(bases, i);
78 if (!PyClass_Check(base)) {
79 if (PyCallable_Check(
80 (PyObject *) base->ob_type))
81 return PyObject_CallFunction(
82 (PyObject *) base->ob_type,
83 "OOO",
84 name,
85 bases,
86 dict);
87 PyErr_SetString(PyExc_TypeError,
88 "PyClass_New: base must be a class");
89 return NULL;
92 Py_INCREF(bases);
94 op = PyObject_GC_New(PyClassObject, &PyClass_Type);
95 if (op == NULL) {
96 Py_DECREF(bases);
97 return NULL;
99 op->cl_bases = bases;
100 Py_INCREF(dict);
101 op->cl_dict = dict;
102 Py_XINCREF(name);
103 op->cl_name = name;
104 if (getattrstr == NULL) {
105 getattrstr = PyString_InternFromString("__getattr__");
106 setattrstr = PyString_InternFromString("__setattr__");
107 delattrstr = PyString_InternFromString("__delattr__");
109 op->cl_getattr = class_lookup(op, getattrstr, &dummy);
110 op->cl_setattr = class_lookup(op, setattrstr, &dummy);
111 op->cl_delattr = class_lookup(op, delattrstr, &dummy);
112 Py_XINCREF(op->cl_getattr);
113 Py_XINCREF(op->cl_setattr);
114 Py_XINCREF(op->cl_delattr);
115 _PyObject_GC_TRACK(op);
116 return (PyObject *) op;
119 PyObject *
120 PyMethod_Function(PyObject *im)
122 if (!PyMethod_Check(im)) {
123 PyErr_BadInternalCall();
124 return NULL;
126 return ((PyMethodObject *)im)->im_func;
129 PyObject *
130 PyMethod_Self(PyObject *im)
132 if (!PyMethod_Check(im)) {
133 PyErr_BadInternalCall();
134 return NULL;
136 return ((PyMethodObject *)im)->im_self;
139 PyObject *
140 PyMethod_Class(PyObject *im)
142 if (!PyMethod_Check(im)) {
143 PyErr_BadInternalCall();
144 return NULL;
146 return ((PyMethodObject *)im)->im_class;
149 static PyObject *
150 class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
152 PyObject *name, *bases, *dict;
153 static char *kwlist[] = {"name", "bases", "dict", 0};
155 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
156 &name, &bases, &dict))
157 return NULL;
158 return PyClass_New(bases, dict, name);
161 /* Class methods */
163 static void
164 class_dealloc(PyClassObject *op)
166 _PyObject_GC_UNTRACK(op);
167 Py_DECREF(op->cl_bases);
168 Py_DECREF(op->cl_dict);
169 Py_XDECREF(op->cl_name);
170 Py_XDECREF(op->cl_getattr);
171 Py_XDECREF(op->cl_setattr);
172 Py_XDECREF(op->cl_delattr);
173 PyObject_GC_Del(op);
176 static PyObject *
177 class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
179 int i, n;
180 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
181 if (value != NULL) {
182 *pclass = cp;
183 return value;
185 n = PyTuple_Size(cp->cl_bases);
186 for (i = 0; i < n; i++) {
187 /* XXX What if one of the bases is not a class? */
188 PyObject *v = class_lookup(
189 (PyClassObject *)
190 PyTuple_GetItem(cp->cl_bases, i), name, pclass);
191 if (v != NULL)
192 return v;
194 return NULL;
197 static PyObject *
198 class_getattr(register PyClassObject *op, PyObject *name)
200 register PyObject *v;
201 register char *sname = PyString_AsString(name);
202 PyClassObject *class;
203 descrgetfunc f;
205 if (sname[0] == '_' && sname[1] == '_') {
206 if (strcmp(sname, "__dict__") == 0) {
207 if (PyEval_GetRestricted()) {
208 PyErr_SetString(PyExc_RuntimeError,
209 "class.__dict__ not accessible in restricted mode");
210 return NULL;
212 Py_INCREF(op->cl_dict);
213 return op->cl_dict;
215 if (strcmp(sname, "__bases__") == 0) {
216 Py_INCREF(op->cl_bases);
217 return op->cl_bases;
219 if (strcmp(sname, "__name__") == 0) {
220 if (op->cl_name == NULL)
221 v = Py_None;
222 else
223 v = op->cl_name;
224 Py_INCREF(v);
225 return v;
228 v = class_lookup(op, name, &class);
229 if (v == NULL) {
230 PyErr_Format(PyExc_AttributeError,
231 "class %.50s has no attribute '%.400s'",
232 PyString_AS_STRING(op->cl_name), sname);
233 return NULL;
235 f = v->ob_type->tp_descr_get;
236 if (f == NULL)
237 Py_INCREF(v);
238 else
239 v = f(v, (PyObject *)NULL, (PyObject *)op);
240 return v;
243 static void
244 set_slot(PyObject **slot, PyObject *v)
246 PyObject *temp = *slot;
247 Py_XINCREF(v);
248 *slot = v;
249 Py_XDECREF(temp);
252 static void
253 set_attr_slots(PyClassObject *c)
255 PyClassObject *dummy;
257 set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
258 set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
259 set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
262 static char *
263 set_dict(PyClassObject *c, PyObject *v)
265 if (v == NULL || !PyDict_Check(v))
266 return "__dict__ must be a dictionary object";
267 set_slot(&c->cl_dict, v);
268 set_attr_slots(c);
269 return "";
272 static char *
273 set_bases(PyClassObject *c, PyObject *v)
275 int i, n;
277 if (v == NULL || !PyTuple_Check(v))
278 return "__bases__ must be a tuple object";
279 n = PyTuple_Size(v);
280 for (i = 0; i < n; i++) {
281 PyObject *x = PyTuple_GET_ITEM(v, i);
282 if (!PyClass_Check(x))
283 return "__bases__ items must be classes";
284 if (PyClass_IsSubclass(x, (PyObject *)c))
285 return "a __bases__ item causes an inheritance cycle";
287 set_slot(&c->cl_bases, v);
288 set_attr_slots(c);
289 return "";
292 static char *
293 set_name(PyClassObject *c, PyObject *v)
295 if (v == NULL || !PyString_Check(v))
296 return "__name__ must be a string object";
297 if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
298 return "__name__ must not contain null bytes";
299 set_slot(&c->cl_name, v);
300 return "";
303 static int
304 class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
306 char *sname;
307 if (PyEval_GetRestricted()) {
308 PyErr_SetString(PyExc_RuntimeError,
309 "classes are read-only in restricted mode");
310 return -1;
312 sname = PyString_AsString(name);
313 if (sname[0] == '_' && sname[1] == '_') {
314 int n = PyString_Size(name);
315 if (sname[n-1] == '_' && sname[n-2] == '_') {
316 char *err = NULL;
317 if (strcmp(sname, "__dict__") == 0)
318 err = set_dict(op, v);
319 else if (strcmp(sname, "__bases__") == 0)
320 err = set_bases(op, v);
321 else if (strcmp(sname, "__name__") == 0)
322 err = set_name(op, v);
323 else if (strcmp(sname, "__getattr__") == 0)
324 set_slot(&op->cl_getattr, v);
325 else if (strcmp(sname, "__setattr__") == 0)
326 set_slot(&op->cl_setattr, v);
327 else if (strcmp(sname, "__delattr__") == 0)
328 set_slot(&op->cl_delattr, v);
329 /* For the last three, we fall through to update the
330 dictionary as well. */
331 if (err != NULL) {
332 if (*err == '\0')
333 return 0;
334 PyErr_SetString(PyExc_TypeError, err);
335 return -1;
339 if (v == NULL) {
340 int rv = PyDict_DelItem(op->cl_dict, name);
341 if (rv < 0)
342 PyErr_Format(PyExc_AttributeError,
343 "class %.50s has no attribute '%.400s'",
344 PyString_AS_STRING(op->cl_name), sname);
345 return rv;
347 else
348 return PyDict_SetItem(op->cl_dict, name, v);
351 static PyObject *
352 class_repr(PyClassObject *op)
354 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
355 char *name;
356 if (op->cl_name == NULL || !PyString_Check(op->cl_name))
357 name = "?";
358 else
359 name = PyString_AsString(op->cl_name);
360 if (mod == NULL || !PyString_Check(mod))
361 return PyString_FromFormat("<class ?.%s at %p>", name, op);
362 else
363 return PyString_FromFormat("<class %s.%s at %p>",
364 PyString_AsString(mod),
365 name, op);
368 static PyObject *
369 class_str(PyClassObject *op)
371 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
372 PyObject *name = op->cl_name;
373 PyObject *res;
374 int m, n;
376 if (name == NULL || !PyString_Check(name))
377 return class_repr(op);
378 if (mod == NULL || !PyString_Check(mod)) {
379 Py_INCREF(name);
380 return name;
382 m = PyString_Size(mod);
383 n = PyString_Size(name);
384 res = PyString_FromStringAndSize((char *)NULL, m+1+n);
385 if (res != NULL) {
386 char *s = PyString_AsString(res);
387 memcpy(s, PyString_AsString(mod), m);
388 s += m;
389 *s++ = '.';
390 memcpy(s, PyString_AsString(name), n);
392 return res;
395 static int
396 class_traverse(PyClassObject *o, visitproc visit, void *arg)
398 int err;
399 if (o->cl_bases) {
400 err = visit(o->cl_bases, arg);
401 if (err)
402 return err;
404 if (o->cl_dict) {
405 err = visit(o->cl_dict, arg);
406 if (err)
407 return err;
409 if (o->cl_name) {
410 err = visit(o->cl_name, arg);
411 if (err)
412 return err;
414 if (o->cl_getattr) {
415 err = visit(o->cl_getattr, arg);
416 if (err)
417 return err;
419 if (o->cl_setattr) {
420 err = visit(o->cl_setattr, arg);
421 if (err)
422 return err;
424 if (o->cl_delattr) {
425 err = visit(o->cl_delattr, arg);
426 if (err)
427 return err;
429 return 0;
432 PyTypeObject PyClass_Type = {
433 PyObject_HEAD_INIT(&PyType_Type)
435 "class",
436 sizeof(PyClassObject),
438 (destructor)class_dealloc, /* tp_dealloc */
439 0, /* tp_print */
440 0, /* tp_getattr */
441 0, /* tp_setattr */
442 0, /* tp_compare */
443 (reprfunc)class_repr, /* tp_repr */
444 0, /* tp_as_number */
445 0, /* tp_as_sequence */
446 0, /* tp_as_mapping */
447 0, /* tp_hash */
448 PyInstance_New, /* tp_call */
449 (reprfunc)class_str, /* tp_str */
450 (getattrofunc)class_getattr, /* tp_getattro */
451 (setattrofunc)class_setattr, /* tp_setattro */
452 0, /* tp_as_buffer */
453 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
454 0, /* tp_doc */
455 (traverseproc)class_traverse, /* tp_traverse */
456 0, /* tp_clear */
457 0, /* tp_richcompare */
458 0, /* tp_weaklistoffset */
459 0, /* tp_iter */
460 0, /* tp_iternext */
461 0, /* tp_methods */
462 0, /* tp_members */
463 0, /* tp_getset */
464 0, /* tp_base */
465 0, /* tp_dict */
466 0, /* tp_descr_get */
467 0, /* tp_descr_set */
468 0, /* tp_dictoffset */
469 0, /* tp_init */
470 0, /* tp_alloc */
471 class_new, /* tp_new */
475 PyClass_IsSubclass(PyObject *class, PyObject *base)
477 int i, n;
478 PyClassObject *cp;
479 if (class == base)
480 return 1;
481 if (class == NULL || !PyClass_Check(class))
482 return 0;
483 cp = (PyClassObject *)class;
484 n = PyTuple_Size(cp->cl_bases);
485 for (i = 0; i < n; i++) {
486 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
487 return 1;
489 return 0;
493 /* Instance objects */
495 PyObject *
496 PyInstance_NewRaw(PyObject *klass, PyObject *dict)
498 PyInstanceObject *inst;
500 if (!PyClass_Check(klass)) {
501 PyErr_BadInternalCall();
502 return NULL;
504 if (dict == NULL) {
505 dict = PyDict_New();
506 if (dict == NULL)
507 return NULL;
509 else {
510 if (!PyDict_Check(dict)) {
511 PyErr_BadInternalCall();
512 return NULL;
514 Py_INCREF(dict);
516 inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
517 if (inst == NULL) {
518 Py_DECREF(dict);
519 return NULL;
521 inst->in_weakreflist = NULL;
522 Py_INCREF(klass);
523 inst->in_class = (PyClassObject *)klass;
524 inst->in_dict = dict;
525 _PyObject_GC_TRACK(inst);
526 return (PyObject *)inst;
529 PyObject *
530 PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
532 register PyInstanceObject *inst;
533 PyObject *init;
534 static PyObject *initstr;
536 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
537 if (inst == NULL)
538 return NULL;
539 if (initstr == NULL)
540 initstr = PyString_InternFromString("__init__");
541 init = instance_getattr2(inst, initstr);
542 if (init == NULL) {
543 if ((arg != NULL && (!PyTuple_Check(arg) ||
544 PyTuple_Size(arg) != 0))
545 || (kw != NULL && (!PyDict_Check(kw) ||
546 PyDict_Size(kw) != 0))) {
547 PyErr_SetString(PyExc_TypeError,
548 "this constructor takes no arguments");
549 Py_DECREF(inst);
550 inst = NULL;
553 else {
554 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
555 Py_DECREF(init);
556 if (res == NULL) {
557 Py_DECREF(inst);
558 inst = NULL;
560 else {
561 if (res != Py_None) {
562 PyErr_SetString(PyExc_TypeError,
563 "__init__() should return None");
564 Py_DECREF(inst);
565 inst = NULL;
567 Py_DECREF(res);
570 return (PyObject *)inst;
573 /* Instance methods */
575 static void
576 instance_dealloc(register PyInstanceObject *inst)
578 PyObject *error_type, *error_value, *error_traceback;
579 PyObject *del;
580 static PyObject *delstr;
581 #ifdef Py_REF_DEBUG
582 extern long _Py_RefTotal;
583 #endif
584 _PyObject_GC_UNTRACK(inst);
585 PyObject_ClearWeakRefs((PyObject *) inst);
587 /* Temporarily resurrect the object. */
588 #ifdef Py_TRACE_REFS
589 #ifndef Py_REF_DEBUG
590 # error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
591 #endif
592 /* much too complicated if Py_TRACE_REFS defined */
593 inst->ob_type = &PyInstance_Type;
594 _Py_NewReference((PyObject *)inst);
595 #ifdef COUNT_ALLOCS
596 /* compensate for boost in _Py_NewReference; note that
597 * _Py_RefTotal was also boosted; we'll knock that down later.
599 inst->ob_type->tp_allocs--;
600 #endif
601 #else /* !Py_TRACE_REFS */
602 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
603 Py_INCREF(inst);
604 #endif /* !Py_TRACE_REFS */
606 /* Save the current exception, if any. */
607 PyErr_Fetch(&error_type, &error_value, &error_traceback);
608 /* Execute __del__ method, if any. */
609 if (delstr == NULL)
610 delstr = PyString_InternFromString("__del__");
611 if ((del = instance_getattr2(inst, delstr)) != NULL) {
612 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
613 if (res == NULL)
614 PyErr_WriteUnraisable(del);
615 else
616 Py_DECREF(res);
617 Py_DECREF(del);
619 /* Restore the saved exception. */
620 PyErr_Restore(error_type, error_value, error_traceback);
621 /* Undo the temporary resurrection; can't use DECREF here, it would
622 * cause a recursive call.
624 #ifdef Py_REF_DEBUG
625 /* _Py_RefTotal was boosted either by _Py_NewReference or
626 * Py_INCREF above.
628 _Py_RefTotal--;
629 #endif
630 if (--inst->ob_refcnt > 0) {
631 #ifdef COUNT_ALLOCS
632 inst->ob_type->tp_frees--;
633 #endif
634 _PyObject_GC_TRACK(inst);
635 return; /* __del__ added a reference; don't delete now */
637 #ifdef Py_TRACE_REFS
638 _Py_ForgetReference((PyObject *)inst);
639 #ifdef COUNT_ALLOCS
640 /* compensate for increment in _Py_ForgetReference */
641 inst->ob_type->tp_frees--;
642 #endif
643 #ifndef WITH_CYCLE_GC
644 inst->ob_type = NULL;
645 #endif
646 #endif
647 Py_DECREF(inst->in_class);
648 Py_XDECREF(inst->in_dict);
649 PyObject_GC_Del(inst);
652 static PyObject *
653 instance_getattr1(register PyInstanceObject *inst, PyObject *name)
655 register PyObject *v;
656 register char *sname = PyString_AsString(name);
657 if (sname[0] == '_' && sname[1] == '_') {
658 if (strcmp(sname, "__dict__") == 0) {
659 if (PyEval_GetRestricted()) {
660 PyErr_SetString(PyExc_RuntimeError,
661 "instance.__dict__ not accessible in restricted mode");
662 return NULL;
664 Py_INCREF(inst->in_dict);
665 return inst->in_dict;
667 if (strcmp(sname, "__class__") == 0) {
668 Py_INCREF(inst->in_class);
669 return (PyObject *)inst->in_class;
672 v = instance_getattr2(inst, name);
673 if (v == NULL) {
674 PyErr_Format(PyExc_AttributeError,
675 "%.50s instance has no attribute '%.400s'",
676 PyString_AS_STRING(inst->in_class->cl_name), sname);
678 return v;
681 static PyObject *
682 instance_getattr2(register PyInstanceObject *inst, PyObject *name)
684 register PyObject *v;
685 PyClassObject *class;
686 descrgetfunc f;
688 v = PyDict_GetItem(inst->in_dict, name);
689 if (v != NULL) {
690 Py_INCREF(v);
691 return v;
693 v = class_lookup(inst->in_class, name, &class);
694 if (v != NULL) {
695 Py_INCREF(v);
696 f = v->ob_type->tp_descr_get;
697 if (f != NULL) {
698 PyObject *w = f(v, (PyObject *)inst,
699 (PyObject *)(inst->in_class));
700 Py_DECREF(v);
701 v = w;
704 return v;
707 static PyObject *
708 instance_getattr(register PyInstanceObject *inst, PyObject *name)
710 register PyObject *func, *res;
711 res = instance_getattr1(inst, name);
712 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
713 PyObject *args;
714 PyErr_Clear();
715 args = Py_BuildValue("(OO)", inst, name);
716 if (args == NULL)
717 return NULL;
718 res = PyEval_CallObject(func, args);
719 Py_DECREF(args);
721 return res;
724 static int
725 instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
727 if (v == NULL) {
728 int rv = PyDict_DelItem(inst->in_dict, name);
729 if (rv < 0)
730 PyErr_Format(PyExc_AttributeError,
731 "%.50s instance has no attribute '%.400s'",
732 PyString_AS_STRING(inst->in_class->cl_name),
733 PyString_AS_STRING(name));
734 return rv;
736 else
737 return PyDict_SetItem(inst->in_dict, name, v);
740 static int
741 instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
743 PyObject *func, *args, *res, *tmp;
744 char *sname = PyString_AsString(name);
745 if (sname[0] == '_' && sname[1] == '_') {
746 int n = PyString_Size(name);
747 if (sname[n-1] == '_' && sname[n-2] == '_') {
748 if (strcmp(sname, "__dict__") == 0) {
749 if (PyEval_GetRestricted()) {
750 PyErr_SetString(PyExc_RuntimeError,
751 "__dict__ not accessible in restricted mode");
752 return -1;
754 if (v == NULL || !PyDict_Check(v)) {
755 PyErr_SetString(PyExc_TypeError,
756 "__dict__ must be set to a dictionary");
757 return -1;
759 tmp = inst->in_dict;
760 Py_INCREF(v);
761 inst->in_dict = v;
762 Py_DECREF(tmp);
763 return 0;
765 if (strcmp(sname, "__class__") == 0) {
766 if (PyEval_GetRestricted()) {
767 PyErr_SetString(PyExc_RuntimeError,
768 "__class__ not accessible in restricted mode");
769 return -1;
771 if (v == NULL || !PyClass_Check(v)) {
772 PyErr_SetString(PyExc_TypeError,
773 "__class__ must be set to a class");
774 return -1;
776 tmp = (PyObject *)(inst->in_class);
777 Py_INCREF(v);
778 inst->in_class = (PyClassObject *)v;
779 Py_DECREF(tmp);
780 return 0;
784 if (v == NULL)
785 func = inst->in_class->cl_delattr;
786 else
787 func = inst->in_class->cl_setattr;
788 if (func == NULL)
789 return instance_setattr1(inst, name, v);
790 if (v == NULL)
791 args = Py_BuildValue("(OO)", inst, name);
792 else
793 args = Py_BuildValue("(OOO)", inst, name, v);
794 if (args == NULL)
795 return -1;
796 res = PyEval_CallObject(func, args);
797 Py_DECREF(args);
798 if (res == NULL)
799 return -1;
800 Py_DECREF(res);
801 return 0;
804 static PyObject *
805 instance_repr(PyInstanceObject *inst)
807 PyObject *func;
808 PyObject *res;
809 static PyObject *reprstr;
811 if (reprstr == NULL)
812 reprstr = PyString_InternFromString("__repr__");
813 func = instance_getattr(inst, reprstr);
814 if (func == NULL) {
815 PyObject *classname = inst->in_class->cl_name;
816 PyObject *mod = PyDict_GetItemString(
817 inst->in_class->cl_dict, "__module__");
818 char *cname;
819 if (classname != NULL && PyString_Check(classname))
820 cname = PyString_AsString(classname);
821 else
822 cname = "?";
823 PyErr_Clear();
824 if (mod == NULL || !PyString_Check(mod))
825 return PyString_FromFormat("<?.%s instance at %p>",
826 cname, inst);
827 else
828 return PyString_FromFormat("<%s.%s instance at %p>",
829 PyString_AsString(mod),
830 cname, inst);
832 res = PyEval_CallObject(func, (PyObject *)NULL);
833 Py_DECREF(func);
834 return res;
837 static PyObject *
838 instance_str(PyInstanceObject *inst)
840 PyObject *func;
841 PyObject *res;
842 static PyObject *strstr;
844 if (strstr == NULL)
845 strstr = PyString_InternFromString("__str__");
846 func = instance_getattr(inst, strstr);
847 if (func == NULL) {
848 PyErr_Clear();
849 return instance_repr(inst);
851 res = PyEval_CallObject(func, (PyObject *)NULL);
852 Py_DECREF(func);
853 return res;
856 static long
857 instance_hash(PyInstanceObject *inst)
859 PyObject *func;
860 PyObject *res;
861 long outcome;
862 static PyObject *hashstr, *eqstr, *cmpstr;
864 if (hashstr == NULL)
865 hashstr = PyString_InternFromString("__hash__");
866 func = instance_getattr(inst, hashstr);
867 if (func == NULL) {
868 /* If there is no __eq__ and no __cmp__ method, we hash on the
869 address. If an __eq__ or __cmp__ method exists, there must
870 be a __hash__. */
871 PyErr_Clear();
872 if (eqstr == NULL)
873 eqstr = PyString_InternFromString("__eq__");
874 func = instance_getattr(inst, eqstr);
875 if (func == NULL) {
876 PyErr_Clear();
877 if (cmpstr == NULL)
878 cmpstr = PyString_InternFromString("__cmp__");
879 func = instance_getattr(inst, cmpstr);
880 if (func == NULL) {
881 PyErr_Clear();
882 return _Py_HashPointer(inst);
885 PyErr_SetString(PyExc_TypeError, "unhashable instance");
886 return -1;
888 res = PyEval_CallObject(func, (PyObject *)NULL);
889 Py_DECREF(func);
890 if (res == NULL)
891 return -1;
892 if (PyInt_Check(res)) {
893 outcome = PyInt_AsLong(res);
894 if (outcome == -1)
895 outcome = -2;
897 else {
898 PyErr_SetString(PyExc_TypeError,
899 "__hash__() should return an int");
900 outcome = -1;
902 Py_DECREF(res);
903 return outcome;
906 static int
907 instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
909 int err;
910 if (o->in_class) {
911 err = visit((PyObject *)(o->in_class), arg);
912 if (err)
913 return err;
915 if (o->in_dict) {
916 err = visit(o->in_dict, arg);
917 if (err)
918 return err;
920 return 0;
923 static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
924 static PyObject *iterstr, *nextstr;
926 static int
927 instance_length(PyInstanceObject *inst)
929 PyObject *func;
930 PyObject *res;
931 int outcome;
933 if (lenstr == NULL)
934 lenstr = PyString_InternFromString("__len__");
935 func = instance_getattr(inst, lenstr);
936 if (func == NULL)
937 return -1;
938 res = PyEval_CallObject(func, (PyObject *)NULL);
939 Py_DECREF(func);
940 if (res == NULL)
941 return -1;
942 if (PyInt_Check(res)) {
943 outcome = PyInt_AsLong(res);
944 if (outcome < 0)
945 PyErr_SetString(PyExc_ValueError,
946 "__len__() should return >= 0");
948 else {
949 PyErr_SetString(PyExc_TypeError,
950 "__len__() should return an int");
951 outcome = -1;
953 Py_DECREF(res);
954 return outcome;
957 static PyObject *
958 instance_subscript(PyInstanceObject *inst, PyObject *key)
960 PyObject *func;
961 PyObject *arg;
962 PyObject *res;
964 if (getitemstr == NULL)
965 getitemstr = PyString_InternFromString("__getitem__");
966 func = instance_getattr(inst, getitemstr);
967 if (func == NULL)
968 return NULL;
969 arg = Py_BuildValue("(O)", key);
970 if (arg == NULL) {
971 Py_DECREF(func);
972 return NULL;
974 res = PyEval_CallObject(func, arg);
975 Py_DECREF(func);
976 Py_DECREF(arg);
977 return res;
980 static int
981 instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
983 PyObject *func;
984 PyObject *arg;
985 PyObject *res;
987 if (value == NULL) {
988 if (delitemstr == NULL)
989 delitemstr = PyString_InternFromString("__delitem__");
990 func = instance_getattr(inst, delitemstr);
992 else {
993 if (setitemstr == NULL)
994 setitemstr = PyString_InternFromString("__setitem__");
995 func = instance_getattr(inst, setitemstr);
997 if (func == NULL)
998 return -1;
999 if (value == NULL)
1000 arg = Py_BuildValue("(O)", key);
1001 else
1002 arg = Py_BuildValue("(OO)", key, value);
1003 if (arg == NULL) {
1004 Py_DECREF(func);
1005 return -1;
1007 res = PyEval_CallObject(func, arg);
1008 Py_DECREF(func);
1009 Py_DECREF(arg);
1010 if (res == NULL)
1011 return -1;
1012 Py_DECREF(res);
1013 return 0;
1016 static PyMappingMethods instance_as_mapping = {
1017 (inquiry)instance_length, /* mp_length */
1018 (binaryfunc)instance_subscript, /* mp_subscript */
1019 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
1022 static PyObject *
1023 instance_item(PyInstanceObject *inst, int i)
1025 PyObject *func, *arg, *res;
1027 if (getitemstr == NULL)
1028 getitemstr = PyString_InternFromString("__getitem__");
1029 func = instance_getattr(inst, getitemstr);
1030 if (func == NULL)
1031 return NULL;
1032 arg = Py_BuildValue("(i)", i);
1033 if (arg == NULL) {
1034 Py_DECREF(func);
1035 return NULL;
1037 res = PyEval_CallObject(func, arg);
1038 Py_DECREF(func);
1039 Py_DECREF(arg);
1040 return res;
1043 static PyObject *
1044 sliceobj_from_intint(int i, int j)
1046 PyObject *start, *end, *res;
1048 start = PyInt_FromLong((long)i);
1049 if (!start)
1050 return NULL;
1052 end = PyInt_FromLong((long)j);
1053 if (!end) {
1054 Py_DECREF(start);
1055 return NULL;
1057 res = PySlice_New(start, end, NULL);
1058 Py_DECREF(start);
1059 Py_DECREF(end);
1060 return res;
1064 static PyObject *
1065 instance_slice(PyInstanceObject *inst, int i, int j)
1067 PyObject *func, *arg, *res;
1068 static PyObject *getslicestr;
1070 if (getslicestr == NULL)
1071 getslicestr = PyString_InternFromString("__getslice__");
1072 func = instance_getattr(inst, getslicestr);
1074 if (func == NULL) {
1075 PyErr_Clear();
1077 if (getitemstr == NULL)
1078 getitemstr = PyString_InternFromString("__getitem__");
1079 func = instance_getattr(inst, getitemstr);
1080 if (func == NULL)
1081 return NULL;
1082 arg = Py_BuildValue("(N)", sliceobj_from_intint(i, j));
1083 } else
1084 arg = Py_BuildValue("(ii)", i, j);
1086 if (arg == NULL) {
1087 Py_DECREF(func);
1088 return NULL;
1090 res = PyEval_CallObject(func, arg);
1091 Py_DECREF(func);
1092 Py_DECREF(arg);
1093 return res;
1096 static int
1097 instance_ass_item(PyInstanceObject *inst, int i, PyObject *item)
1099 PyObject *func, *arg, *res;
1101 if (item == NULL) {
1102 if (delitemstr == NULL)
1103 delitemstr = PyString_InternFromString("__delitem__");
1104 func = instance_getattr(inst, delitemstr);
1106 else {
1107 if (setitemstr == NULL)
1108 setitemstr = PyString_InternFromString("__setitem__");
1109 func = instance_getattr(inst, setitemstr);
1111 if (func == NULL)
1112 return -1;
1113 if (item == NULL)
1114 arg = Py_BuildValue("i", i);
1115 else
1116 arg = Py_BuildValue("(iO)", i, item);
1117 if (arg == NULL) {
1118 Py_DECREF(func);
1119 return -1;
1121 res = PyEval_CallObject(func, arg);
1122 Py_DECREF(func);
1123 Py_DECREF(arg);
1124 if (res == NULL)
1125 return -1;
1126 Py_DECREF(res);
1127 return 0;
1130 static int
1131 instance_ass_slice(PyInstanceObject *inst, int i, int j, PyObject *value)
1133 PyObject *func, *arg, *res;
1134 static PyObject *setslicestr, *delslicestr;
1136 if (value == NULL) {
1137 if (delslicestr == NULL)
1138 delslicestr =
1139 PyString_InternFromString("__delslice__");
1140 func = instance_getattr(inst, delslicestr);
1141 if (func == NULL) {
1142 PyErr_Clear();
1143 if (delitemstr == NULL)
1144 delitemstr =
1145 PyString_InternFromString("__delitem__");
1146 func = instance_getattr(inst, delitemstr);
1147 if (func == NULL)
1148 return -1;
1150 arg = Py_BuildValue("(N)",
1151 sliceobj_from_intint(i, j));
1152 } else
1153 arg = Py_BuildValue("(ii)", i, j);
1155 else {
1156 if (setslicestr == NULL)
1157 setslicestr =
1158 PyString_InternFromString("__setslice__");
1159 func = instance_getattr(inst, setslicestr);
1160 if (func == NULL) {
1161 PyErr_Clear();
1162 if (setitemstr == NULL)
1163 setitemstr =
1164 PyString_InternFromString("__setitem__");
1165 func = instance_getattr(inst, setitemstr);
1166 if (func == NULL)
1167 return -1;
1169 arg = Py_BuildValue("(NO)",
1170 sliceobj_from_intint(i, j), value);
1171 } else
1172 arg = Py_BuildValue("(iiO)", i, j, value);
1174 if (arg == NULL) {
1175 Py_DECREF(func);
1176 return -1;
1178 res = PyEval_CallObject(func, arg);
1179 Py_DECREF(func);
1180 Py_DECREF(arg);
1181 if (res == NULL)
1182 return -1;
1183 Py_DECREF(res);
1184 return 0;
1187 static int
1188 instance_contains(PyInstanceObject *inst, PyObject *member)
1190 static PyObject *__contains__;
1191 PyObject *func;
1193 /* Try __contains__ first.
1194 * If that can't be done, try iterator-based searching.
1197 if(__contains__ == NULL) {
1198 __contains__ = PyString_InternFromString("__contains__");
1199 if(__contains__ == NULL)
1200 return -1;
1202 func = instance_getattr(inst, __contains__);
1203 if (func) {
1204 PyObject *res;
1205 int ret;
1206 PyObject *arg = Py_BuildValue("(O)", member);
1207 if(arg == NULL) {
1208 Py_DECREF(func);
1209 return -1;
1211 res = PyEval_CallObject(func, arg);
1212 Py_DECREF(func);
1213 Py_DECREF(arg);
1214 if(res == NULL)
1215 return -1;
1216 ret = PyObject_IsTrue(res);
1217 Py_DECREF(res);
1218 return ret;
1221 /* Couldn't find __contains__. */
1222 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1223 /* Assume the failure was simply due to that there is no
1224 * __contains__ attribute, and try iterating instead.
1226 PyErr_Clear();
1227 return _PySequence_IterSearch((PyObject *)inst, member,
1228 PY_ITERSEARCH_CONTAINS);
1230 else
1231 return -1;
1234 static PySequenceMethods
1235 instance_as_sequence = {
1236 (inquiry)instance_length, /* sq_length */
1237 0, /* sq_concat */
1238 0, /* sq_repeat */
1239 (intargfunc)instance_item, /* sq_item */
1240 (intintargfunc)instance_slice, /* sq_slice */
1241 (intobjargproc)instance_ass_item, /* sq_ass_item */
1242 (intintobjargproc)instance_ass_slice, /* sq_ass_slice */
1243 (objobjproc)instance_contains, /* sq_contains */
1246 static PyObject *
1247 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1249 PyObject *func, *res;
1251 if ((func = instance_getattr(self, methodname)) == NULL)
1252 return NULL;
1253 res = PyEval_CallObject(func, (PyObject *)NULL);
1254 Py_DECREF(func);
1255 return res;
1258 static PyObject *
1259 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1261 PyObject *result;
1262 PyObject *args;
1263 PyObject *func = PyObject_GetAttrString(v, opname);
1264 if (func == NULL) {
1265 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1266 return NULL;
1267 PyErr_Clear();
1268 Py_INCREF(Py_NotImplemented);
1269 return Py_NotImplemented;
1271 args = Py_BuildValue("(O)", w);
1272 if (args == NULL) {
1273 Py_DECREF(func);
1274 return NULL;
1276 result = PyEval_CallObject(func, args);
1277 Py_DECREF(args);
1278 Py_DECREF(func);
1279 return result;
1283 static PyObject *coerce_obj;
1285 /* Try one half of a binary operator involving a class instance. */
1286 static PyObject *
1287 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1288 int swapped)
1290 PyObject *args;
1291 PyObject *coercefunc;
1292 PyObject *coerced = NULL;
1293 PyObject *v1;
1294 PyObject *result;
1296 if (!PyInstance_Check(v)) {
1297 Py_INCREF(Py_NotImplemented);
1298 return Py_NotImplemented;
1301 if (coerce_obj == NULL) {
1302 coerce_obj = PyString_InternFromString("__coerce__");
1303 if (coerce_obj == NULL)
1304 return NULL;
1306 coercefunc = PyObject_GetAttr(v, coerce_obj);
1307 if (coercefunc == NULL) {
1308 PyErr_Clear();
1309 return generic_binary_op(v, w, opname);
1312 args = Py_BuildValue("(O)", w);
1313 if (args == NULL) {
1314 return NULL;
1316 coerced = PyEval_CallObject(coercefunc, args);
1317 Py_DECREF(args);
1318 Py_DECREF(coercefunc);
1319 if (coerced == NULL) {
1320 return NULL;
1322 if (coerced == Py_None || coerced == Py_NotImplemented) {
1323 Py_DECREF(coerced);
1324 return generic_binary_op(v, w, opname);
1326 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1327 Py_DECREF(coerced);
1328 PyErr_SetString(PyExc_TypeError,
1329 "coercion should return None or 2-tuple");
1330 return NULL;
1332 v1 = PyTuple_GetItem(coerced, 0);
1333 w = PyTuple_GetItem(coerced, 1);
1334 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1335 /* prevent recursion if __coerce__ returns self as the first
1336 * argument */
1337 result = generic_binary_op(v1, w, opname);
1338 } else {
1339 if (swapped)
1340 result = (thisfunc)(w, v1);
1341 else
1342 result = (thisfunc)(v1, w);
1344 Py_DECREF(coerced);
1345 return result;
1348 /* Implement a binary operator involving at least one class instance. */
1349 static PyObject *
1350 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1351 binaryfunc thisfunc)
1353 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1354 if (result == Py_NotImplemented) {
1355 Py_DECREF(result);
1356 result = half_binop(w, v, ropname, thisfunc, 1);
1358 return result;
1361 static PyObject *
1362 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1363 char *ropname, binaryfunc thisfunc)
1365 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1366 if (result == Py_NotImplemented) {
1367 Py_DECREF(result);
1368 result = do_binop(v, w, opname, ropname, thisfunc);
1370 return result;
1373 static int
1374 instance_coerce(PyObject **pv, PyObject **pw)
1376 PyObject *v = *pv;
1377 PyObject *w = *pw;
1378 PyObject *coercefunc;
1379 PyObject *args;
1380 PyObject *coerced;
1382 if (coerce_obj == NULL) {
1383 coerce_obj = PyString_InternFromString("__coerce__");
1384 if (coerce_obj == NULL)
1385 return -1;
1387 coercefunc = PyObject_GetAttr(v, coerce_obj);
1388 if (coercefunc == NULL) {
1389 /* No __coerce__ method */
1390 PyErr_Clear();
1391 return 1;
1393 /* Has __coerce__ method: call it */
1394 args = Py_BuildValue("(O)", w);
1395 if (args == NULL) {
1396 return -1;
1398 coerced = PyEval_CallObject(coercefunc, args);
1399 Py_DECREF(args);
1400 Py_DECREF(coercefunc);
1401 if (coerced == NULL) {
1402 /* __coerce__ call raised an exception */
1403 return -1;
1405 if (coerced == Py_None || coerced == Py_NotImplemented) {
1406 /* __coerce__ says "I can't do it" */
1407 Py_DECREF(coerced);
1408 return 1;
1410 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1411 /* __coerce__ return value is malformed */
1412 Py_DECREF(coerced);
1413 PyErr_SetString(PyExc_TypeError,
1414 "coercion should return None or 2-tuple");
1415 return -1;
1417 /* __coerce__ returned two new values */
1418 *pv = PyTuple_GetItem(coerced, 0);
1419 *pw = PyTuple_GetItem(coerced, 1);
1420 Py_INCREF(*pv);
1421 Py_INCREF(*pw);
1422 Py_DECREF(coerced);
1423 return 0;
1426 #define UNARY(funcname, methodname) \
1427 static PyObject *funcname(PyInstanceObject *self) { \
1428 static PyObject *o; \
1429 if (o == NULL) o = PyString_InternFromString(methodname); \
1430 return generic_unary_op(self, o); \
1433 #define BINARY(f, m, n) \
1434 static PyObject *f(PyObject *v, PyObject *w) { \
1435 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1438 #define BINARY_INPLACE(f, m, n) \
1439 static PyObject *f(PyObject *v, PyObject *w) { \
1440 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1441 "__r" m "__", n); \
1444 UNARY(instance_neg, "__neg__")
1445 UNARY(instance_pos, "__pos__")
1446 UNARY(instance_abs, "__abs__")
1448 BINARY(instance_or, "or", PyNumber_Or)
1449 BINARY(instance_and, "and", PyNumber_And)
1450 BINARY(instance_xor, "xor", PyNumber_Xor)
1451 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1452 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1453 BINARY(instance_add, "add", PyNumber_Add)
1454 BINARY(instance_sub, "sub", PyNumber_Subtract)
1455 BINARY(instance_mul, "mul", PyNumber_Multiply)
1456 BINARY(instance_div, "div", PyNumber_Divide)
1457 BINARY(instance_mod, "mod", PyNumber_Remainder)
1458 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1459 BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1460 BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1462 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1463 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1464 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1465 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1466 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1467 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1468 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1469 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1470 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1471 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1472 BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1473 BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1475 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1476 -2 for an exception;
1477 -1 if v < w;
1478 0 if v == w;
1479 1 if v > w;
1480 2 if this particular 3-way comparison is not implemented or undefined.
1482 static int
1483 half_cmp(PyObject *v, PyObject *w)
1485 static PyObject *cmp_obj;
1486 PyObject *args;
1487 PyObject *cmp_func;
1488 PyObject *result;
1489 long l;
1491 assert(PyInstance_Check(v));
1493 if (cmp_obj == NULL) {
1494 cmp_obj = PyString_InternFromString("__cmp__");
1495 if (cmp_obj == NULL)
1496 return -2;
1499 cmp_func = PyObject_GetAttr(v, cmp_obj);
1500 if (cmp_func == NULL) {
1501 PyErr_Clear();
1502 return 2;
1505 args = Py_BuildValue("(O)", w);
1506 if (args == NULL)
1507 return -2;
1509 result = PyEval_CallObject(cmp_func, args);
1510 Py_DECREF(args);
1511 Py_DECREF(cmp_func);
1513 if (result == NULL)
1514 return -2;
1516 if (result == Py_NotImplemented) {
1517 Py_DECREF(result);
1518 return 2;
1521 l = PyInt_AsLong(result);
1522 Py_DECREF(result);
1523 if (l == -1 && PyErr_Occurred()) {
1524 PyErr_SetString(PyExc_TypeError,
1525 "comparison did not return an int");
1526 return -2;
1529 return l < 0 ? -1 : l > 0 ? 1 : 0;
1532 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1533 We first try a coercion. Return:
1534 -2 for an exception;
1535 -1 if v < w;
1536 0 if v == w;
1537 1 if v > w;
1538 2 if this particular 3-way comparison is not implemented or undefined.
1539 THIS IS ONLY CALLED FROM object.c!
1541 static int
1542 instance_compare(PyObject *v, PyObject *w)
1544 int c;
1546 c = PyNumber_CoerceEx(&v, &w);
1547 if (c < 0)
1548 return -2;
1549 if (c == 0) {
1550 /* If neither is now an instance, use regular comparison */
1551 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1552 c = PyObject_Compare(v, w);
1553 Py_DECREF(v);
1554 Py_DECREF(w);
1555 if (PyErr_Occurred())
1556 return -2;
1557 return c < 0 ? -1 : c > 0 ? 1 : 0;
1560 else {
1561 /* The coercion didn't do anything.
1562 Treat this the same as returning v and w unchanged. */
1563 Py_INCREF(v);
1564 Py_INCREF(w);
1567 if (PyInstance_Check(v)) {
1568 c = half_cmp(v, w);
1569 if (c <= 1) {
1570 Py_DECREF(v);
1571 Py_DECREF(w);
1572 return c;
1575 if (PyInstance_Check(w)) {
1576 c = half_cmp(w, v);
1577 if (c <= 1) {
1578 Py_DECREF(v);
1579 Py_DECREF(w);
1580 if (c >= -1)
1581 c = -c;
1582 return c;
1585 Py_DECREF(v);
1586 Py_DECREF(w);
1587 return 2;
1590 static int
1591 instance_nonzero(PyInstanceObject *self)
1593 PyObject *func, *res;
1594 long outcome;
1595 static PyObject *nonzerostr;
1597 if (nonzerostr == NULL)
1598 nonzerostr = PyString_InternFromString("__nonzero__");
1599 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1600 PyErr_Clear();
1601 if (lenstr == NULL)
1602 lenstr = PyString_InternFromString("__len__");
1603 if ((func = instance_getattr(self, lenstr)) == NULL) {
1604 PyErr_Clear();
1605 /* Fall back to the default behavior:
1606 all instances are nonzero */
1607 return 1;
1610 res = PyEval_CallObject(func, (PyObject *)NULL);
1611 Py_DECREF(func);
1612 if (res == NULL)
1613 return -1;
1614 if (!PyInt_Check(res)) {
1615 Py_DECREF(res);
1616 PyErr_SetString(PyExc_TypeError,
1617 "__nonzero__ should return an int");
1618 return -1;
1620 outcome = PyInt_AsLong(res);
1621 Py_DECREF(res);
1622 if (outcome < 0) {
1623 PyErr_SetString(PyExc_ValueError,
1624 "__nonzero__ should return >= 0");
1625 return -1;
1627 return outcome > 0;
1630 UNARY(instance_invert, "__invert__")
1631 UNARY(instance_int, "__int__")
1632 UNARY(instance_long, "__long__")
1633 UNARY(instance_float, "__float__")
1634 UNARY(instance_oct, "__oct__")
1635 UNARY(instance_hex, "__hex__")
1637 static PyObject *
1638 bin_power(PyObject *v, PyObject *w)
1640 return PyNumber_Power(v, w, Py_None);
1643 /* This version is for ternary calls only (z != None) */
1644 static PyObject *
1645 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1647 if (z == Py_None) {
1648 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1650 else {
1651 PyObject *func;
1652 PyObject *args;
1653 PyObject *result;
1655 /* XXX Doesn't do coercions... */
1656 func = PyObject_GetAttrString(v, "__pow__");
1657 if (func == NULL)
1658 return NULL;
1659 args = Py_BuildValue("(OO)", w, z);
1660 if (args == NULL) {
1661 Py_DECREF(func);
1662 return NULL;
1664 result = PyEval_CallObject(func, args);
1665 Py_DECREF(func);
1666 Py_DECREF(args);
1667 return result;
1671 static PyObject *
1672 bin_inplace_power(PyObject *v, PyObject *w)
1674 return PyNumber_InPlacePower(v, w, Py_None);
1678 static PyObject *
1679 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1681 if (z == Py_None) {
1682 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1683 "__rpow__", bin_inplace_power);
1685 else {
1686 /* XXX Doesn't do coercions... */
1687 PyObject *func;
1688 PyObject *args;
1689 PyObject *result;
1691 func = PyObject_GetAttrString(v, "__ipow__");
1692 if (func == NULL) {
1693 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1694 return NULL;
1695 PyErr_Clear();
1696 return instance_pow(v, w, z);
1698 args = Py_BuildValue("(OO)", w, z);
1699 if (args == NULL) {
1700 Py_DECREF(func);
1701 return NULL;
1703 result = PyEval_CallObject(func, args);
1704 Py_DECREF(func);
1705 Py_DECREF(args);
1706 return result;
1711 /* Map rich comparison operators to their __xx__ namesakes */
1712 #define NAME_OPS 6
1713 static PyObject **name_op = NULL;
1715 static int
1716 init_name_op(void)
1718 int i;
1719 char *_name_op[] = {
1720 "__lt__",
1721 "__le__",
1722 "__eq__",
1723 "__ne__",
1724 "__gt__",
1725 "__ge__",
1728 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1729 if (name_op == NULL)
1730 return -1;
1731 for (i = 0; i < NAME_OPS; ++i) {
1732 name_op[i] = PyString_InternFromString(_name_op[i]);
1733 if (name_op[i] == NULL)
1734 return -1;
1736 return 0;
1739 static PyObject *
1740 half_richcompare(PyObject *v, PyObject *w, int op)
1742 PyObject *method;
1743 PyObject *args;
1744 PyObject *res;
1746 assert(PyInstance_Check(v));
1748 if (name_op == NULL) {
1749 if (init_name_op() < 0)
1750 return NULL;
1752 /* If the instance doesn't define an __getattr__ method, use
1753 instance_getattr2 directly because it will not set an
1754 exception on failure. */
1755 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL) {
1756 method = instance_getattr2((PyInstanceObject *)v,
1757 name_op[op]);
1758 if (method == NULL) {
1759 assert(!PyErr_Occurred());
1760 res = Py_NotImplemented;
1761 Py_INCREF(res);
1762 return res;
1764 } else {
1765 method = PyObject_GetAttr(v, name_op[op]);
1766 if (method == NULL) {
1767 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1768 return NULL;
1769 PyErr_Clear();
1770 res = Py_NotImplemented;
1771 Py_INCREF(res);
1772 return res;
1776 args = Py_BuildValue("(O)", w);
1777 if (args == NULL) {
1778 Py_DECREF(method);
1779 return NULL;
1782 res = PyEval_CallObject(method, args);
1783 Py_DECREF(args);
1784 Py_DECREF(method);
1786 return res;
1789 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1790 static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
1792 static PyObject *
1793 instance_richcompare(PyObject *v, PyObject *w, int op)
1795 PyObject *res;
1797 if (PyInstance_Check(v)) {
1798 res = half_richcompare(v, w, op);
1799 if (res != Py_NotImplemented)
1800 return res;
1801 Py_DECREF(res);
1804 if (PyInstance_Check(w)) {
1805 res = half_richcompare(w, v, swapped_op[op]);
1806 if (res != Py_NotImplemented)
1807 return res;
1808 Py_DECREF(res);
1811 Py_INCREF(Py_NotImplemented);
1812 return Py_NotImplemented;
1816 /* Get the iterator */
1817 static PyObject *
1818 instance_getiter(PyInstanceObject *self)
1820 PyObject *func;
1822 if (iterstr == NULL)
1823 iterstr = PyString_InternFromString("__iter__");
1824 if (getitemstr == NULL)
1825 getitemstr = PyString_InternFromString("__getitem__");
1827 if ((func = instance_getattr(self, iterstr)) != NULL) {
1828 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1829 Py_DECREF(func);
1830 if (res != NULL && !PyIter_Check(res)) {
1831 PyErr_Format(PyExc_TypeError,
1832 "__iter__ returned non-iterator "
1833 "of type '%.100s'",
1834 res->ob_type->tp_name);
1835 Py_DECREF(res);
1836 res = NULL;
1838 return res;
1840 PyErr_Clear();
1841 if ((func = instance_getattr(self, getitemstr)) == NULL) {
1842 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
1843 return NULL;
1845 Py_DECREF(func);
1846 return PySeqIter_New((PyObject *)self);
1850 /* Call the iterator's next */
1851 static PyObject *
1852 instance_iternext(PyInstanceObject *self)
1854 PyObject *func;
1856 if (nextstr == NULL)
1857 nextstr = PyString_InternFromString("next");
1859 if ((func = instance_getattr(self, nextstr)) != NULL) {
1860 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
1861 Py_DECREF(func);
1862 if (res != NULL) {
1863 return res;
1865 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
1866 PyErr_Clear();
1867 return NULL;
1869 return NULL;
1871 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
1872 return NULL;
1875 static PyObject *
1876 instance_call(PyObject *func, PyObject *arg, PyObject *kw)
1878 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
1879 if (call == NULL) {
1880 PyInstanceObject *inst = (PyInstanceObject*) func;
1881 PyErr_Clear();
1882 PyErr_Format(PyExc_AttributeError,
1883 "%.200s instance has no __call__ method",
1884 PyString_AsString(inst->in_class->cl_name));
1885 return NULL;
1887 res = PyObject_Call(call, arg, kw);
1888 Py_DECREF(call);
1889 return res;
1893 static PyNumberMethods instance_as_number = {
1894 (binaryfunc)instance_add, /* nb_add */
1895 (binaryfunc)instance_sub, /* nb_subtract */
1896 (binaryfunc)instance_mul, /* nb_multiply */
1897 (binaryfunc)instance_div, /* nb_divide */
1898 (binaryfunc)instance_mod, /* nb_remainder */
1899 (binaryfunc)instance_divmod, /* nb_divmod */
1900 (ternaryfunc)instance_pow, /* nb_power */
1901 (unaryfunc)instance_neg, /* nb_negative */
1902 (unaryfunc)instance_pos, /* nb_positive */
1903 (unaryfunc)instance_abs, /* nb_absolute */
1904 (inquiry)instance_nonzero, /* nb_nonzero */
1905 (unaryfunc)instance_invert, /* nb_invert */
1906 (binaryfunc)instance_lshift, /* nb_lshift */
1907 (binaryfunc)instance_rshift, /* nb_rshift */
1908 (binaryfunc)instance_and, /* nb_and */
1909 (binaryfunc)instance_xor, /* nb_xor */
1910 (binaryfunc)instance_or, /* nb_or */
1911 (coercion)instance_coerce, /* nb_coerce */
1912 (unaryfunc)instance_int, /* nb_int */
1913 (unaryfunc)instance_long, /* nb_long */
1914 (unaryfunc)instance_float, /* nb_float */
1915 (unaryfunc)instance_oct, /* nb_oct */
1916 (unaryfunc)instance_hex, /* nb_hex */
1917 (binaryfunc)instance_iadd, /* nb_inplace_add */
1918 (binaryfunc)instance_isub, /* nb_inplace_subtract */
1919 (binaryfunc)instance_imul, /* nb_inplace_multiply */
1920 (binaryfunc)instance_idiv, /* nb_inplace_divide */
1921 (binaryfunc)instance_imod, /* nb_inplace_remainder */
1922 (ternaryfunc)instance_ipow, /* nb_inplace_power */
1923 (binaryfunc)instance_ilshift, /* nb_inplace_lshift */
1924 (binaryfunc)instance_irshift, /* nb_inplace_rshift */
1925 (binaryfunc)instance_iand, /* nb_inplace_and */
1926 (binaryfunc)instance_ixor, /* nb_inplace_xor */
1927 (binaryfunc)instance_ior, /* nb_inplace_or */
1928 (binaryfunc)instance_floordiv, /* nb_floor_divide */
1929 (binaryfunc)instance_truediv, /* nb_true_divide */
1930 (binaryfunc)instance_ifloordiv, /* nb_inplace_floor_divide */
1931 (binaryfunc)instance_itruediv, /* nb_inplace_true_divide */
1934 PyTypeObject PyInstance_Type = {
1935 PyObject_HEAD_INIT(&PyType_Type)
1937 "instance",
1938 sizeof(PyInstanceObject),
1940 (destructor)instance_dealloc, /* tp_dealloc */
1941 0, /* tp_print */
1942 0, /* tp_getattr */
1943 0, /* tp_setattr */
1944 instance_compare, /* tp_compare */
1945 (reprfunc)instance_repr, /* tp_repr */
1946 &instance_as_number, /* tp_as_number */
1947 &instance_as_sequence, /* tp_as_sequence */
1948 &instance_as_mapping, /* tp_as_mapping */
1949 (hashfunc)instance_hash, /* tp_hash */
1950 instance_call, /* tp_call */
1951 (reprfunc)instance_str, /* tp_str */
1952 (getattrofunc)instance_getattr, /* tp_getattro */
1953 (setattrofunc)instance_setattr, /* tp_setattro */
1954 0, /* tp_as_buffer */
1955 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
1956 0, /* tp_doc */
1957 (traverseproc)instance_traverse, /* tp_traverse */
1958 0, /* tp_clear */
1959 instance_richcompare, /* tp_richcompare */
1960 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
1961 (getiterfunc)instance_getiter, /* tp_iter */
1962 (iternextfunc)instance_iternext, /* tp_iternext */
1966 /* Instance method objects are used for two purposes:
1967 (a) as bound instance methods (returned by instancename.methodname)
1968 (b) as unbound methods (returned by ClassName.methodname)
1969 In case (b), im_self is NULL
1972 static PyMethodObject *free_list;
1974 PyObject *
1975 PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
1977 register PyMethodObject *im;
1978 if (!PyCallable_Check(func)) {
1979 PyErr_BadInternalCall();
1980 return NULL;
1982 im = free_list;
1983 if (im != NULL) {
1984 free_list = (PyMethodObject *)(im->im_self);
1985 PyObject_INIT(im, &PyMethod_Type);
1987 else {
1988 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
1989 if (im == NULL)
1990 return NULL;
1992 im->im_weakreflist = NULL;
1993 Py_INCREF(func);
1994 im->im_func = func;
1995 Py_XINCREF(self);
1996 im->im_self = self;
1997 Py_XINCREF(class);
1998 im->im_class = class;
1999 _PyObject_GC_TRACK(im);
2000 return (PyObject *)im;
2003 /* Descriptors for PyMethod attributes */
2005 /* im_class, im_func and im_self are stored in the PyMethod object */
2007 #define OFF(x) offsetof(PyMethodObject, x)
2009 static PyMemberDef instancemethod_memberlist[] = {
2010 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2011 "the class associated with a method"},
2012 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2013 "the function (or other callable) implementing a method"},
2014 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2015 "the instance to which a method is bound; None for unbound methods"},
2016 {NULL} /* Sentinel */
2019 /* __dict__, __doc__ and __name__ are retrieved from im_func */
2021 static PyObject *
2022 im_get_dict(PyMethodObject *im)
2024 return PyObject_GetAttrString(im->im_func, "__dict__");
2027 static PyObject *
2028 im_get_doc(PyMethodObject *im)
2030 return PyObject_GetAttrString(im->im_func, "__doc__");
2033 static PyObject *
2034 im_get_name(PyMethodObject *im)
2036 return PyObject_GetAttrString(im->im_func, "__name__");
2039 static PyGetSetDef instancemethod_getsetlist[] = {
2040 {"__dict__", (getter)im_get_dict, NULL, "same as im_func.__dict__"},
2041 {"__doc__", (getter)im_get_doc, NULL, "same as im_func.__doc__"},
2042 {"__name__", (getter)im_get_name, NULL, "same as im_func.__name__"},
2043 {NULL} /* Sentinel */
2046 /* The getattr() implementation for PyMethod objects is similar to
2047 PyObject_GenericGetAttr(), but instead of looking in __dict__ it
2048 asks im_self for the attribute. Then the error handling is a bit
2049 different because we want to preserve the exception raised by the
2050 delegate, unless we have an alternative from our class. */
2052 static PyObject *
2053 instancemethod_getattro(PyObject *obj, PyObject *name)
2055 PyMethodObject *im = (PyMethodObject *)obj;
2056 PyTypeObject *tp = obj->ob_type;
2057 PyObject *descr, *res;
2058 descrgetfunc f;
2060 if (tp->tp_dict == NULL) {
2061 if (PyType_Ready(tp) < 0)
2062 return NULL;
2065 descr = _PyType_Lookup(tp, name);
2066 f = NULL;
2067 if (descr != NULL) {
2068 f = descr->ob_type->tp_descr_get;
2069 if (f != NULL && PyDescr_IsData(descr))
2070 return f(descr, obj, (PyObject *)obj->ob_type);
2073 res = PyObject_GetAttr(im->im_func, name);
2074 if (res != NULL || !PyErr_ExceptionMatches(PyExc_AttributeError))
2075 return res;
2077 if (f != NULL) {
2078 PyErr_Clear();
2079 return f(descr, obj, (PyObject *)obj->ob_type);
2082 if (descr != NULL) {
2083 PyErr_Clear();
2084 Py_INCREF(descr);
2085 return descr;
2088 assert(PyErr_Occurred());
2089 return NULL;
2092 static void
2093 instancemethod_dealloc(register PyMethodObject *im)
2095 _PyObject_GC_UNTRACK(im);
2096 PyObject_ClearWeakRefs((PyObject *)im);
2097 Py_DECREF(im->im_func);
2098 Py_XDECREF(im->im_self);
2099 Py_XDECREF(im->im_class);
2100 im->im_self = (PyObject *)free_list;
2101 free_list = im;
2104 static int
2105 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2107 if (a->im_self != b->im_self)
2108 return (a->im_self < b->im_self) ? -1 : 1;
2109 return PyObject_Compare(a->im_func, b->im_func);
2112 static PyObject *
2113 instancemethod_repr(PyMethodObject *a)
2115 PyObject *self = a->im_self;
2116 PyObject *func = a->im_func;
2117 PyObject *klass = a->im_class;
2118 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2119 char *sfuncname = "?", *sklassname = "?";
2121 funcname = PyObject_GetAttrString(func, "__name__");
2122 if (funcname == NULL)
2123 PyErr_Clear();
2124 else if (!PyString_Check(funcname)) {
2125 Py_DECREF(funcname);
2126 funcname = NULL;
2128 else
2129 sfuncname = PyString_AS_STRING(funcname);
2130 if (klass == NULL)
2131 klassname = NULL;
2132 else {
2133 klassname = PyObject_GetAttrString(klass, "__name__");
2134 if (klassname == NULL)
2135 PyErr_Clear();
2136 else if (!PyString_Check(klassname)) {
2137 Py_DECREF(klassname);
2138 klassname = NULL;
2140 else
2141 sklassname = PyString_AS_STRING(klassname);
2143 if (self == NULL)
2144 result = PyString_FromFormat("<unbound method %s.%s>",
2145 sklassname, sfuncname);
2146 else {
2147 /* XXX Shouldn't use repr() here! */
2148 PyObject *selfrepr = PyObject_Repr(self);
2149 if (selfrepr == NULL)
2150 goto fail;
2151 if (!PyString_Check(selfrepr)) {
2152 Py_DECREF(selfrepr);
2153 goto fail;
2155 result = PyString_FromFormat("<bound method %s.%s of %s>",
2156 sklassname, sfuncname,
2157 PyString_AS_STRING(selfrepr));
2158 Py_DECREF(selfrepr);
2160 fail:
2161 Py_XDECREF(funcname);
2162 Py_XDECREF(klassname);
2163 return result;
2166 static long
2167 instancemethod_hash(PyMethodObject *a)
2169 long x, y;
2170 if (a->im_self == NULL)
2171 x = PyObject_Hash(Py_None);
2172 else
2173 x = PyObject_Hash(a->im_self);
2174 if (x == -1)
2175 return -1;
2176 y = PyObject_Hash(a->im_func);
2177 if (y == -1)
2178 return -1;
2179 return x ^ y;
2182 static int
2183 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2185 int err;
2186 if (im->im_func) {
2187 err = visit(im->im_func, arg);
2188 if (err)
2189 return err;
2191 if (im->im_self) {
2192 err = visit(im->im_self, arg);
2193 if (err)
2194 return err;
2196 if (im->im_class) {
2197 err = visit(im->im_class, arg);
2198 if (err)
2199 return err;
2201 return 0;
2204 static char *
2205 getclassname(PyObject *class)
2207 PyObject *name;
2209 if (class == NULL)
2210 name = NULL;
2211 else
2212 name = PyObject_GetAttrString(class, "__name__");
2213 if (name == NULL) {
2214 PyErr_Clear();
2215 return "?";
2217 if (!PyString_Check(name)) {
2218 Py_DECREF(name);
2219 return "?";
2221 PyString_InternInPlace(&name);
2222 Py_DECREF(name);
2223 return PyString_AS_STRING(name);
2226 static char *
2227 getinstclassname(PyObject *inst)
2229 PyObject *class;
2230 char *name;
2232 if (inst == NULL)
2233 return "nothing";
2235 class = PyObject_GetAttrString(inst, "__class__");
2236 if (class == NULL) {
2237 PyErr_Clear();
2238 class = (PyObject *)(inst->ob_type);
2239 Py_INCREF(class);
2241 name = getclassname(class);
2242 Py_XDECREF(class);
2243 return name;
2246 static PyObject *
2247 instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2249 PyObject *self = PyMethod_GET_SELF(func);
2250 PyObject *class = PyMethod_GET_CLASS(func);
2251 PyObject *result;
2253 func = PyMethod_GET_FUNCTION(func);
2254 if (self == NULL) {
2255 /* Unbound methods must be called with an instance of
2256 the class (or a derived class) as first argument */
2257 int ok;
2258 if (PyTuple_Size(arg) >= 1)
2259 self = PyTuple_GET_ITEM(arg, 0);
2260 if (self == NULL)
2261 ok = 0;
2262 else {
2263 ok = PyObject_IsInstance(self, class);
2264 if (ok < 0)
2265 return NULL;
2267 if (!ok) {
2268 PyErr_Format(PyExc_TypeError,
2269 "unbound method %s%s must be called with "
2270 "%s instance as first argument "
2271 "(got %s%s instead)",
2272 PyEval_GetFuncName(func),
2273 PyEval_GetFuncDesc(func),
2274 getclassname(class),
2275 getinstclassname(self),
2276 self == NULL ? "" : " instance");
2277 return NULL;
2279 Py_INCREF(arg);
2281 else {
2282 int argcount = PyTuple_Size(arg);
2283 PyObject *newarg = PyTuple_New(argcount + 1);
2284 int i;
2285 if (newarg == NULL)
2286 return NULL;
2287 Py_INCREF(self);
2288 PyTuple_SET_ITEM(newarg, 0, self);
2289 for (i = 0; i < argcount; i++) {
2290 PyObject *v = PyTuple_GET_ITEM(arg, i);
2291 Py_XINCREF(v);
2292 PyTuple_SET_ITEM(newarg, i+1, v);
2294 arg = newarg;
2296 result = PyObject_Call((PyObject *)func, arg, kw);
2297 Py_DECREF(arg);
2298 return result;
2301 static PyObject *
2302 instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *class)
2304 /* Don't rebind an already bound method, or an unbound method
2305 of a class that's not a base class of class */
2306 if (PyMethod_GET_SELF(meth) != NULL ||
2307 (PyMethod_GET_CLASS(meth) != NULL &&
2308 !PyObject_IsSubclass(class, PyMethod_GET_CLASS(meth)))) {
2309 Py_INCREF(meth);
2310 return meth;
2312 if (obj == Py_None)
2313 obj = NULL;
2314 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, class);
2317 PyTypeObject PyMethod_Type = {
2318 PyObject_HEAD_INIT(&PyType_Type)
2320 "instance method",
2321 sizeof(PyMethodObject),
2323 (destructor)instancemethod_dealloc, /* tp_dealloc */
2324 0, /* tp_print */
2325 0, /* tp_getattr */
2326 0, /* tp_setattr */
2327 (cmpfunc)instancemethod_compare, /* tp_compare */
2328 (reprfunc)instancemethod_repr, /* tp_repr */
2329 0, /* tp_as_number */
2330 0, /* tp_as_sequence */
2331 0, /* tp_as_mapping */
2332 (hashfunc)instancemethod_hash, /* tp_hash */
2333 instancemethod_call, /* tp_call */
2334 0, /* tp_str */
2335 (getattrofunc)instancemethod_getattro, /* tp_getattro */
2336 PyObject_GenericSetAttr, /* tp_setattro */
2337 0, /* tp_as_buffer */
2338 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2339 0, /* tp_doc */
2340 (traverseproc)instancemethod_traverse, /* tp_traverse */
2341 0, /* tp_clear */
2342 0, /* tp_richcompare */
2343 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2344 0, /* tp_iter */
2345 0, /* tp_iternext */
2346 0, /* tp_methods */
2347 instancemethod_memberlist, /* tp_members */
2348 instancemethod_getsetlist, /* tp_getset */
2349 0, /* tp_base */
2350 0, /* tp_dict */
2351 instancemethod_descr_get, /* tp_descr_get */
2352 0, /* tp_descr_set */
2353 0, /* tp_dictoffset */
2356 /* Clear out the free list */
2358 void
2359 PyMethod_Fini(void)
2361 while (free_list) {
2362 PyMethodObject *im = free_list;
2363 free_list = (PyMethodObject *)(im->im_self);
2364 PyObject_GC_Del(im);