Updated with fix for #3126.
[python.git] / Objects / classobject.c
blobcaf6b3e7b0de0a5e82a0f255a5a27d4dfca2e658
2 /* Class object implementation */
4 #include "Python.h"
5 #include "structmember.h"
7 /* Free list for method objects to safe malloc/free overhead
8 * The im_self element is used to chain the elements.
9 */
10 static PyMethodObject *free_list;
11 static int numfree = 0;
12 #ifndef PyMethod_MAXFREELIST
13 #define PyMethod_MAXFREELIST 256
14 #endif
16 #define TP_DESCR_GET(t) \
17 (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
19 /* Forward */
20 static PyObject *class_lookup(PyClassObject *, PyObject *,
21 PyClassObject **);
22 static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
23 static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
25 static PyObject *getattrstr, *setattrstr, *delattrstr;
28 PyObject *
29 PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
30 /* bases is NULL or tuple of classobjects! */
32 PyClassObject *op, *dummy;
33 static PyObject *docstr, *modstr, *namestr;
34 if (docstr == NULL) {
35 docstr= PyString_InternFromString("__doc__");
36 if (docstr == NULL)
37 return NULL;
39 if (modstr == NULL) {
40 modstr= PyString_InternFromString("__module__");
41 if (modstr == NULL)
42 return NULL;
44 if (namestr == NULL) {
45 namestr= PyString_InternFromString("__name__");
46 if (namestr == NULL)
47 return NULL;
49 if (name == NULL || !PyString_Check(name)) {
50 PyErr_SetString(PyExc_TypeError,
51 "PyClass_New: name must be a string");
52 return NULL;
54 if (dict == NULL || !PyDict_Check(dict)) {
55 PyErr_SetString(PyExc_TypeError,
56 "PyClass_New: dict must be a dictionary");
57 return NULL;
59 if (PyDict_GetItem(dict, docstr) == NULL) {
60 if (PyDict_SetItem(dict, docstr, Py_None) < 0)
61 return NULL;
63 if (PyDict_GetItem(dict, modstr) == NULL) {
64 PyObject *globals = PyEval_GetGlobals();
65 if (globals != NULL) {
66 PyObject *modname = PyDict_GetItem(globals, namestr);
67 if (modname != NULL) {
68 if (PyDict_SetItem(dict, modstr, modname) < 0)
69 return NULL;
73 if (bases == NULL) {
74 bases = PyTuple_New(0);
75 if (bases == NULL)
76 return NULL;
78 else {
79 Py_ssize_t i, n;
80 PyObject *base;
81 if (!PyTuple_Check(bases)) {
82 PyErr_SetString(PyExc_TypeError,
83 "PyClass_New: bases must be a tuple");
84 return NULL;
86 n = PyTuple_Size(bases);
87 for (i = 0; i < n; i++) {
88 base = PyTuple_GET_ITEM(bases, i);
89 if (!PyClass_Check(base)) {
90 if (PyCallable_Check(
91 (PyObject *) base->ob_type))
92 return PyObject_CallFunctionObjArgs(
93 (PyObject *) base->ob_type,
94 name, bases, dict, NULL);
95 PyErr_SetString(PyExc_TypeError,
96 "PyClass_New: base must be a class");
97 return NULL;
100 Py_INCREF(bases);
103 if (getattrstr == NULL) {
104 getattrstr = PyString_InternFromString("__getattr__");
105 if (getattrstr == NULL)
106 goto alloc_error;
107 setattrstr = PyString_InternFromString("__setattr__");
108 if (setattrstr == NULL)
109 goto alloc_error;
110 delattrstr = PyString_InternFromString("__delattr__");
111 if (delattrstr == NULL)
112 goto alloc_error;
115 op = PyObject_GC_New(PyClassObject, &PyClass_Type);
116 if (op == NULL) {
117 alloc_error:
118 Py_DECREF(bases);
119 return NULL;
121 op->cl_bases = bases;
122 Py_INCREF(dict);
123 op->cl_dict = dict;
124 Py_XINCREF(name);
125 op->cl_name = name;
127 op->cl_getattr = class_lookup(op, getattrstr, &dummy);
128 op->cl_setattr = class_lookup(op, setattrstr, &dummy);
129 op->cl_delattr = class_lookup(op, delattrstr, &dummy);
130 Py_XINCREF(op->cl_getattr);
131 Py_XINCREF(op->cl_setattr);
132 Py_XINCREF(op->cl_delattr);
133 _PyObject_GC_TRACK(op);
134 return (PyObject *) op;
137 PyObject *
138 PyMethod_Function(PyObject *im)
140 if (!PyMethod_Check(im)) {
141 PyErr_BadInternalCall();
142 return NULL;
144 return ((PyMethodObject *)im)->im_func;
147 PyObject *
148 PyMethod_Self(PyObject *im)
150 if (!PyMethod_Check(im)) {
151 PyErr_BadInternalCall();
152 return NULL;
154 return ((PyMethodObject *)im)->im_self;
157 PyObject *
158 PyMethod_Class(PyObject *im)
160 if (!PyMethod_Check(im)) {
161 PyErr_BadInternalCall();
162 return NULL;
164 return ((PyMethodObject *)im)->im_class;
167 PyDoc_STRVAR(class_doc,
168 "classobj(name, bases, dict)\n\
170 Create a class object. The name must be a string; the second argument\n\
171 a tuple of classes, and the third a dictionary.");
173 static PyObject *
174 class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
176 PyObject *name, *bases, *dict;
177 static char *kwlist[] = {"name", "bases", "dict", 0};
179 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
180 &name, &bases, &dict))
181 return NULL;
182 return PyClass_New(bases, dict, name);
185 /* Class methods */
187 static void
188 class_dealloc(PyClassObject *op)
190 _PyObject_GC_UNTRACK(op);
191 Py_DECREF(op->cl_bases);
192 Py_DECREF(op->cl_dict);
193 Py_XDECREF(op->cl_name);
194 Py_XDECREF(op->cl_getattr);
195 Py_XDECREF(op->cl_setattr);
196 Py_XDECREF(op->cl_delattr);
197 PyObject_GC_Del(op);
200 static PyObject *
201 class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
203 Py_ssize_t i, n;
204 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
205 if (value != NULL) {
206 *pclass = cp;
207 return value;
209 n = PyTuple_Size(cp->cl_bases);
210 for (i = 0; i < n; i++) {
211 /* XXX What if one of the bases is not a class? */
212 PyObject *v = class_lookup(
213 (PyClassObject *)
214 PyTuple_GetItem(cp->cl_bases, i), name, pclass);
215 if (v != NULL)
216 return v;
218 return NULL;
221 static PyObject *
222 class_getattr(register PyClassObject *op, PyObject *name)
224 register PyObject *v;
225 register char *sname = PyString_AsString(name);
226 PyClassObject *klass;
227 descrgetfunc f;
229 if (sname[0] == '_' && sname[1] == '_') {
230 if (strcmp(sname, "__dict__") == 0) {
231 if (PyEval_GetRestricted()) {
232 PyErr_SetString(PyExc_RuntimeError,
233 "class.__dict__ not accessible in restricted mode");
234 return NULL;
236 Py_INCREF(op->cl_dict);
237 return op->cl_dict;
239 if (strcmp(sname, "__bases__") == 0) {
240 Py_INCREF(op->cl_bases);
241 return op->cl_bases;
243 if (strcmp(sname, "__name__") == 0) {
244 if (op->cl_name == NULL)
245 v = Py_None;
246 else
247 v = op->cl_name;
248 Py_INCREF(v);
249 return v;
252 v = class_lookup(op, name, &klass);
253 if (v == NULL) {
254 PyErr_Format(PyExc_AttributeError,
255 "class %.50s has no attribute '%.400s'",
256 PyString_AS_STRING(op->cl_name), sname);
257 return NULL;
259 f = TP_DESCR_GET(v->ob_type);
260 if (f == NULL)
261 Py_INCREF(v);
262 else
263 v = f(v, (PyObject *)NULL, (PyObject *)op);
264 return v;
267 static void
268 set_slot(PyObject **slot, PyObject *v)
270 PyObject *temp = *slot;
271 Py_XINCREF(v);
272 *slot = v;
273 Py_XDECREF(temp);
276 static void
277 set_attr_slots(PyClassObject *c)
279 PyClassObject *dummy;
281 set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
282 set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
283 set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
286 static char *
287 set_dict(PyClassObject *c, PyObject *v)
289 if (v == NULL || !PyDict_Check(v))
290 return "__dict__ must be a dictionary object";
291 set_slot(&c->cl_dict, v);
292 set_attr_slots(c);
293 return "";
296 static char *
297 set_bases(PyClassObject *c, PyObject *v)
299 Py_ssize_t i, n;
301 if (v == NULL || !PyTuple_Check(v))
302 return "__bases__ must be a tuple object";
303 n = PyTuple_Size(v);
304 for (i = 0; i < n; i++) {
305 PyObject *x = PyTuple_GET_ITEM(v, i);
306 if (!PyClass_Check(x))
307 return "__bases__ items must be classes";
308 if (PyClass_IsSubclass(x, (PyObject *)c))
309 return "a __bases__ item causes an inheritance cycle";
311 set_slot(&c->cl_bases, v);
312 set_attr_slots(c);
313 return "";
316 static char *
317 set_name(PyClassObject *c, PyObject *v)
319 if (v == NULL || !PyString_Check(v))
320 return "__name__ must be a string object";
321 if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
322 return "__name__ must not contain null bytes";
323 set_slot(&c->cl_name, v);
324 return "";
327 static int
328 class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
330 char *sname;
331 if (PyEval_GetRestricted()) {
332 PyErr_SetString(PyExc_RuntimeError,
333 "classes are read-only in restricted mode");
334 return -1;
336 sname = PyString_AsString(name);
337 if (sname[0] == '_' && sname[1] == '_') {
338 Py_ssize_t n = PyString_Size(name);
339 if (sname[n-1] == '_' && sname[n-2] == '_') {
340 char *err = NULL;
341 if (strcmp(sname, "__dict__") == 0)
342 err = set_dict(op, v);
343 else if (strcmp(sname, "__bases__") == 0)
344 err = set_bases(op, v);
345 else if (strcmp(sname, "__name__") == 0)
346 err = set_name(op, v);
347 else if (strcmp(sname, "__getattr__") == 0)
348 set_slot(&op->cl_getattr, v);
349 else if (strcmp(sname, "__setattr__") == 0)
350 set_slot(&op->cl_setattr, v);
351 else if (strcmp(sname, "__delattr__") == 0)
352 set_slot(&op->cl_delattr, v);
353 /* For the last three, we fall through to update the
354 dictionary as well. */
355 if (err != NULL) {
356 if (*err == '\0')
357 return 0;
358 PyErr_SetString(PyExc_TypeError, err);
359 return -1;
363 if (v == NULL) {
364 int rv = PyDict_DelItem(op->cl_dict, name);
365 if (rv < 0)
366 PyErr_Format(PyExc_AttributeError,
367 "class %.50s has no attribute '%.400s'",
368 PyString_AS_STRING(op->cl_name), sname);
369 return rv;
371 else
372 return PyDict_SetItem(op->cl_dict, name, v);
375 static PyObject *
376 class_repr(PyClassObject *op)
378 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
379 char *name;
380 if (op->cl_name == NULL || !PyString_Check(op->cl_name))
381 name = "?";
382 else
383 name = PyString_AsString(op->cl_name);
384 if (mod == NULL || !PyString_Check(mod))
385 return PyString_FromFormat("<class ?.%s at %p>", name, op);
386 else
387 return PyString_FromFormat("<class %s.%s at %p>",
388 PyString_AsString(mod),
389 name, op);
392 static PyObject *
393 class_str(PyClassObject *op)
395 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
396 PyObject *name = op->cl_name;
397 PyObject *res;
398 Py_ssize_t m, n;
400 if (name == NULL || !PyString_Check(name))
401 return class_repr(op);
402 if (mod == NULL || !PyString_Check(mod)) {
403 Py_INCREF(name);
404 return name;
406 m = PyString_GET_SIZE(mod);
407 n = PyString_GET_SIZE(name);
408 res = PyString_FromStringAndSize((char *)NULL, m+1+n);
409 if (res != NULL) {
410 char *s = PyString_AS_STRING(res);
411 memcpy(s, PyString_AS_STRING(mod), m);
412 s += m;
413 *s++ = '.';
414 memcpy(s, PyString_AS_STRING(name), n);
416 return res;
419 static int
420 class_traverse(PyClassObject *o, visitproc visit, void *arg)
422 Py_VISIT(o->cl_bases);
423 Py_VISIT(o->cl_dict);
424 Py_VISIT(o->cl_name);
425 Py_VISIT(o->cl_getattr);
426 Py_VISIT(o->cl_setattr);
427 Py_VISIT(o->cl_delattr);
428 return 0;
431 PyTypeObject PyClass_Type = {
432 PyObject_HEAD_INIT(&PyType_Type)
434 "classobj",
435 sizeof(PyClassObject),
437 (destructor)class_dealloc, /* tp_dealloc */
438 0, /* tp_print */
439 0, /* tp_getattr */
440 0, /* tp_setattr */
441 0, /* tp_compare */
442 (reprfunc)class_repr, /* tp_repr */
443 0, /* tp_as_number */
444 0, /* tp_as_sequence */
445 0, /* tp_as_mapping */
446 0, /* tp_hash */
447 PyInstance_New, /* tp_call */
448 (reprfunc)class_str, /* tp_str */
449 (getattrofunc)class_getattr, /* tp_getattro */
450 (setattrofunc)class_setattr, /* tp_setattro */
451 0, /* tp_as_buffer */
452 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
453 class_doc, /* tp_doc */
454 (traverseproc)class_traverse, /* tp_traverse */
455 0, /* tp_clear */
456 0, /* tp_richcompare */
457 0, /* tp_weaklistoffset */
458 0, /* tp_iter */
459 0, /* tp_iternext */
460 0, /* tp_methods */
461 0, /* tp_members */
462 0, /* tp_getset */
463 0, /* tp_base */
464 0, /* tp_dict */
465 0, /* tp_descr_get */
466 0, /* tp_descr_set */
467 0, /* tp_dictoffset */
468 0, /* tp_init */
469 0, /* tp_alloc */
470 class_new, /* tp_new */
474 PyClass_IsSubclass(PyObject *klass, PyObject *base)
476 Py_ssize_t i, n;
477 PyClassObject *cp;
478 if (klass == base)
479 return 1;
480 if (PyTuple_Check(base)) {
481 n = PyTuple_GET_SIZE(base);
482 for (i = 0; i < n; i++) {
483 if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
484 return 1;
486 return 0;
488 if (klass == NULL || !PyClass_Check(klass))
489 return 0;
490 cp = (PyClassObject *)klass;
491 n = PyTuple_Size(cp->cl_bases);
492 for (i = 0; i < n; i++) {
493 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
494 return 1;
496 return 0;
500 /* Instance objects */
502 PyObject *
503 PyInstance_NewRaw(PyObject *klass, PyObject *dict)
505 PyInstanceObject *inst;
507 if (!PyClass_Check(klass)) {
508 PyErr_BadInternalCall();
509 return NULL;
511 if (dict == NULL) {
512 dict = PyDict_New();
513 if (dict == NULL)
514 return NULL;
516 else {
517 if (!PyDict_Check(dict)) {
518 PyErr_BadInternalCall();
519 return NULL;
521 Py_INCREF(dict);
523 inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
524 if (inst == NULL) {
525 Py_DECREF(dict);
526 return NULL;
528 inst->in_weakreflist = NULL;
529 Py_INCREF(klass);
530 inst->in_class = (PyClassObject *)klass;
531 inst->in_dict = dict;
532 _PyObject_GC_TRACK(inst);
533 return (PyObject *)inst;
536 PyObject *
537 PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
539 register PyInstanceObject *inst;
540 PyObject *init;
541 static PyObject *initstr;
543 if (initstr == NULL) {
544 initstr = PyString_InternFromString("__init__");
545 if (initstr == NULL)
546 return NULL;
548 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
549 if (inst == NULL)
550 return NULL;
551 init = instance_getattr2(inst, initstr);
552 if (init == NULL) {
553 if (PyErr_Occurred()) {
554 Py_DECREF(inst);
555 return NULL;
557 if ((arg != NULL && (!PyTuple_Check(arg) ||
558 PyTuple_Size(arg) != 0))
559 || (kw != NULL && (!PyDict_Check(kw) ||
560 PyDict_Size(kw) != 0))) {
561 PyErr_SetString(PyExc_TypeError,
562 "this constructor takes no arguments");
563 Py_DECREF(inst);
564 inst = NULL;
567 else {
568 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
569 Py_DECREF(init);
570 if (res == NULL) {
571 Py_DECREF(inst);
572 inst = NULL;
574 else {
575 if (res != Py_None) {
576 PyErr_SetString(PyExc_TypeError,
577 "__init__() should return None");
578 Py_DECREF(inst);
579 inst = NULL;
581 Py_DECREF(res);
584 return (PyObject *)inst;
587 /* Instance methods */
589 PyDoc_STRVAR(instance_doc,
590 "instance(class[, dict])\n\
592 Create an instance without calling its __init__() method.\n\
593 The class must be a classic class.\n\
594 If present, dict must be a dictionary or None.");
596 static PyObject *
597 instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
599 PyObject *klass;
600 PyObject *dict = Py_None;
602 if (!PyArg_ParseTuple(args, "O!|O:instance",
603 &PyClass_Type, &klass, &dict))
604 return NULL;
606 if (dict == Py_None)
607 dict = NULL;
608 else if (!PyDict_Check(dict)) {
609 PyErr_SetString(PyExc_TypeError,
610 "instance() second arg must be dictionary or None");
611 return NULL;
613 return PyInstance_NewRaw(klass, dict);
617 static void
618 instance_dealloc(register PyInstanceObject *inst)
620 PyObject *error_type, *error_value, *error_traceback;
621 PyObject *del;
622 static PyObject *delstr;
624 _PyObject_GC_UNTRACK(inst);
625 if (inst->in_weakreflist != NULL)
626 PyObject_ClearWeakRefs((PyObject *) inst);
628 /* Temporarily resurrect the object. */
629 assert(inst->ob_type == &PyInstance_Type);
630 assert(inst->ob_refcnt == 0);
631 inst->ob_refcnt = 1;
633 /* Save the current exception, if any. */
634 PyErr_Fetch(&error_type, &error_value, &error_traceback);
635 /* Execute __del__ method, if any. */
636 if (delstr == NULL) {
637 delstr = PyString_InternFromString("__del__");
638 if (delstr == NULL)
639 PyErr_WriteUnraisable((PyObject*)inst);
641 if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
642 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
643 if (res == NULL)
644 PyErr_WriteUnraisable(del);
645 else
646 Py_DECREF(res);
647 Py_DECREF(del);
649 /* Restore the saved exception. */
650 PyErr_Restore(error_type, error_value, error_traceback);
652 /* Undo the temporary resurrection; can't use DECREF here, it would
653 * cause a recursive call.
655 assert(inst->ob_refcnt > 0);
656 if (--inst->ob_refcnt == 0) {
658 /* New weakrefs could be created during the finalizer call.
659 If this occurs, clear them out without calling their
660 finalizers since they might rely on part of the object
661 being finalized that has already been destroyed. */
662 while (inst->in_weakreflist != NULL) {
663 _PyWeakref_ClearRef((PyWeakReference *)
664 (inst->in_weakreflist));
667 Py_DECREF(inst->in_class);
668 Py_XDECREF(inst->in_dict);
669 PyObject_GC_Del(inst);
671 else {
672 Py_ssize_t refcnt = inst->ob_refcnt;
673 /* __del__ resurrected it! Make it look like the original
674 * Py_DECREF never happened.
676 _Py_NewReference((PyObject *)inst);
677 inst->ob_refcnt = refcnt;
678 _PyObject_GC_TRACK(inst);
679 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
680 * we need to undo that. */
681 _Py_DEC_REFTOTAL;
682 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
683 * object chain, so no more to do there.
684 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
685 * _Py_NewReference bumped tp_allocs: both of those need to be
686 * undone.
688 #ifdef COUNT_ALLOCS
689 --inst->ob_type->tp_frees;
690 --inst->ob_type->tp_allocs;
691 #endif
695 static PyObject *
696 instance_getattr1(register PyInstanceObject *inst, PyObject *name)
698 register PyObject *v;
699 register char *sname = PyString_AsString(name);
700 if (sname[0] == '_' && sname[1] == '_') {
701 if (strcmp(sname, "__dict__") == 0) {
702 if (PyEval_GetRestricted()) {
703 PyErr_SetString(PyExc_RuntimeError,
704 "instance.__dict__ not accessible in restricted mode");
705 return NULL;
707 Py_INCREF(inst->in_dict);
708 return inst->in_dict;
710 if (strcmp(sname, "__class__") == 0) {
711 Py_INCREF(inst->in_class);
712 return (PyObject *)inst->in_class;
715 v = instance_getattr2(inst, name);
716 if (v == NULL && !PyErr_Occurred()) {
717 PyErr_Format(PyExc_AttributeError,
718 "%.50s instance has no attribute '%.400s'",
719 PyString_AS_STRING(inst->in_class->cl_name), sname);
721 return v;
724 static PyObject *
725 instance_getattr2(register PyInstanceObject *inst, PyObject *name)
727 register PyObject *v;
728 PyClassObject *klass;
729 descrgetfunc f;
731 v = PyDict_GetItem(inst->in_dict, name);
732 if (v != NULL) {
733 Py_INCREF(v);
734 return v;
736 v = class_lookup(inst->in_class, name, &klass);
737 if (v != NULL) {
738 Py_INCREF(v);
739 f = TP_DESCR_GET(v->ob_type);
740 if (f != NULL) {
741 PyObject *w = f(v, (PyObject *)inst,
742 (PyObject *)(inst->in_class));
743 Py_DECREF(v);
744 v = w;
747 return v;
750 static PyObject *
751 instance_getattr(register PyInstanceObject *inst, PyObject *name)
753 register PyObject *func, *res;
754 res = instance_getattr1(inst, name);
755 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
756 PyObject *args;
757 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
758 return NULL;
759 PyErr_Clear();
760 args = PyTuple_Pack(2, inst, name);
761 if (args == NULL)
762 return NULL;
763 res = PyEval_CallObject(func, args);
764 Py_DECREF(args);
766 return res;
769 /* See classobject.h comments: this only does dict lookups, and is always
770 * safe to call.
772 PyObject *
773 _PyInstance_Lookup(PyObject *pinst, PyObject *name)
775 PyObject *v;
776 PyClassObject *klass;
777 PyInstanceObject *inst; /* pinst cast to the right type */
779 assert(PyInstance_Check(pinst));
780 inst = (PyInstanceObject *)pinst;
782 assert(PyString_Check(name));
784 v = PyDict_GetItem(inst->in_dict, name);
785 if (v == NULL)
786 v = class_lookup(inst->in_class, name, &klass);
787 return v;
790 static int
791 instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
793 if (v == NULL) {
794 int rv = PyDict_DelItem(inst->in_dict, name);
795 if (rv < 0)
796 PyErr_Format(PyExc_AttributeError,
797 "%.50s instance has no attribute '%.400s'",
798 PyString_AS_STRING(inst->in_class->cl_name),
799 PyString_AS_STRING(name));
800 return rv;
802 else
803 return PyDict_SetItem(inst->in_dict, name, v);
806 static int
807 instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
809 PyObject *func, *args, *res, *tmp;
810 char *sname = PyString_AsString(name);
811 if (sname[0] == '_' && sname[1] == '_') {
812 Py_ssize_t n = PyString_Size(name);
813 if (sname[n-1] == '_' && sname[n-2] == '_') {
814 if (strcmp(sname, "__dict__") == 0) {
815 if (PyEval_GetRestricted()) {
816 PyErr_SetString(PyExc_RuntimeError,
817 "__dict__ not accessible in restricted mode");
818 return -1;
820 if (v == NULL || !PyDict_Check(v)) {
821 PyErr_SetString(PyExc_TypeError,
822 "__dict__ must be set to a dictionary");
823 return -1;
825 tmp = inst->in_dict;
826 Py_INCREF(v);
827 inst->in_dict = v;
828 Py_DECREF(tmp);
829 return 0;
831 if (strcmp(sname, "__class__") == 0) {
832 if (PyEval_GetRestricted()) {
833 PyErr_SetString(PyExc_RuntimeError,
834 "__class__ not accessible in restricted mode");
835 return -1;
837 if (v == NULL || !PyClass_Check(v)) {
838 PyErr_SetString(PyExc_TypeError,
839 "__class__ must be set to a class");
840 return -1;
842 tmp = (PyObject *)(inst->in_class);
843 Py_INCREF(v);
844 inst->in_class = (PyClassObject *)v;
845 Py_DECREF(tmp);
846 return 0;
850 if (v == NULL)
851 func = inst->in_class->cl_delattr;
852 else
853 func = inst->in_class->cl_setattr;
854 if (func == NULL)
855 return instance_setattr1(inst, name, v);
856 if (v == NULL)
857 args = PyTuple_Pack(2, inst, name);
858 else
859 args = PyTuple_Pack(3, inst, name, v);
860 if (args == NULL)
861 return -1;
862 res = PyEval_CallObject(func, args);
863 Py_DECREF(args);
864 if (res == NULL)
865 return -1;
866 Py_DECREF(res);
867 return 0;
870 static PyObject *
871 instance_repr(PyInstanceObject *inst)
873 PyObject *func;
874 PyObject *res;
875 static PyObject *reprstr;
877 if (reprstr == NULL) {
878 reprstr = PyString_InternFromString("__repr__");
879 if (reprstr == NULL)
880 return NULL;
882 func = instance_getattr(inst, reprstr);
883 if (func == NULL) {
884 PyObject *classname, *mod;
885 char *cname;
886 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
887 return NULL;
888 PyErr_Clear();
889 classname = inst->in_class->cl_name;
890 mod = PyDict_GetItemString(inst->in_class->cl_dict,
891 "__module__");
892 if (classname != NULL && PyString_Check(classname))
893 cname = PyString_AsString(classname);
894 else
895 cname = "?";
896 if (mod == NULL || !PyString_Check(mod))
897 return PyString_FromFormat("<?.%s instance at %p>",
898 cname, inst);
899 else
900 return PyString_FromFormat("<%s.%s instance at %p>",
901 PyString_AsString(mod),
902 cname, inst);
904 res = PyEval_CallObject(func, (PyObject *)NULL);
905 Py_DECREF(func);
906 return res;
909 static PyObject *
910 instance_str(PyInstanceObject *inst)
912 PyObject *func;
913 PyObject *res;
914 static PyObject *strstr;
916 if (strstr == NULL) {
917 strstr = PyString_InternFromString("__str__");
918 if (strstr == NULL)
919 return NULL;
921 func = instance_getattr(inst, strstr);
922 if (func == NULL) {
923 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
924 return NULL;
925 PyErr_Clear();
926 return instance_repr(inst);
928 res = PyEval_CallObject(func, (PyObject *)NULL);
929 Py_DECREF(func);
930 return res;
933 static long
934 instance_hash(PyInstanceObject *inst)
936 PyObject *func;
937 PyObject *res;
938 long outcome;
939 static PyObject *hashstr, *eqstr, *cmpstr;
941 if (hashstr == NULL) {
942 hashstr = PyString_InternFromString("__hash__");
943 if (hashstr == NULL)
944 return -1;
946 func = instance_getattr(inst, hashstr);
947 if (func == NULL) {
948 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
949 return -1;
950 PyErr_Clear();
951 /* If there is no __eq__ and no __cmp__ method, we hash on the
952 address. If an __eq__ or __cmp__ method exists, there must
953 be a __hash__. */
954 if (eqstr == NULL) {
955 eqstr = PyString_InternFromString("__eq__");
956 if (eqstr == NULL)
957 return -1;
959 func = instance_getattr(inst, eqstr);
960 if (func == NULL) {
961 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
962 return -1;
963 PyErr_Clear();
964 if (cmpstr == NULL) {
965 cmpstr = PyString_InternFromString("__cmp__");
966 if (cmpstr == NULL)
967 return -1;
969 func = instance_getattr(inst, cmpstr);
970 if (func == NULL) {
971 if (!PyErr_ExceptionMatches(
972 PyExc_AttributeError))
973 return -1;
974 PyErr_Clear();
975 return _Py_HashPointer(inst);
978 Py_XDECREF(func);
979 PyErr_SetString(PyExc_TypeError, "unhashable instance");
980 return -1;
982 res = PyEval_CallObject(func, (PyObject *)NULL);
983 Py_DECREF(func);
984 if (res == NULL)
985 return -1;
986 if (PyInt_Check(res) || PyLong_Check(res))
987 /* This already converts a -1 result to -2. */
988 outcome = res->ob_type->tp_hash(res);
989 else {
990 PyErr_SetString(PyExc_TypeError,
991 "__hash__() should return an int");
992 outcome = -1;
994 Py_DECREF(res);
995 return outcome;
998 static int
999 instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
1001 Py_VISIT(o->in_class);
1002 Py_VISIT(o->in_dict);
1003 return 0;
1006 static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
1007 static PyObject *iterstr, *nextstr;
1009 static Py_ssize_t
1010 instance_length(PyInstanceObject *inst)
1012 PyObject *func;
1013 PyObject *res;
1014 Py_ssize_t outcome;
1016 if (lenstr == NULL) {
1017 lenstr = PyString_InternFromString("__len__");
1018 if (lenstr == NULL)
1019 return -1;
1021 func = instance_getattr(inst, lenstr);
1022 if (func == NULL)
1023 return -1;
1024 res = PyEval_CallObject(func, (PyObject *)NULL);
1025 Py_DECREF(func);
1026 if (res == NULL)
1027 return -1;
1028 if (PyInt_Check(res)) {
1029 outcome = PyInt_AsSsize_t(res);
1030 if (outcome == -1 && PyErr_Occurred()) {
1031 Py_DECREF(res);
1032 return -1;
1034 #if SIZEOF_SIZE_T < SIZEOF_INT
1035 /* Overflow check -- range of PyInt is more than C int */
1036 if (outcome != (int)outcome) {
1037 PyErr_SetString(PyExc_OverflowError,
1038 "__len__() should return 0 <= outcome < 2**31");
1039 outcome = -1;
1041 else
1042 #endif
1043 if (outcome < 0) {
1044 PyErr_SetString(PyExc_ValueError,
1045 "__len__() should return >= 0");
1046 outcome = -1;
1049 else {
1050 PyErr_SetString(PyExc_TypeError,
1051 "__len__() should return an int");
1052 outcome = -1;
1054 Py_DECREF(res);
1055 return outcome;
1058 static PyObject *
1059 instance_subscript(PyInstanceObject *inst, PyObject *key)
1061 PyObject *func;
1062 PyObject *arg;
1063 PyObject *res;
1065 if (getitemstr == NULL) {
1066 getitemstr = PyString_InternFromString("__getitem__");
1067 if (getitemstr == NULL)
1068 return NULL;
1070 func = instance_getattr(inst, getitemstr);
1071 if (func == NULL)
1072 return NULL;
1073 arg = PyTuple_Pack(1, key);
1074 if (arg == NULL) {
1075 Py_DECREF(func);
1076 return NULL;
1078 res = PyEval_CallObject(func, arg);
1079 Py_DECREF(func);
1080 Py_DECREF(arg);
1081 return res;
1084 static int
1085 instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1087 PyObject *func;
1088 PyObject *arg;
1089 PyObject *res;
1091 if (value == NULL) {
1092 if (delitemstr == NULL) {
1093 delitemstr = PyString_InternFromString("__delitem__");
1094 if (delitemstr == NULL)
1095 return -1;
1097 func = instance_getattr(inst, delitemstr);
1099 else {
1100 if (setitemstr == NULL) {
1101 setitemstr = PyString_InternFromString("__setitem__");
1102 if (setitemstr == NULL)
1103 return -1;
1105 func = instance_getattr(inst, setitemstr);
1107 if (func == NULL)
1108 return -1;
1109 if (value == NULL)
1110 arg = PyTuple_Pack(1, key);
1111 else
1112 arg = PyTuple_Pack(2, key, value);
1113 if (arg == NULL) {
1114 Py_DECREF(func);
1115 return -1;
1117 res = PyEval_CallObject(func, arg);
1118 Py_DECREF(func);
1119 Py_DECREF(arg);
1120 if (res == NULL)
1121 return -1;
1122 Py_DECREF(res);
1123 return 0;
1126 static PyMappingMethods instance_as_mapping = {
1127 (lenfunc)instance_length, /* mp_length */
1128 (binaryfunc)instance_subscript, /* mp_subscript */
1129 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
1132 static PyObject *
1133 instance_item(PyInstanceObject *inst, Py_ssize_t i)
1135 PyObject *func, *res;
1137 if (getitemstr == NULL) {
1138 getitemstr = PyString_InternFromString("__getitem__");
1139 if (getitemstr == NULL)
1140 return NULL;
1142 func = instance_getattr(inst, getitemstr);
1143 if (func == NULL)
1144 return NULL;
1145 res = PyObject_CallFunction(func, "n", i);
1146 Py_DECREF(func);
1147 return res;
1150 static PyObject *
1151 instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
1153 PyObject *func, *arg, *res;
1154 static PyObject *getslicestr;
1156 if (getslicestr == NULL) {
1157 getslicestr = PyString_InternFromString("__getslice__");
1158 if (getslicestr == NULL)
1159 return NULL;
1161 func = instance_getattr(inst, getslicestr);
1163 if (func == NULL) {
1164 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1165 return NULL;
1166 PyErr_Clear();
1168 if (getitemstr == NULL) {
1169 getitemstr = PyString_InternFromString("__getitem__");
1170 if (getitemstr == NULL)
1171 return NULL;
1173 func = instance_getattr(inst, getitemstr);
1174 if (func == NULL)
1175 return NULL;
1176 arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
1177 } else
1178 arg = Py_BuildValue("(nn)", i, j);
1180 if (arg == NULL) {
1181 Py_DECREF(func);
1182 return NULL;
1184 res = PyEval_CallObject(func, arg);
1185 Py_DECREF(func);
1186 Py_DECREF(arg);
1187 return res;
1190 static int
1191 instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
1193 PyObject *func, *arg, *res;
1195 if (item == NULL) {
1196 if (delitemstr == NULL) {
1197 delitemstr = PyString_InternFromString("__delitem__");
1198 if (delitemstr == NULL)
1199 return -1;
1201 func = instance_getattr(inst, delitemstr);
1203 else {
1204 if (setitemstr == NULL) {
1205 setitemstr = PyString_InternFromString("__setitem__");
1206 if (setitemstr == NULL)
1207 return -1;
1209 func = instance_getattr(inst, setitemstr);
1211 if (func == NULL)
1212 return -1;
1213 if (item == NULL)
1214 arg = PyInt_FromSsize_t(i);
1215 else
1216 arg = Py_BuildValue("(nO)", i, item);
1217 if (arg == NULL) {
1218 Py_DECREF(func);
1219 return -1;
1221 res = PyEval_CallObject(func, arg);
1222 Py_DECREF(func);
1223 Py_DECREF(arg);
1224 if (res == NULL)
1225 return -1;
1226 Py_DECREF(res);
1227 return 0;
1230 static int
1231 instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
1233 PyObject *func, *arg, *res;
1234 static PyObject *setslicestr, *delslicestr;
1236 if (value == NULL) {
1237 if (delslicestr == NULL) {
1238 delslicestr =
1239 PyString_InternFromString("__delslice__");
1240 if (delslicestr == NULL)
1241 return -1;
1243 func = instance_getattr(inst, delslicestr);
1244 if (func == NULL) {
1245 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1246 return -1;
1247 PyErr_Clear();
1248 if (delitemstr == NULL) {
1249 delitemstr =
1250 PyString_InternFromString("__delitem__");
1251 if (delitemstr == NULL)
1252 return -1;
1254 func = instance_getattr(inst, delitemstr);
1255 if (func == NULL)
1256 return -1;
1258 arg = Py_BuildValue("(N)",
1259 _PySlice_FromIndices(i, j));
1260 } else
1261 arg = Py_BuildValue("(nn)", i, j);
1263 else {
1264 if (setslicestr == NULL) {
1265 setslicestr =
1266 PyString_InternFromString("__setslice__");
1267 if (setslicestr == NULL)
1268 return -1;
1270 func = instance_getattr(inst, setslicestr);
1271 if (func == NULL) {
1272 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1273 return -1;
1274 PyErr_Clear();
1275 if (setitemstr == NULL) {
1276 setitemstr =
1277 PyString_InternFromString("__setitem__");
1278 if (setitemstr == NULL)
1279 return -1;
1281 func = instance_getattr(inst, setitemstr);
1282 if (func == NULL)
1283 return -1;
1285 arg = Py_BuildValue("(NO)",
1286 _PySlice_FromIndices(i, j), value);
1287 } else
1288 arg = Py_BuildValue("(nnO)", i, j, value);
1290 if (arg == NULL) {
1291 Py_DECREF(func);
1292 return -1;
1294 res = PyEval_CallObject(func, arg);
1295 Py_DECREF(func);
1296 Py_DECREF(arg);
1297 if (res == NULL)
1298 return -1;
1299 Py_DECREF(res);
1300 return 0;
1303 static int
1304 instance_contains(PyInstanceObject *inst, PyObject *member)
1306 static PyObject *__contains__;
1307 PyObject *func;
1309 /* Try __contains__ first.
1310 * If that can't be done, try iterator-based searching.
1313 if(__contains__ == NULL) {
1314 __contains__ = PyString_InternFromString("__contains__");
1315 if(__contains__ == NULL)
1316 return -1;
1318 func = instance_getattr(inst, __contains__);
1319 if (func) {
1320 PyObject *res;
1321 int ret;
1322 PyObject *arg = PyTuple_Pack(1, member);
1323 if(arg == NULL) {
1324 Py_DECREF(func);
1325 return -1;
1327 res = PyEval_CallObject(func, arg);
1328 Py_DECREF(func);
1329 Py_DECREF(arg);
1330 if(res == NULL)
1331 return -1;
1332 ret = PyObject_IsTrue(res);
1333 Py_DECREF(res);
1334 return ret;
1337 /* Couldn't find __contains__. */
1338 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1339 Py_ssize_t rc;
1340 /* Assume the failure was simply due to that there is no
1341 * __contains__ attribute, and try iterating instead.
1343 PyErr_Clear();
1344 rc = _PySequence_IterSearch((PyObject *)inst, member,
1345 PY_ITERSEARCH_CONTAINS);
1346 if (rc >= 0)
1347 return rc > 0;
1349 return -1;
1352 static PySequenceMethods
1353 instance_as_sequence = {
1354 (lenfunc)instance_length, /* sq_length */
1355 0, /* sq_concat */
1356 0, /* sq_repeat */
1357 (ssizeargfunc)instance_item, /* sq_item */
1358 (ssizessizeargfunc)instance_slice, /* sq_slice */
1359 (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
1360 (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1361 (objobjproc)instance_contains, /* sq_contains */
1364 static PyObject *
1365 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1367 PyObject *func, *res;
1369 if ((func = instance_getattr(self, methodname)) == NULL)
1370 return NULL;
1371 res = PyEval_CallObject(func, (PyObject *)NULL);
1372 Py_DECREF(func);
1373 return res;
1376 static PyObject *
1377 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1379 PyObject *result;
1380 PyObject *args;
1381 PyObject *func = PyObject_GetAttrString(v, opname);
1382 if (func == NULL) {
1383 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1384 return NULL;
1385 PyErr_Clear();
1386 Py_INCREF(Py_NotImplemented);
1387 return Py_NotImplemented;
1389 args = PyTuple_Pack(1, w);
1390 if (args == NULL) {
1391 Py_DECREF(func);
1392 return NULL;
1394 result = PyEval_CallObject(func, args);
1395 Py_DECREF(args);
1396 Py_DECREF(func);
1397 return result;
1401 static PyObject *coerce_obj;
1403 /* Try one half of a binary operator involving a class instance. */
1404 static PyObject *
1405 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1406 int swapped)
1408 PyObject *args;
1409 PyObject *coercefunc;
1410 PyObject *coerced = NULL;
1411 PyObject *v1;
1412 PyObject *result;
1414 if (!PyInstance_Check(v)) {
1415 Py_INCREF(Py_NotImplemented);
1416 return Py_NotImplemented;
1419 if (coerce_obj == NULL) {
1420 coerce_obj = PyString_InternFromString("__coerce__");
1421 if (coerce_obj == NULL)
1422 return NULL;
1424 coercefunc = PyObject_GetAttr(v, coerce_obj);
1425 if (coercefunc == NULL) {
1426 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1427 return NULL;
1428 PyErr_Clear();
1429 return generic_binary_op(v, w, opname);
1432 args = PyTuple_Pack(1, w);
1433 if (args == NULL) {
1434 Py_DECREF(coercefunc);
1435 return NULL;
1437 coerced = PyEval_CallObject(coercefunc, args);
1438 Py_DECREF(args);
1439 Py_DECREF(coercefunc);
1440 if (coerced == NULL) {
1441 return NULL;
1443 if (coerced == Py_None || coerced == Py_NotImplemented) {
1444 Py_DECREF(coerced);
1445 return generic_binary_op(v, w, opname);
1447 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1448 Py_DECREF(coerced);
1449 PyErr_SetString(PyExc_TypeError,
1450 "coercion should return None or 2-tuple");
1451 return NULL;
1453 v1 = PyTuple_GetItem(coerced, 0);
1454 w = PyTuple_GetItem(coerced, 1);
1455 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1456 /* prevent recursion if __coerce__ returns self as the first
1457 * argument */
1458 result = generic_binary_op(v1, w, opname);
1459 } else {
1460 if (Py_EnterRecursiveCall(" after coercion"))
1461 return NULL;
1462 if (swapped)
1463 result = (thisfunc)(w, v1);
1464 else
1465 result = (thisfunc)(v1, w);
1466 Py_LeaveRecursiveCall();
1468 Py_DECREF(coerced);
1469 return result;
1472 /* Implement a binary operator involving at least one class instance. */
1473 static PyObject *
1474 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1475 binaryfunc thisfunc)
1477 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1478 if (result == Py_NotImplemented) {
1479 Py_DECREF(result);
1480 result = half_binop(w, v, ropname, thisfunc, 1);
1482 return result;
1485 static PyObject *
1486 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1487 char *ropname, binaryfunc thisfunc)
1489 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1490 if (result == Py_NotImplemented) {
1491 Py_DECREF(result);
1492 result = do_binop(v, w, opname, ropname, thisfunc);
1494 return result;
1497 static int
1498 instance_coerce(PyObject **pv, PyObject **pw)
1500 PyObject *v = *pv;
1501 PyObject *w = *pw;
1502 PyObject *coercefunc;
1503 PyObject *args;
1504 PyObject *coerced;
1506 if (coerce_obj == NULL) {
1507 coerce_obj = PyString_InternFromString("__coerce__");
1508 if (coerce_obj == NULL)
1509 return -1;
1511 coercefunc = PyObject_GetAttr(v, coerce_obj);
1512 if (coercefunc == NULL) {
1513 /* No __coerce__ method */
1514 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1515 return -1;
1516 PyErr_Clear();
1517 return 1;
1519 /* Has __coerce__ method: call it */
1520 args = PyTuple_Pack(1, w);
1521 if (args == NULL) {
1522 return -1;
1524 coerced = PyEval_CallObject(coercefunc, args);
1525 Py_DECREF(args);
1526 Py_DECREF(coercefunc);
1527 if (coerced == NULL) {
1528 /* __coerce__ call raised an exception */
1529 return -1;
1531 if (coerced == Py_None || coerced == Py_NotImplemented) {
1532 /* __coerce__ says "I can't do it" */
1533 Py_DECREF(coerced);
1534 return 1;
1536 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1537 /* __coerce__ return value is malformed */
1538 Py_DECREF(coerced);
1539 PyErr_SetString(PyExc_TypeError,
1540 "coercion should return None or 2-tuple");
1541 return -1;
1543 /* __coerce__ returned two new values */
1544 *pv = PyTuple_GetItem(coerced, 0);
1545 *pw = PyTuple_GetItem(coerced, 1);
1546 Py_INCREF(*pv);
1547 Py_INCREF(*pw);
1548 Py_DECREF(coerced);
1549 return 0;
1552 #define UNARY(funcname, methodname) \
1553 static PyObject *funcname(PyInstanceObject *self) { \
1554 static PyObject *o; \
1555 if (o == NULL) { o = PyString_InternFromString(methodname); \
1556 if (o == NULL) return NULL; } \
1557 return generic_unary_op(self, o); \
1560 /* unary function with a fallback */
1561 #define UNARY_FB(funcname, methodname, funcname_fb) \
1562 static PyObject *funcname(PyInstanceObject *self) { \
1563 static PyObject *o; \
1564 if (o == NULL) { o = PyString_InternFromString(methodname); \
1565 if (o == NULL) return NULL; } \
1566 if (PyObject_HasAttr((PyObject*)self, o)) \
1567 return generic_unary_op(self, o); \
1568 else \
1569 return funcname_fb(self); \
1572 #define BINARY(f, m, n) \
1573 static PyObject *f(PyObject *v, PyObject *w) { \
1574 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1577 #define BINARY_INPLACE(f, m, n) \
1578 static PyObject *f(PyObject *v, PyObject *w) { \
1579 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1580 "__r" m "__", n); \
1583 UNARY(instance_neg, "__neg__")
1584 UNARY(instance_pos, "__pos__")
1585 UNARY(instance_abs, "__abs__")
1587 BINARY(instance_or, "or", PyNumber_Or)
1588 BINARY(instance_and, "and", PyNumber_And)
1589 BINARY(instance_xor, "xor", PyNumber_Xor)
1590 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1591 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1592 BINARY(instance_add, "add", PyNumber_Add)
1593 BINARY(instance_sub, "sub", PyNumber_Subtract)
1594 BINARY(instance_mul, "mul", PyNumber_Multiply)
1595 BINARY(instance_div, "div", PyNumber_Divide)
1596 BINARY(instance_mod, "mod", PyNumber_Remainder)
1597 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1598 BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1599 BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1601 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1602 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1603 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1604 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1605 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1606 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1607 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1608 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1609 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1610 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1611 BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1612 BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1614 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1615 -2 for an exception;
1616 -1 if v < w;
1617 0 if v == w;
1618 1 if v > w;
1619 2 if this particular 3-way comparison is not implemented or undefined.
1621 static int
1622 half_cmp(PyObject *v, PyObject *w)
1624 static PyObject *cmp_obj;
1625 PyObject *args;
1626 PyObject *cmp_func;
1627 PyObject *result;
1628 long l;
1630 assert(PyInstance_Check(v));
1632 if (cmp_obj == NULL) {
1633 cmp_obj = PyString_InternFromString("__cmp__");
1634 if (cmp_obj == NULL)
1635 return -2;
1638 cmp_func = PyObject_GetAttr(v, cmp_obj);
1639 if (cmp_func == NULL) {
1640 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1641 return -2;
1642 PyErr_Clear();
1643 return 2;
1646 args = PyTuple_Pack(1, w);
1647 if (args == NULL) {
1648 Py_DECREF(cmp_func);
1649 return -2;
1652 result = PyEval_CallObject(cmp_func, args);
1653 Py_DECREF(args);
1654 Py_DECREF(cmp_func);
1656 if (result == NULL)
1657 return -2;
1659 if (result == Py_NotImplemented) {
1660 Py_DECREF(result);
1661 return 2;
1664 l = PyInt_AsLong(result);
1665 Py_DECREF(result);
1666 if (l == -1 && PyErr_Occurred()) {
1667 PyErr_SetString(PyExc_TypeError,
1668 "comparison did not return an int");
1669 return -2;
1672 return l < 0 ? -1 : l > 0 ? 1 : 0;
1675 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1676 We first try a coercion. Return:
1677 -2 for an exception;
1678 -1 if v < w;
1679 0 if v == w;
1680 1 if v > w;
1681 2 if this particular 3-way comparison is not implemented or undefined.
1682 THIS IS ONLY CALLED FROM object.c!
1684 static int
1685 instance_compare(PyObject *v, PyObject *w)
1687 int c;
1689 c = PyNumber_CoerceEx(&v, &w);
1690 if (c < 0)
1691 return -2;
1692 if (c == 0) {
1693 /* If neither is now an instance, use regular comparison */
1694 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1695 c = PyObject_Compare(v, w);
1696 Py_DECREF(v);
1697 Py_DECREF(w);
1698 if (PyErr_Occurred())
1699 return -2;
1700 return c < 0 ? -1 : c > 0 ? 1 : 0;
1703 else {
1704 /* The coercion didn't do anything.
1705 Treat this the same as returning v and w unchanged. */
1706 Py_INCREF(v);
1707 Py_INCREF(w);
1710 if (PyInstance_Check(v)) {
1711 c = half_cmp(v, w);
1712 if (c <= 1) {
1713 Py_DECREF(v);
1714 Py_DECREF(w);
1715 return c;
1718 if (PyInstance_Check(w)) {
1719 c = half_cmp(w, v);
1720 if (c <= 1) {
1721 Py_DECREF(v);
1722 Py_DECREF(w);
1723 if (c >= -1)
1724 c = -c;
1725 return c;
1728 Py_DECREF(v);
1729 Py_DECREF(w);
1730 return 2;
1733 static int
1734 instance_nonzero(PyInstanceObject *self)
1736 PyObject *func, *res;
1737 long outcome;
1738 static PyObject *nonzerostr;
1740 if (nonzerostr == NULL) {
1741 nonzerostr = PyString_InternFromString("__nonzero__");
1742 if (nonzerostr == NULL)
1743 return -1;
1745 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1746 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1747 return -1;
1748 PyErr_Clear();
1749 if (lenstr == NULL) {
1750 lenstr = PyString_InternFromString("__len__");
1751 if (lenstr == NULL)
1752 return -1;
1754 if ((func = instance_getattr(self, lenstr)) == NULL) {
1755 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1756 return -1;
1757 PyErr_Clear();
1758 /* Fall back to the default behavior:
1759 all instances are nonzero */
1760 return 1;
1763 res = PyEval_CallObject(func, (PyObject *)NULL);
1764 Py_DECREF(func);
1765 if (res == NULL)
1766 return -1;
1767 if (!PyInt_Check(res)) {
1768 Py_DECREF(res);
1769 PyErr_SetString(PyExc_TypeError,
1770 "__nonzero__ should return an int");
1771 return -1;
1773 outcome = PyInt_AsLong(res);
1774 Py_DECREF(res);
1775 if (outcome < 0) {
1776 PyErr_SetString(PyExc_ValueError,
1777 "__nonzero__ should return >= 0");
1778 return -1;
1780 return outcome > 0;
1783 static PyObject *
1784 instance_index(PyInstanceObject *self)
1786 PyObject *func, *res;
1787 static PyObject *indexstr = NULL;
1789 if (indexstr == NULL) {
1790 indexstr = PyString_InternFromString("__index__");
1791 if (indexstr == NULL)
1792 return NULL;
1794 if ((func = instance_getattr(self, indexstr)) == NULL) {
1795 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1796 return NULL;
1797 PyErr_Clear();
1798 PyErr_SetString(PyExc_TypeError,
1799 "object cannot be interpreted as an index");
1800 return NULL;
1802 res = PyEval_CallObject(func, (PyObject *)NULL);
1803 Py_DECREF(func);
1804 return res;
1808 UNARY(instance_invert, "__invert__")
1809 UNARY(_instance_trunc, "__trunc__")
1811 static PyObject *
1812 instance_int(PyInstanceObject *self)
1814 PyObject *truncated;
1815 static PyObject *int_name;
1816 if (int_name == NULL) {
1817 int_name = PyString_InternFromString("__int__");
1818 if (int_name == NULL)
1819 return NULL;
1821 if (PyObject_HasAttr((PyObject*)self, int_name))
1822 return generic_unary_op(self, int_name);
1824 truncated = _instance_trunc(self);
1825 /* __trunc__ is specified to return an Integral type, but
1826 int() needs to return an int. */
1827 return _PyNumber_ConvertIntegralToInt(
1828 truncated,
1829 "__trunc__ returned non-Integral (type %.200s)");
1832 UNARY_FB(instance_long, "__long__", instance_int)
1833 UNARY(instance_float, "__float__")
1834 UNARY(instance_oct, "__oct__")
1835 UNARY(instance_hex, "__hex__")
1837 static PyObject *
1838 bin_power(PyObject *v, PyObject *w)
1840 return PyNumber_Power(v, w, Py_None);
1843 /* This version is for ternary calls only (z != None) */
1844 static PyObject *
1845 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1847 if (z == Py_None) {
1848 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1850 else {
1851 PyObject *func;
1852 PyObject *args;
1853 PyObject *result;
1855 /* XXX Doesn't do coercions... */
1856 func = PyObject_GetAttrString(v, "__pow__");
1857 if (func == NULL)
1858 return NULL;
1859 args = PyTuple_Pack(2, w, z);
1860 if (args == NULL) {
1861 Py_DECREF(func);
1862 return NULL;
1864 result = PyEval_CallObject(func, args);
1865 Py_DECREF(func);
1866 Py_DECREF(args);
1867 return result;
1871 static PyObject *
1872 bin_inplace_power(PyObject *v, PyObject *w)
1874 return PyNumber_InPlacePower(v, w, Py_None);
1878 static PyObject *
1879 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1881 if (z == Py_None) {
1882 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1883 "__rpow__", bin_inplace_power);
1885 else {
1886 /* XXX Doesn't do coercions... */
1887 PyObject *func;
1888 PyObject *args;
1889 PyObject *result;
1891 func = PyObject_GetAttrString(v, "__ipow__");
1892 if (func == NULL) {
1893 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1894 return NULL;
1895 PyErr_Clear();
1896 return instance_pow(v, w, z);
1898 args = PyTuple_Pack(2, w, z);
1899 if (args == NULL) {
1900 Py_DECREF(func);
1901 return NULL;
1903 result = PyEval_CallObject(func, args);
1904 Py_DECREF(func);
1905 Py_DECREF(args);
1906 return result;
1911 /* Map rich comparison operators to their __xx__ namesakes */
1912 #define NAME_OPS 6
1913 static PyObject **name_op = NULL;
1915 static int
1916 init_name_op(void)
1918 int i;
1919 char *_name_op[] = {
1920 "__lt__",
1921 "__le__",
1922 "__eq__",
1923 "__ne__",
1924 "__gt__",
1925 "__ge__",
1928 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1929 if (name_op == NULL)
1930 return -1;
1931 for (i = 0; i < NAME_OPS; ++i) {
1932 name_op[i] = PyString_InternFromString(_name_op[i]);
1933 if (name_op[i] == NULL)
1934 return -1;
1936 return 0;
1939 static PyObject *
1940 half_richcompare(PyObject *v, PyObject *w, int op)
1942 PyObject *method;
1943 PyObject *args;
1944 PyObject *res;
1946 assert(PyInstance_Check(v));
1948 if (name_op == NULL) {
1949 if (init_name_op() < 0)
1950 return NULL;
1952 /* If the instance doesn't define an __getattr__ method, use
1953 instance_getattr2 directly because it will not set an
1954 exception on failure. */
1955 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1956 method = instance_getattr2((PyInstanceObject *)v,
1957 name_op[op]);
1958 else
1959 method = PyObject_GetAttr(v, name_op[op]);
1960 if (method == NULL) {
1961 if (PyErr_Occurred()) {
1962 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1963 return NULL;
1964 PyErr_Clear();
1966 res = Py_NotImplemented;
1967 Py_INCREF(res);
1968 return res;
1971 args = PyTuple_Pack(1, w);
1972 if (args == NULL) {
1973 Py_DECREF(method);
1974 return NULL;
1977 res = PyEval_CallObject(method, args);
1978 Py_DECREF(args);
1979 Py_DECREF(method);
1981 return res;
1984 static PyObject *
1985 instance_richcompare(PyObject *v, PyObject *w, int op)
1987 PyObject *res;
1989 if (PyInstance_Check(v)) {
1990 res = half_richcompare(v, w, op);
1991 if (res != Py_NotImplemented)
1992 return res;
1993 Py_DECREF(res);
1996 if (PyInstance_Check(w)) {
1997 res = half_richcompare(w, v, _Py_SwappedOp[op]);
1998 if (res != Py_NotImplemented)
1999 return res;
2000 Py_DECREF(res);
2003 Py_INCREF(Py_NotImplemented);
2004 return Py_NotImplemented;
2008 /* Get the iterator */
2009 static PyObject *
2010 instance_getiter(PyInstanceObject *self)
2012 PyObject *func;
2014 if (iterstr == NULL) {
2015 iterstr = PyString_InternFromString("__iter__");
2016 if (iterstr == NULL)
2017 return NULL;
2019 if (getitemstr == NULL) {
2020 getitemstr = PyString_InternFromString("__getitem__");
2021 if (getitemstr == NULL)
2022 return NULL;
2025 if ((func = instance_getattr(self, iterstr)) != NULL) {
2026 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2027 Py_DECREF(func);
2028 if (res != NULL && !PyIter_Check(res)) {
2029 PyErr_Format(PyExc_TypeError,
2030 "__iter__ returned non-iterator "
2031 "of type '%.100s'",
2032 res->ob_type->tp_name);
2033 Py_DECREF(res);
2034 res = NULL;
2036 return res;
2038 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2039 return NULL;
2040 PyErr_Clear();
2041 if ((func = instance_getattr(self, getitemstr)) == NULL) {
2042 PyErr_SetString(PyExc_TypeError,
2043 "iteration over non-sequence");
2044 return NULL;
2046 Py_DECREF(func);
2047 return PySeqIter_New((PyObject *)self);
2051 /* Call the iterator's next */
2052 static PyObject *
2053 instance_iternext(PyInstanceObject *self)
2055 PyObject *func;
2057 if (nextstr == NULL) {
2058 nextstr = PyString_InternFromString("next");
2059 if (nextstr == NULL)
2060 return NULL;
2063 if ((func = instance_getattr(self, nextstr)) != NULL) {
2064 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2065 Py_DECREF(func);
2066 if (res != NULL) {
2067 return res;
2069 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
2070 PyErr_Clear();
2071 return NULL;
2073 return NULL;
2075 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
2076 return NULL;
2079 static PyObject *
2080 instance_call(PyObject *func, PyObject *arg, PyObject *kw)
2082 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
2083 if (call == NULL) {
2084 PyInstanceObject *inst = (PyInstanceObject*) func;
2085 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2086 return NULL;
2087 PyErr_Clear();
2088 PyErr_Format(PyExc_AttributeError,
2089 "%.200s instance has no __call__ method",
2090 PyString_AsString(inst->in_class->cl_name));
2091 return NULL;
2093 /* We must check and increment the recursion depth here. Scenario:
2094 class A:
2095 pass
2096 A.__call__ = A() # that's right
2097 a = A() # ok
2098 a() # infinite recursion
2099 This bounces between instance_call() and PyObject_Call() without
2100 ever hitting eval_frame() (which has the main recursion check). */
2101 if (Py_EnterRecursiveCall(" in __call__")) {
2102 res = NULL;
2104 else {
2105 res = PyObject_Call(call, arg, kw);
2106 Py_LeaveRecursiveCall();
2108 Py_DECREF(call);
2109 return res;
2113 static PyNumberMethods instance_as_number = {
2114 instance_add, /* nb_add */
2115 instance_sub, /* nb_subtract */
2116 instance_mul, /* nb_multiply */
2117 instance_div, /* nb_divide */
2118 instance_mod, /* nb_remainder */
2119 instance_divmod, /* nb_divmod */
2120 instance_pow, /* nb_power */
2121 (unaryfunc)instance_neg, /* nb_negative */
2122 (unaryfunc)instance_pos, /* nb_positive */
2123 (unaryfunc)instance_abs, /* nb_absolute */
2124 (inquiry)instance_nonzero, /* nb_nonzero */
2125 (unaryfunc)instance_invert, /* nb_invert */
2126 instance_lshift, /* nb_lshift */
2127 instance_rshift, /* nb_rshift */
2128 instance_and, /* nb_and */
2129 instance_xor, /* nb_xor */
2130 instance_or, /* nb_or */
2131 instance_coerce, /* nb_coerce */
2132 (unaryfunc)instance_int, /* nb_int */
2133 (unaryfunc)instance_long, /* nb_long */
2134 (unaryfunc)instance_float, /* nb_float */
2135 (unaryfunc)instance_oct, /* nb_oct */
2136 (unaryfunc)instance_hex, /* nb_hex */
2137 instance_iadd, /* nb_inplace_add */
2138 instance_isub, /* nb_inplace_subtract */
2139 instance_imul, /* nb_inplace_multiply */
2140 instance_idiv, /* nb_inplace_divide */
2141 instance_imod, /* nb_inplace_remainder */
2142 instance_ipow, /* nb_inplace_power */
2143 instance_ilshift, /* nb_inplace_lshift */
2144 instance_irshift, /* nb_inplace_rshift */
2145 instance_iand, /* nb_inplace_and */
2146 instance_ixor, /* nb_inplace_xor */
2147 instance_ior, /* nb_inplace_or */
2148 instance_floordiv, /* nb_floor_divide */
2149 instance_truediv, /* nb_true_divide */
2150 instance_ifloordiv, /* nb_inplace_floor_divide */
2151 instance_itruediv, /* nb_inplace_true_divide */
2152 (unaryfunc)instance_index, /* nb_index */
2155 PyTypeObject PyInstance_Type = {
2156 PyObject_HEAD_INIT(&PyType_Type)
2158 "instance",
2159 sizeof(PyInstanceObject),
2161 (destructor)instance_dealloc, /* tp_dealloc */
2162 0, /* tp_print */
2163 0, /* tp_getattr */
2164 0, /* tp_setattr */
2165 instance_compare, /* tp_compare */
2166 (reprfunc)instance_repr, /* tp_repr */
2167 &instance_as_number, /* tp_as_number */
2168 &instance_as_sequence, /* tp_as_sequence */
2169 &instance_as_mapping, /* tp_as_mapping */
2170 (hashfunc)instance_hash, /* tp_hash */
2171 instance_call, /* tp_call */
2172 (reprfunc)instance_str, /* tp_str */
2173 (getattrofunc)instance_getattr, /* tp_getattro */
2174 (setattrofunc)instance_setattr, /* tp_setattro */
2175 0, /* tp_as_buffer */
2176 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2177 instance_doc, /* tp_doc */
2178 (traverseproc)instance_traverse, /* tp_traverse */
2179 0, /* tp_clear */
2180 instance_richcompare, /* tp_richcompare */
2181 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2182 (getiterfunc)instance_getiter, /* tp_iter */
2183 (iternextfunc)instance_iternext, /* tp_iternext */
2184 0, /* tp_methods */
2185 0, /* tp_members */
2186 0, /* tp_getset */
2187 0, /* tp_base */
2188 0, /* tp_dict */
2189 0, /* tp_descr_get */
2190 0, /* tp_descr_set */
2191 0, /* tp_dictoffset */
2192 0, /* tp_init */
2193 0, /* tp_alloc */
2194 instance_new, /* tp_new */
2198 /* Instance method objects are used for two purposes:
2199 (a) as bound instance methods (returned by instancename.methodname)
2200 (b) as unbound methods (returned by ClassName.methodname)
2201 In case (b), im_self is NULL
2204 PyObject *
2205 PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
2207 register PyMethodObject *im;
2208 if (!PyCallable_Check(func)) {
2209 PyErr_BadInternalCall();
2210 return NULL;
2212 im = free_list;
2213 if (im != NULL) {
2214 free_list = (PyMethodObject *)(im->im_self);
2215 PyObject_INIT(im, &PyMethod_Type);
2216 numfree--;
2218 else {
2219 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2220 if (im == NULL)
2221 return NULL;
2223 im->im_weakreflist = NULL;
2224 Py_INCREF(func);
2225 im->im_func = func;
2226 Py_XINCREF(self);
2227 im->im_self = self;
2228 Py_XINCREF(klass);
2229 im->im_class = klass;
2230 _PyObject_GC_TRACK(im);
2231 return (PyObject *)im;
2234 /* Descriptors for PyMethod attributes */
2236 /* im_class, im_func and im_self are stored in the PyMethod object */
2238 #define OFF(x) offsetof(PyMethodObject, x)
2240 static PyMemberDef instancemethod_memberlist[] = {
2241 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2242 "the class associated with a method"},
2243 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2244 "the function (or other callable) implementing a method"},
2245 {"__func__", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2246 "the function (or other callable) implementing a method"},
2247 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2248 "the instance to which a method is bound; None for unbound methods"},
2249 {"__self__", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2250 "the instance to which a method is bound; None for unbound methods"},
2251 {NULL} /* Sentinel */
2254 /* Christian Tismer argued convincingly that method attributes should
2255 (nearly) always override function attributes.
2256 The one exception is __doc__; there's a default __doc__ which
2257 should only be used for the class, not for instances */
2259 static PyObject *
2260 instancemethod_get_doc(PyMethodObject *im, void *context)
2262 static PyObject *docstr;
2263 if (docstr == NULL) {
2264 docstr= PyString_InternFromString("__doc__");
2265 if (docstr == NULL)
2266 return NULL;
2268 return PyObject_GetAttr(im->im_func, docstr);
2271 static PyGetSetDef instancemethod_getset[] = {
2272 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2276 static PyObject *
2277 instancemethod_getattro(PyObject *obj, PyObject *name)
2279 PyMethodObject *im = (PyMethodObject *)obj;
2280 PyTypeObject *tp = obj->ob_type;
2281 PyObject *descr = NULL;
2283 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2284 if (tp->tp_dict == NULL) {
2285 if (PyType_Ready(tp) < 0)
2286 return NULL;
2288 descr = _PyType_Lookup(tp, name);
2291 if (descr != NULL) {
2292 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
2293 if (f != NULL)
2294 return f(descr, obj, (PyObject *)obj->ob_type);
2295 else {
2296 Py_INCREF(descr);
2297 return descr;
2301 return PyObject_GetAttr(im->im_func, name);
2304 PyDoc_STRVAR(instancemethod_doc,
2305 "instancemethod(function, instance, class)\n\
2307 Create an instance method object.");
2309 static PyObject *
2310 instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2312 PyObject *func;
2313 PyObject *self;
2314 PyObject *classObj = NULL;
2316 if (!_PyArg_NoKeywords("instancemethod", kw))
2317 return NULL;
2318 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2319 &func, &self, &classObj))
2320 return NULL;
2321 if (!PyCallable_Check(func)) {
2322 PyErr_SetString(PyExc_TypeError,
2323 "first argument must be callable");
2324 return NULL;
2326 if (self == Py_None)
2327 self = NULL;
2328 if (self == NULL && classObj == NULL) {
2329 PyErr_SetString(PyExc_TypeError,
2330 "unbound methods must have non-NULL im_class");
2331 return NULL;
2334 return PyMethod_New(func, self, classObj);
2337 static void
2338 instancemethod_dealloc(register PyMethodObject *im)
2340 _PyObject_GC_UNTRACK(im);
2341 if (im->im_weakreflist != NULL)
2342 PyObject_ClearWeakRefs((PyObject *)im);
2343 Py_DECREF(im->im_func);
2344 Py_XDECREF(im->im_self);
2345 Py_XDECREF(im->im_class);
2346 if (numfree < PyMethod_MAXFREELIST) {
2347 im->im_self = (PyObject *)free_list;
2348 free_list = im;
2349 numfree++;
2351 else {
2352 PyObject_GC_Del(im);
2356 static int
2357 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2359 int cmp;
2360 cmp = PyObject_Compare(a->im_func, b->im_func);
2361 if (cmp)
2362 return cmp;
2364 if (a->im_self == b->im_self)
2365 return 0;
2366 if (a->im_self == NULL || b->im_self == NULL)
2367 return (a->im_self < b->im_self) ? -1 : 1;
2368 else
2369 return PyObject_Compare(a->im_self, b->im_self);
2372 static PyObject *
2373 instancemethod_repr(PyMethodObject *a)
2375 PyObject *self = a->im_self;
2376 PyObject *func = a->im_func;
2377 PyObject *klass = a->im_class;
2378 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2379 char *sfuncname = "?", *sklassname = "?";
2381 funcname = PyObject_GetAttrString(func, "__name__");
2382 if (funcname == NULL) {
2383 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2384 return NULL;
2385 PyErr_Clear();
2387 else if (!PyString_Check(funcname)) {
2388 Py_DECREF(funcname);
2389 funcname = NULL;
2391 else
2392 sfuncname = PyString_AS_STRING(funcname);
2393 if (klass == NULL)
2394 klassname = NULL;
2395 else {
2396 klassname = PyObject_GetAttrString(klass, "__name__");
2397 if (klassname == NULL) {
2398 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2399 return NULL;
2400 PyErr_Clear();
2402 else if (!PyString_Check(klassname)) {
2403 Py_DECREF(klassname);
2404 klassname = NULL;
2406 else
2407 sklassname = PyString_AS_STRING(klassname);
2409 if (self == NULL)
2410 result = PyString_FromFormat("<unbound method %s.%s>",
2411 sklassname, sfuncname);
2412 else {
2413 /* XXX Shouldn't use repr() here! */
2414 PyObject *selfrepr = PyObject_Repr(self);
2415 if (selfrepr == NULL)
2416 goto fail;
2417 if (!PyString_Check(selfrepr)) {
2418 Py_DECREF(selfrepr);
2419 goto fail;
2421 result = PyString_FromFormat("<bound method %s.%s of %s>",
2422 sklassname, sfuncname,
2423 PyString_AS_STRING(selfrepr));
2424 Py_DECREF(selfrepr);
2426 fail:
2427 Py_XDECREF(funcname);
2428 Py_XDECREF(klassname);
2429 return result;
2432 static long
2433 instancemethod_hash(PyMethodObject *a)
2435 long x, y;
2436 if (a->im_self == NULL)
2437 x = PyObject_Hash(Py_None);
2438 else
2439 x = PyObject_Hash(a->im_self);
2440 if (x == -1)
2441 return -1;
2442 y = PyObject_Hash(a->im_func);
2443 if (y == -1)
2444 return -1;
2445 x = x ^ y;
2446 if (x == -1)
2447 x = -2;
2448 return x;
2451 static int
2452 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2454 Py_VISIT(im->im_func);
2455 Py_VISIT(im->im_self);
2456 Py_VISIT(im->im_class);
2457 return 0;
2460 static void
2461 getclassname(PyObject *klass, char *buf, int bufsize)
2463 PyObject *name;
2465 assert(bufsize > 1);
2466 strcpy(buf, "?"); /* Default outcome */
2467 if (klass == NULL)
2468 return;
2469 name = PyObject_GetAttrString(klass, "__name__");
2470 if (name == NULL) {
2471 /* This function cannot return an exception */
2472 PyErr_Clear();
2473 return;
2475 if (PyString_Check(name)) {
2476 strncpy(buf, PyString_AS_STRING(name), bufsize);
2477 buf[bufsize-1] = '\0';
2479 Py_DECREF(name);
2482 static void
2483 getinstclassname(PyObject *inst, char *buf, int bufsize)
2485 PyObject *klass;
2487 if (inst == NULL) {
2488 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2489 strcpy(buf, "nothing");
2490 return;
2493 klass = PyObject_GetAttrString(inst, "__class__");
2494 if (klass == NULL) {
2495 /* This function cannot return an exception */
2496 PyErr_Clear();
2497 klass = (PyObject *)(inst->ob_type);
2498 Py_INCREF(klass);
2500 getclassname(klass, buf, bufsize);
2501 Py_XDECREF(klass);
2504 static PyObject *
2505 instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2507 PyObject *self = PyMethod_GET_SELF(func);
2508 PyObject *klass = PyMethod_GET_CLASS(func);
2509 PyObject *result;
2511 func = PyMethod_GET_FUNCTION(func);
2512 if (self == NULL) {
2513 /* Unbound methods must be called with an instance of
2514 the class (or a derived class) as first argument */
2515 int ok;
2516 if (PyTuple_Size(arg) >= 1)
2517 self = PyTuple_GET_ITEM(arg, 0);
2518 if (self == NULL)
2519 ok = 0;
2520 else {
2521 ok = PyObject_IsInstance(self, klass);
2522 if (ok < 0)
2523 return NULL;
2525 if (!ok) {
2526 char clsbuf[256];
2527 char instbuf[256];
2528 getclassname(klass, clsbuf, sizeof(clsbuf));
2529 getinstclassname(self, instbuf, sizeof(instbuf));
2530 PyErr_Format(PyExc_TypeError,
2531 "unbound method %s%s must be called with "
2532 "%s instance as first argument "
2533 "(got %s%s instead)",
2534 PyEval_GetFuncName(func),
2535 PyEval_GetFuncDesc(func),
2536 clsbuf,
2537 instbuf,
2538 self == NULL ? "" : " instance");
2539 return NULL;
2541 Py_INCREF(arg);
2543 else {
2544 Py_ssize_t argcount = PyTuple_Size(arg);
2545 PyObject *newarg = PyTuple_New(argcount + 1);
2546 int i;
2547 if (newarg == NULL)
2548 return NULL;
2549 Py_INCREF(self);
2550 PyTuple_SET_ITEM(newarg, 0, self);
2551 for (i = 0; i < argcount; i++) {
2552 PyObject *v = PyTuple_GET_ITEM(arg, i);
2553 Py_XINCREF(v);
2554 PyTuple_SET_ITEM(newarg, i+1, v);
2556 arg = newarg;
2558 result = PyObject_Call((PyObject *)func, arg, kw);
2559 Py_DECREF(arg);
2560 return result;
2563 static PyObject *
2564 instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
2566 /* Don't rebind an already bound method, or an unbound method
2567 of a class that's not a base class of cls. */
2569 if (PyMethod_GET_SELF(meth) != NULL) {
2570 /* Already bound */
2571 Py_INCREF(meth);
2572 return meth;
2574 /* No, it is an unbound method */
2575 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2576 /* Do subclass test. If it fails, return meth unchanged. */
2577 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2578 if (ok < 0)
2579 return NULL;
2580 if (!ok) {
2581 Py_INCREF(meth);
2582 return meth;
2585 /* Bind it to obj */
2586 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
2589 PyTypeObject PyMethod_Type = {
2590 PyObject_HEAD_INIT(&PyType_Type)
2592 "instancemethod",
2593 sizeof(PyMethodObject),
2595 (destructor)instancemethod_dealloc, /* tp_dealloc */
2596 0, /* tp_print */
2597 0, /* tp_getattr */
2598 0, /* tp_setattr */
2599 (cmpfunc)instancemethod_compare, /* tp_compare */
2600 (reprfunc)instancemethod_repr, /* tp_repr */
2601 0, /* tp_as_number */
2602 0, /* tp_as_sequence */
2603 0, /* tp_as_mapping */
2604 (hashfunc)instancemethod_hash, /* tp_hash */
2605 instancemethod_call, /* tp_call */
2606 0, /* tp_str */
2607 instancemethod_getattro, /* tp_getattro */
2608 PyObject_GenericSetAttr, /* tp_setattro */
2609 0, /* tp_as_buffer */
2610 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2611 instancemethod_doc, /* tp_doc */
2612 (traverseproc)instancemethod_traverse, /* tp_traverse */
2613 0, /* tp_clear */
2614 0, /* tp_richcompare */
2615 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2616 0, /* tp_iter */
2617 0, /* tp_iternext */
2618 0, /* tp_methods */
2619 instancemethod_memberlist, /* tp_members */
2620 instancemethod_getset, /* tp_getset */
2621 0, /* tp_base */
2622 0, /* tp_dict */
2623 instancemethod_descr_get, /* tp_descr_get */
2624 0, /* tp_descr_set */
2625 0, /* tp_dictoffset */
2626 0, /* tp_init */
2627 0, /* tp_alloc */
2628 instancemethod_new, /* tp_new */
2631 /* Clear out the free list */
2634 PyMethod_ClearFreeList(void)
2636 int freelist_size = numfree;
2638 while (free_list) {
2639 PyMethodObject *im = free_list;
2640 free_list = (PyMethodObject *)(im->im_self);
2641 PyObject_GC_Del(im);
2642 numfree--;
2644 assert(numfree == 0);
2645 return freelist_size;
2648 void
2649 PyMethod_Fini(void)
2651 (void)PyMethod_ClearFreeList();