Add better error reporting for MemoryErrors caused by str->float conversions.
[python.git] / Objects / classobject.c
blob3f51c0fc55cc4aa5d6596e92913764a53c290cd3
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));
1178 else {
1179 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
1180 "use __getitem__", 1) < 0) {
1181 Py_DECREF(func);
1182 return NULL;
1184 arg = Py_BuildValue("(nn)", i, j);
1187 if (arg == NULL) {
1188 Py_DECREF(func);
1189 return NULL;
1191 res = PyEval_CallObject(func, arg);
1192 Py_DECREF(func);
1193 Py_DECREF(arg);
1194 return res;
1197 static int
1198 instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
1200 PyObject *func, *arg, *res;
1202 if (item == NULL) {
1203 if (delitemstr == NULL) {
1204 delitemstr = PyString_InternFromString("__delitem__");
1205 if (delitemstr == NULL)
1206 return -1;
1208 func = instance_getattr(inst, delitemstr);
1210 else {
1211 if (setitemstr == NULL) {
1212 setitemstr = PyString_InternFromString("__setitem__");
1213 if (setitemstr == NULL)
1214 return -1;
1216 func = instance_getattr(inst, setitemstr);
1218 if (func == NULL)
1219 return -1;
1220 if (item == NULL)
1221 arg = PyInt_FromSsize_t(i);
1222 else
1223 arg = Py_BuildValue("(nO)", i, item);
1224 if (arg == NULL) {
1225 Py_DECREF(func);
1226 return -1;
1228 res = PyEval_CallObject(func, arg);
1229 Py_DECREF(func);
1230 Py_DECREF(arg);
1231 if (res == NULL)
1232 return -1;
1233 Py_DECREF(res);
1234 return 0;
1237 static int
1238 instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
1240 PyObject *func, *arg, *res;
1241 static PyObject *setslicestr, *delslicestr;
1243 if (value == NULL) {
1244 if (delslicestr == NULL) {
1245 delslicestr =
1246 PyString_InternFromString("__delslice__");
1247 if (delslicestr == NULL)
1248 return -1;
1250 func = instance_getattr(inst, delslicestr);
1251 if (func == NULL) {
1252 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1253 return -1;
1254 PyErr_Clear();
1255 if (delitemstr == NULL) {
1256 delitemstr =
1257 PyString_InternFromString("__delitem__");
1258 if (delitemstr == NULL)
1259 return -1;
1261 func = instance_getattr(inst, delitemstr);
1262 if (func == NULL)
1263 return -1;
1265 arg = Py_BuildValue("(N)",
1266 _PySlice_FromIndices(i, j));
1268 else {
1269 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
1270 "removed; use __delitem__", 1) < 0) {
1271 Py_DECREF(func);
1272 return -1;
1274 arg = Py_BuildValue("(nn)", i, j);
1277 else {
1278 if (setslicestr == NULL) {
1279 setslicestr =
1280 PyString_InternFromString("__setslice__");
1281 if (setslicestr == NULL)
1282 return -1;
1284 func = instance_getattr(inst, setslicestr);
1285 if (func == NULL) {
1286 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1287 return -1;
1288 PyErr_Clear();
1289 if (setitemstr == NULL) {
1290 setitemstr =
1291 PyString_InternFromString("__setitem__");
1292 if (setitemstr == NULL)
1293 return -1;
1295 func = instance_getattr(inst, setitemstr);
1296 if (func == NULL)
1297 return -1;
1299 arg = Py_BuildValue("(NO)",
1300 _PySlice_FromIndices(i, j), value);
1302 else {
1303 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
1304 "removed; use __setitem__", 1) < 0) {
1305 Py_DECREF(func);
1306 return -1;
1308 arg = Py_BuildValue("(nnO)", i, j, value);
1311 if (arg == NULL) {
1312 Py_DECREF(func);
1313 return -1;
1315 res = PyEval_CallObject(func, arg);
1316 Py_DECREF(func);
1317 Py_DECREF(arg);
1318 if (res == NULL)
1319 return -1;
1320 Py_DECREF(res);
1321 return 0;
1324 static int
1325 instance_contains(PyInstanceObject *inst, PyObject *member)
1327 static PyObject *__contains__;
1328 PyObject *func;
1330 /* Try __contains__ first.
1331 * If that can't be done, try iterator-based searching.
1334 if(__contains__ == NULL) {
1335 __contains__ = PyString_InternFromString("__contains__");
1336 if(__contains__ == NULL)
1337 return -1;
1339 func = instance_getattr(inst, __contains__);
1340 if (func) {
1341 PyObject *res;
1342 int ret;
1343 PyObject *arg = PyTuple_Pack(1, member);
1344 if(arg == NULL) {
1345 Py_DECREF(func);
1346 return -1;
1348 res = PyEval_CallObject(func, arg);
1349 Py_DECREF(func);
1350 Py_DECREF(arg);
1351 if(res == NULL)
1352 return -1;
1353 ret = PyObject_IsTrue(res);
1354 Py_DECREF(res);
1355 return ret;
1358 /* Couldn't find __contains__. */
1359 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1360 Py_ssize_t rc;
1361 /* Assume the failure was simply due to that there is no
1362 * __contains__ attribute, and try iterating instead.
1364 PyErr_Clear();
1365 rc = _PySequence_IterSearch((PyObject *)inst, member,
1366 PY_ITERSEARCH_CONTAINS);
1367 if (rc >= 0)
1368 return rc > 0;
1370 return -1;
1373 static PySequenceMethods
1374 instance_as_sequence = {
1375 (lenfunc)instance_length, /* sq_length */
1376 0, /* sq_concat */
1377 0, /* sq_repeat */
1378 (ssizeargfunc)instance_item, /* sq_item */
1379 (ssizessizeargfunc)instance_slice, /* sq_slice */
1380 (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
1381 (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1382 (objobjproc)instance_contains, /* sq_contains */
1385 static PyObject *
1386 generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1388 PyObject *func, *res;
1390 if ((func = instance_getattr(self, methodname)) == NULL)
1391 return NULL;
1392 res = PyEval_CallObject(func, (PyObject *)NULL);
1393 Py_DECREF(func);
1394 return res;
1397 static PyObject *
1398 generic_binary_op(PyObject *v, PyObject *w, char *opname)
1400 PyObject *result;
1401 PyObject *args;
1402 PyObject *func = PyObject_GetAttrString(v, opname);
1403 if (func == NULL) {
1404 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1405 return NULL;
1406 PyErr_Clear();
1407 Py_INCREF(Py_NotImplemented);
1408 return Py_NotImplemented;
1410 args = PyTuple_Pack(1, w);
1411 if (args == NULL) {
1412 Py_DECREF(func);
1413 return NULL;
1415 result = PyEval_CallObject(func, args);
1416 Py_DECREF(args);
1417 Py_DECREF(func);
1418 return result;
1422 static PyObject *coerce_obj;
1424 /* Try one half of a binary operator involving a class instance. */
1425 static PyObject *
1426 half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1427 int swapped)
1429 PyObject *args;
1430 PyObject *coercefunc;
1431 PyObject *coerced = NULL;
1432 PyObject *v1;
1433 PyObject *result;
1435 if (!PyInstance_Check(v)) {
1436 Py_INCREF(Py_NotImplemented);
1437 return Py_NotImplemented;
1440 if (coerce_obj == NULL) {
1441 coerce_obj = PyString_InternFromString("__coerce__");
1442 if (coerce_obj == NULL)
1443 return NULL;
1445 coercefunc = PyObject_GetAttr(v, coerce_obj);
1446 if (coercefunc == NULL) {
1447 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1448 return NULL;
1449 PyErr_Clear();
1450 return generic_binary_op(v, w, opname);
1453 args = PyTuple_Pack(1, w);
1454 if (args == NULL) {
1455 Py_DECREF(coercefunc);
1456 return NULL;
1458 coerced = PyEval_CallObject(coercefunc, args);
1459 Py_DECREF(args);
1460 Py_DECREF(coercefunc);
1461 if (coerced == NULL) {
1462 return NULL;
1464 if (coerced == Py_None || coerced == Py_NotImplemented) {
1465 Py_DECREF(coerced);
1466 return generic_binary_op(v, w, opname);
1468 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1469 Py_DECREF(coerced);
1470 PyErr_SetString(PyExc_TypeError,
1471 "coercion should return None or 2-tuple");
1472 return NULL;
1474 v1 = PyTuple_GetItem(coerced, 0);
1475 w = PyTuple_GetItem(coerced, 1);
1476 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1477 /* prevent recursion if __coerce__ returns self as the first
1478 * argument */
1479 result = generic_binary_op(v1, w, opname);
1480 } else {
1481 if (Py_EnterRecursiveCall(" after coercion"))
1482 return NULL;
1483 if (swapped)
1484 result = (thisfunc)(w, v1);
1485 else
1486 result = (thisfunc)(v1, w);
1487 Py_LeaveRecursiveCall();
1489 Py_DECREF(coerced);
1490 return result;
1493 /* Implement a binary operator involving at least one class instance. */
1494 static PyObject *
1495 do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1496 binaryfunc thisfunc)
1498 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1499 if (result == Py_NotImplemented) {
1500 Py_DECREF(result);
1501 result = half_binop(w, v, ropname, thisfunc, 1);
1503 return result;
1506 static PyObject *
1507 do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1508 char *ropname, binaryfunc thisfunc)
1510 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1511 if (result == Py_NotImplemented) {
1512 Py_DECREF(result);
1513 result = do_binop(v, w, opname, ropname, thisfunc);
1515 return result;
1518 static int
1519 instance_coerce(PyObject **pv, PyObject **pw)
1521 PyObject *v = *pv;
1522 PyObject *w = *pw;
1523 PyObject *coercefunc;
1524 PyObject *args;
1525 PyObject *coerced;
1527 if (coerce_obj == NULL) {
1528 coerce_obj = PyString_InternFromString("__coerce__");
1529 if (coerce_obj == NULL)
1530 return -1;
1532 coercefunc = PyObject_GetAttr(v, coerce_obj);
1533 if (coercefunc == NULL) {
1534 /* No __coerce__ method */
1535 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1536 return -1;
1537 PyErr_Clear();
1538 return 1;
1540 /* Has __coerce__ method: call it */
1541 args = PyTuple_Pack(1, w);
1542 if (args == NULL) {
1543 return -1;
1545 coerced = PyEval_CallObject(coercefunc, args);
1546 Py_DECREF(args);
1547 Py_DECREF(coercefunc);
1548 if (coerced == NULL) {
1549 /* __coerce__ call raised an exception */
1550 return -1;
1552 if (coerced == Py_None || coerced == Py_NotImplemented) {
1553 /* __coerce__ says "I can't do it" */
1554 Py_DECREF(coerced);
1555 return 1;
1557 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1558 /* __coerce__ return value is malformed */
1559 Py_DECREF(coerced);
1560 PyErr_SetString(PyExc_TypeError,
1561 "coercion should return None or 2-tuple");
1562 return -1;
1564 /* __coerce__ returned two new values */
1565 *pv = PyTuple_GetItem(coerced, 0);
1566 *pw = PyTuple_GetItem(coerced, 1);
1567 Py_INCREF(*pv);
1568 Py_INCREF(*pw);
1569 Py_DECREF(coerced);
1570 return 0;
1573 #define UNARY(funcname, methodname) \
1574 static PyObject *funcname(PyInstanceObject *self) { \
1575 static PyObject *o; \
1576 if (o == NULL) { o = PyString_InternFromString(methodname); \
1577 if (o == NULL) return NULL; } \
1578 return generic_unary_op(self, o); \
1581 /* unary function with a fallback */
1582 #define UNARY_FB(funcname, methodname, funcname_fb) \
1583 static PyObject *funcname(PyInstanceObject *self) { \
1584 static PyObject *o; \
1585 if (o == NULL) { o = PyString_InternFromString(methodname); \
1586 if (o == NULL) return NULL; } \
1587 if (PyObject_HasAttr((PyObject*)self, o)) \
1588 return generic_unary_op(self, o); \
1589 else \
1590 return funcname_fb(self); \
1593 #define BINARY(f, m, n) \
1594 static PyObject *f(PyObject *v, PyObject *w) { \
1595 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1598 #define BINARY_INPLACE(f, m, n) \
1599 static PyObject *f(PyObject *v, PyObject *w) { \
1600 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1601 "__r" m "__", n); \
1604 UNARY(instance_neg, "__neg__")
1605 UNARY(instance_pos, "__pos__")
1606 UNARY(instance_abs, "__abs__")
1608 BINARY(instance_or, "or", PyNumber_Or)
1609 BINARY(instance_and, "and", PyNumber_And)
1610 BINARY(instance_xor, "xor", PyNumber_Xor)
1611 BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1612 BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1613 BINARY(instance_add, "add", PyNumber_Add)
1614 BINARY(instance_sub, "sub", PyNumber_Subtract)
1615 BINARY(instance_mul, "mul", PyNumber_Multiply)
1616 BINARY(instance_div, "div", PyNumber_Divide)
1617 BINARY(instance_mod, "mod", PyNumber_Remainder)
1618 BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1619 BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1620 BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1622 BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1623 BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1624 BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1625 BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1626 BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1627 BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1628 BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1629 BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1630 BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1631 BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1632 BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1633 BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1635 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1636 -2 for an exception;
1637 -1 if v < w;
1638 0 if v == w;
1639 1 if v > w;
1640 2 if this particular 3-way comparison is not implemented or undefined.
1642 static int
1643 half_cmp(PyObject *v, PyObject *w)
1645 static PyObject *cmp_obj;
1646 PyObject *args;
1647 PyObject *cmp_func;
1648 PyObject *result;
1649 long l;
1651 assert(PyInstance_Check(v));
1653 if (cmp_obj == NULL) {
1654 cmp_obj = PyString_InternFromString("__cmp__");
1655 if (cmp_obj == NULL)
1656 return -2;
1659 cmp_func = PyObject_GetAttr(v, cmp_obj);
1660 if (cmp_func == NULL) {
1661 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1662 return -2;
1663 PyErr_Clear();
1664 return 2;
1667 args = PyTuple_Pack(1, w);
1668 if (args == NULL) {
1669 Py_DECREF(cmp_func);
1670 return -2;
1673 result = PyEval_CallObject(cmp_func, args);
1674 Py_DECREF(args);
1675 Py_DECREF(cmp_func);
1677 if (result == NULL)
1678 return -2;
1680 if (result == Py_NotImplemented) {
1681 Py_DECREF(result);
1682 return 2;
1685 l = PyInt_AsLong(result);
1686 Py_DECREF(result);
1687 if (l == -1 && PyErr_Occurred()) {
1688 PyErr_SetString(PyExc_TypeError,
1689 "comparison did not return an int");
1690 return -2;
1693 return l < 0 ? -1 : l > 0 ? 1 : 0;
1696 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1697 We first try a coercion. Return:
1698 -2 for an exception;
1699 -1 if v < w;
1700 0 if v == w;
1701 1 if v > w;
1702 2 if this particular 3-way comparison is not implemented or undefined.
1703 THIS IS ONLY CALLED FROM object.c!
1705 static int
1706 instance_compare(PyObject *v, PyObject *w)
1708 int c;
1710 c = PyNumber_CoerceEx(&v, &w);
1711 if (c < 0)
1712 return -2;
1713 if (c == 0) {
1714 /* If neither is now an instance, use regular comparison */
1715 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1716 c = PyObject_Compare(v, w);
1717 Py_DECREF(v);
1718 Py_DECREF(w);
1719 if (PyErr_Occurred())
1720 return -2;
1721 return c < 0 ? -1 : c > 0 ? 1 : 0;
1724 else {
1725 /* The coercion didn't do anything.
1726 Treat this the same as returning v and w unchanged. */
1727 Py_INCREF(v);
1728 Py_INCREF(w);
1731 if (PyInstance_Check(v)) {
1732 c = half_cmp(v, w);
1733 if (c <= 1) {
1734 Py_DECREF(v);
1735 Py_DECREF(w);
1736 return c;
1739 if (PyInstance_Check(w)) {
1740 c = half_cmp(w, v);
1741 if (c <= 1) {
1742 Py_DECREF(v);
1743 Py_DECREF(w);
1744 if (c >= -1)
1745 c = -c;
1746 return c;
1749 Py_DECREF(v);
1750 Py_DECREF(w);
1751 return 2;
1754 static int
1755 instance_nonzero(PyInstanceObject *self)
1757 PyObject *func, *res;
1758 long outcome;
1759 static PyObject *nonzerostr;
1761 if (nonzerostr == NULL) {
1762 nonzerostr = PyString_InternFromString("__nonzero__");
1763 if (nonzerostr == NULL)
1764 return -1;
1766 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1767 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1768 return -1;
1769 PyErr_Clear();
1770 if (lenstr == NULL) {
1771 lenstr = PyString_InternFromString("__len__");
1772 if (lenstr == NULL)
1773 return -1;
1775 if ((func = instance_getattr(self, lenstr)) == NULL) {
1776 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1777 return -1;
1778 PyErr_Clear();
1779 /* Fall back to the default behavior:
1780 all instances are nonzero */
1781 return 1;
1784 res = PyEval_CallObject(func, (PyObject *)NULL);
1785 Py_DECREF(func);
1786 if (res == NULL)
1787 return -1;
1788 if (!PyInt_Check(res)) {
1789 Py_DECREF(res);
1790 PyErr_SetString(PyExc_TypeError,
1791 "__nonzero__ should return an int");
1792 return -1;
1794 outcome = PyInt_AsLong(res);
1795 Py_DECREF(res);
1796 if (outcome < 0) {
1797 PyErr_SetString(PyExc_ValueError,
1798 "__nonzero__ should return >= 0");
1799 return -1;
1801 return outcome > 0;
1804 static PyObject *
1805 instance_index(PyInstanceObject *self)
1807 PyObject *func, *res;
1808 static PyObject *indexstr = NULL;
1810 if (indexstr == NULL) {
1811 indexstr = PyString_InternFromString("__index__");
1812 if (indexstr == NULL)
1813 return NULL;
1815 if ((func = instance_getattr(self, indexstr)) == NULL) {
1816 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1817 return NULL;
1818 PyErr_Clear();
1819 PyErr_SetString(PyExc_TypeError,
1820 "object cannot be interpreted as an index");
1821 return NULL;
1823 res = PyEval_CallObject(func, (PyObject *)NULL);
1824 Py_DECREF(func);
1825 return res;
1829 UNARY(instance_invert, "__invert__")
1830 UNARY(_instance_trunc, "__trunc__")
1832 static PyObject *
1833 instance_int(PyInstanceObject *self)
1835 PyObject *truncated;
1836 static PyObject *int_name;
1837 if (int_name == NULL) {
1838 int_name = PyString_InternFromString("__int__");
1839 if (int_name == NULL)
1840 return NULL;
1842 if (PyObject_HasAttr((PyObject*)self, int_name))
1843 return generic_unary_op(self, int_name);
1845 truncated = _instance_trunc(self);
1846 /* __trunc__ is specified to return an Integral type, but
1847 int() needs to return an int. */
1848 return _PyNumber_ConvertIntegralToInt(
1849 truncated,
1850 "__trunc__ returned non-Integral (type %.200s)");
1853 UNARY_FB(instance_long, "__long__", instance_int)
1854 UNARY(instance_float, "__float__")
1855 UNARY(instance_oct, "__oct__")
1856 UNARY(instance_hex, "__hex__")
1858 static PyObject *
1859 bin_power(PyObject *v, PyObject *w)
1861 return PyNumber_Power(v, w, Py_None);
1864 /* This version is for ternary calls only (z != None) */
1865 static PyObject *
1866 instance_pow(PyObject *v, PyObject *w, PyObject *z)
1868 if (z == Py_None) {
1869 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1871 else {
1872 PyObject *func;
1873 PyObject *args;
1874 PyObject *result;
1876 /* XXX Doesn't do coercions... */
1877 func = PyObject_GetAttrString(v, "__pow__");
1878 if (func == NULL)
1879 return NULL;
1880 args = PyTuple_Pack(2, w, z);
1881 if (args == NULL) {
1882 Py_DECREF(func);
1883 return NULL;
1885 result = PyEval_CallObject(func, args);
1886 Py_DECREF(func);
1887 Py_DECREF(args);
1888 return result;
1892 static PyObject *
1893 bin_inplace_power(PyObject *v, PyObject *w)
1895 return PyNumber_InPlacePower(v, w, Py_None);
1899 static PyObject *
1900 instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1902 if (z == Py_None) {
1903 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1904 "__rpow__", bin_inplace_power);
1906 else {
1907 /* XXX Doesn't do coercions... */
1908 PyObject *func;
1909 PyObject *args;
1910 PyObject *result;
1912 func = PyObject_GetAttrString(v, "__ipow__");
1913 if (func == NULL) {
1914 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1915 return NULL;
1916 PyErr_Clear();
1917 return instance_pow(v, w, z);
1919 args = PyTuple_Pack(2, w, z);
1920 if (args == NULL) {
1921 Py_DECREF(func);
1922 return NULL;
1924 result = PyEval_CallObject(func, args);
1925 Py_DECREF(func);
1926 Py_DECREF(args);
1927 return result;
1932 /* Map rich comparison operators to their __xx__ namesakes */
1933 #define NAME_OPS 6
1934 static PyObject **name_op = NULL;
1936 static int
1937 init_name_op(void)
1939 int i;
1940 char *_name_op[] = {
1941 "__lt__",
1942 "__le__",
1943 "__eq__",
1944 "__ne__",
1945 "__gt__",
1946 "__ge__",
1949 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1950 if (name_op == NULL)
1951 return -1;
1952 for (i = 0; i < NAME_OPS; ++i) {
1953 name_op[i] = PyString_InternFromString(_name_op[i]);
1954 if (name_op[i] == NULL)
1955 return -1;
1957 return 0;
1960 static PyObject *
1961 half_richcompare(PyObject *v, PyObject *w, int op)
1963 PyObject *method;
1964 PyObject *args;
1965 PyObject *res;
1967 assert(PyInstance_Check(v));
1969 if (name_op == NULL) {
1970 if (init_name_op() < 0)
1971 return NULL;
1973 /* If the instance doesn't define an __getattr__ method, use
1974 instance_getattr2 directly because it will not set an
1975 exception on failure. */
1976 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1977 method = instance_getattr2((PyInstanceObject *)v,
1978 name_op[op]);
1979 else
1980 method = PyObject_GetAttr(v, name_op[op]);
1981 if (method == NULL) {
1982 if (PyErr_Occurred()) {
1983 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1984 return NULL;
1985 PyErr_Clear();
1987 res = Py_NotImplemented;
1988 Py_INCREF(res);
1989 return res;
1992 args = PyTuple_Pack(1, w);
1993 if (args == NULL) {
1994 Py_DECREF(method);
1995 return NULL;
1998 res = PyEval_CallObject(method, args);
1999 Py_DECREF(args);
2000 Py_DECREF(method);
2002 return res;
2005 static PyObject *
2006 instance_richcompare(PyObject *v, PyObject *w, int op)
2008 PyObject *res;
2010 if (PyInstance_Check(v)) {
2011 res = half_richcompare(v, w, op);
2012 if (res != Py_NotImplemented)
2013 return res;
2014 Py_DECREF(res);
2017 if (PyInstance_Check(w)) {
2018 res = half_richcompare(w, v, _Py_SwappedOp[op]);
2019 if (res != Py_NotImplemented)
2020 return res;
2021 Py_DECREF(res);
2024 Py_INCREF(Py_NotImplemented);
2025 return Py_NotImplemented;
2029 /* Get the iterator */
2030 static PyObject *
2031 instance_getiter(PyInstanceObject *self)
2033 PyObject *func;
2035 if (iterstr == NULL) {
2036 iterstr = PyString_InternFromString("__iter__");
2037 if (iterstr == NULL)
2038 return NULL;
2040 if (getitemstr == NULL) {
2041 getitemstr = PyString_InternFromString("__getitem__");
2042 if (getitemstr == NULL)
2043 return NULL;
2046 if ((func = instance_getattr(self, iterstr)) != NULL) {
2047 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2048 Py_DECREF(func);
2049 if (res != NULL && !PyIter_Check(res)) {
2050 PyErr_Format(PyExc_TypeError,
2051 "__iter__ returned non-iterator "
2052 "of type '%.100s'",
2053 res->ob_type->tp_name);
2054 Py_DECREF(res);
2055 res = NULL;
2057 return res;
2059 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2060 return NULL;
2061 PyErr_Clear();
2062 if ((func = instance_getattr(self, getitemstr)) == NULL) {
2063 PyErr_SetString(PyExc_TypeError,
2064 "iteration over non-sequence");
2065 return NULL;
2067 Py_DECREF(func);
2068 return PySeqIter_New((PyObject *)self);
2072 /* Call the iterator's next */
2073 static PyObject *
2074 instance_iternext(PyInstanceObject *self)
2076 PyObject *func;
2078 if (nextstr == NULL) {
2079 nextstr = PyString_InternFromString("next");
2080 if (nextstr == NULL)
2081 return NULL;
2084 if ((func = instance_getattr(self, nextstr)) != NULL) {
2085 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2086 Py_DECREF(func);
2087 if (res != NULL) {
2088 return res;
2090 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
2091 PyErr_Clear();
2092 return NULL;
2094 return NULL;
2096 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
2097 return NULL;
2100 static PyObject *
2101 instance_call(PyObject *func, PyObject *arg, PyObject *kw)
2103 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
2104 if (call == NULL) {
2105 PyInstanceObject *inst = (PyInstanceObject*) func;
2106 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2107 return NULL;
2108 PyErr_Clear();
2109 PyErr_Format(PyExc_AttributeError,
2110 "%.200s instance has no __call__ method",
2111 PyString_AsString(inst->in_class->cl_name));
2112 return NULL;
2114 /* We must check and increment the recursion depth here. Scenario:
2115 class A:
2116 pass
2117 A.__call__ = A() # that's right
2118 a = A() # ok
2119 a() # infinite recursion
2120 This bounces between instance_call() and PyObject_Call() without
2121 ever hitting eval_frame() (which has the main recursion check). */
2122 if (Py_EnterRecursiveCall(" in __call__")) {
2123 res = NULL;
2125 else {
2126 res = PyObject_Call(call, arg, kw);
2127 Py_LeaveRecursiveCall();
2129 Py_DECREF(call);
2130 return res;
2134 static PyNumberMethods instance_as_number = {
2135 instance_add, /* nb_add */
2136 instance_sub, /* nb_subtract */
2137 instance_mul, /* nb_multiply */
2138 instance_div, /* nb_divide */
2139 instance_mod, /* nb_remainder */
2140 instance_divmod, /* nb_divmod */
2141 instance_pow, /* nb_power */
2142 (unaryfunc)instance_neg, /* nb_negative */
2143 (unaryfunc)instance_pos, /* nb_positive */
2144 (unaryfunc)instance_abs, /* nb_absolute */
2145 (inquiry)instance_nonzero, /* nb_nonzero */
2146 (unaryfunc)instance_invert, /* nb_invert */
2147 instance_lshift, /* nb_lshift */
2148 instance_rshift, /* nb_rshift */
2149 instance_and, /* nb_and */
2150 instance_xor, /* nb_xor */
2151 instance_or, /* nb_or */
2152 instance_coerce, /* nb_coerce */
2153 (unaryfunc)instance_int, /* nb_int */
2154 (unaryfunc)instance_long, /* nb_long */
2155 (unaryfunc)instance_float, /* nb_float */
2156 (unaryfunc)instance_oct, /* nb_oct */
2157 (unaryfunc)instance_hex, /* nb_hex */
2158 instance_iadd, /* nb_inplace_add */
2159 instance_isub, /* nb_inplace_subtract */
2160 instance_imul, /* nb_inplace_multiply */
2161 instance_idiv, /* nb_inplace_divide */
2162 instance_imod, /* nb_inplace_remainder */
2163 instance_ipow, /* nb_inplace_power */
2164 instance_ilshift, /* nb_inplace_lshift */
2165 instance_irshift, /* nb_inplace_rshift */
2166 instance_iand, /* nb_inplace_and */
2167 instance_ixor, /* nb_inplace_xor */
2168 instance_ior, /* nb_inplace_or */
2169 instance_floordiv, /* nb_floor_divide */
2170 instance_truediv, /* nb_true_divide */
2171 instance_ifloordiv, /* nb_inplace_floor_divide */
2172 instance_itruediv, /* nb_inplace_true_divide */
2173 (unaryfunc)instance_index, /* nb_index */
2176 PyTypeObject PyInstance_Type = {
2177 PyObject_HEAD_INIT(&PyType_Type)
2179 "instance",
2180 sizeof(PyInstanceObject),
2182 (destructor)instance_dealloc, /* tp_dealloc */
2183 0, /* tp_print */
2184 0, /* tp_getattr */
2185 0, /* tp_setattr */
2186 instance_compare, /* tp_compare */
2187 (reprfunc)instance_repr, /* tp_repr */
2188 &instance_as_number, /* tp_as_number */
2189 &instance_as_sequence, /* tp_as_sequence */
2190 &instance_as_mapping, /* tp_as_mapping */
2191 (hashfunc)instance_hash, /* tp_hash */
2192 instance_call, /* tp_call */
2193 (reprfunc)instance_str, /* tp_str */
2194 (getattrofunc)instance_getattr, /* tp_getattro */
2195 (setattrofunc)instance_setattr, /* tp_setattro */
2196 0, /* tp_as_buffer */
2197 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2198 instance_doc, /* tp_doc */
2199 (traverseproc)instance_traverse, /* tp_traverse */
2200 0, /* tp_clear */
2201 instance_richcompare, /* tp_richcompare */
2202 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2203 (getiterfunc)instance_getiter, /* tp_iter */
2204 (iternextfunc)instance_iternext, /* tp_iternext */
2205 0, /* tp_methods */
2206 0, /* tp_members */
2207 0, /* tp_getset */
2208 0, /* tp_base */
2209 0, /* tp_dict */
2210 0, /* tp_descr_get */
2211 0, /* tp_descr_set */
2212 0, /* tp_dictoffset */
2213 0, /* tp_init */
2214 0, /* tp_alloc */
2215 instance_new, /* tp_new */
2219 /* Instance method objects are used for two purposes:
2220 (a) as bound instance methods (returned by instancename.methodname)
2221 (b) as unbound methods (returned by ClassName.methodname)
2222 In case (b), im_self is NULL
2225 PyObject *
2226 PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
2228 register PyMethodObject *im;
2229 im = free_list;
2230 if (im != NULL) {
2231 free_list = (PyMethodObject *)(im->im_self);
2232 PyObject_INIT(im, &PyMethod_Type);
2233 numfree--;
2235 else {
2236 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2237 if (im == NULL)
2238 return NULL;
2240 im->im_weakreflist = NULL;
2241 Py_INCREF(func);
2242 im->im_func = func;
2243 Py_XINCREF(self);
2244 im->im_self = self;
2245 Py_XINCREF(klass);
2246 im->im_class = klass;
2247 _PyObject_GC_TRACK(im);
2248 return (PyObject *)im;
2251 /* Descriptors for PyMethod attributes */
2253 /* im_class, im_func and im_self are stored in the PyMethod object */
2255 #define OFF(x) offsetof(PyMethodObject, x)
2257 static PyMemberDef instancemethod_memberlist[] = {
2258 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2259 "the class associated with a method"},
2260 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2261 "the function (or other callable) implementing a method"},
2262 {"__func__", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2263 "the function (or other callable) implementing a method"},
2264 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2265 "the instance to which a method is bound; None for unbound methods"},
2266 {"__self__", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2267 "the instance to which a method is bound; None for unbound methods"},
2268 {NULL} /* Sentinel */
2271 /* Christian Tismer argued convincingly that method attributes should
2272 (nearly) always override function attributes.
2273 The one exception is __doc__; there's a default __doc__ which
2274 should only be used for the class, not for instances */
2276 static PyObject *
2277 instancemethod_get_doc(PyMethodObject *im, void *context)
2279 static PyObject *docstr;
2280 if (docstr == NULL) {
2281 docstr= PyString_InternFromString("__doc__");
2282 if (docstr == NULL)
2283 return NULL;
2285 return PyObject_GetAttr(im->im_func, docstr);
2288 static PyGetSetDef instancemethod_getset[] = {
2289 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2293 static PyObject *
2294 instancemethod_getattro(PyObject *obj, PyObject *name)
2296 PyMethodObject *im = (PyMethodObject *)obj;
2297 PyTypeObject *tp = obj->ob_type;
2298 PyObject *descr = NULL;
2300 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2301 if (tp->tp_dict == NULL) {
2302 if (PyType_Ready(tp) < 0)
2303 return NULL;
2305 descr = _PyType_Lookup(tp, name);
2308 if (descr != NULL) {
2309 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
2310 if (f != NULL)
2311 return f(descr, obj, (PyObject *)obj->ob_type);
2312 else {
2313 Py_INCREF(descr);
2314 return descr;
2318 return PyObject_GetAttr(im->im_func, name);
2321 PyDoc_STRVAR(instancemethod_doc,
2322 "instancemethod(function, instance, class)\n\
2324 Create an instance method object.");
2326 static PyObject *
2327 instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2329 PyObject *func;
2330 PyObject *self;
2331 PyObject *classObj = NULL;
2333 if (!_PyArg_NoKeywords("instancemethod", kw))
2334 return NULL;
2335 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2336 &func, &self, &classObj))
2337 return NULL;
2338 if (!PyCallable_Check(func)) {
2339 PyErr_SetString(PyExc_TypeError,
2340 "first argument must be callable");
2341 return NULL;
2343 if (self == Py_None)
2344 self = NULL;
2345 if (self == NULL && classObj == NULL) {
2346 PyErr_SetString(PyExc_TypeError,
2347 "unbound methods must have non-NULL im_class");
2348 return NULL;
2351 return PyMethod_New(func, self, classObj);
2354 static void
2355 instancemethod_dealloc(register PyMethodObject *im)
2357 _PyObject_GC_UNTRACK(im);
2358 if (im->im_weakreflist != NULL)
2359 PyObject_ClearWeakRefs((PyObject *)im);
2360 Py_DECREF(im->im_func);
2361 Py_XDECREF(im->im_self);
2362 Py_XDECREF(im->im_class);
2363 if (numfree < PyMethod_MAXFREELIST) {
2364 im->im_self = (PyObject *)free_list;
2365 free_list = im;
2366 numfree++;
2368 else {
2369 PyObject_GC_Del(im);
2373 static int
2374 instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
2376 int cmp;
2377 cmp = PyObject_Compare(a->im_func, b->im_func);
2378 if (cmp)
2379 return cmp;
2381 if (a->im_self == b->im_self)
2382 return 0;
2383 if (a->im_self == NULL || b->im_self == NULL)
2384 return (a->im_self < b->im_self) ? -1 : 1;
2385 else
2386 return PyObject_Compare(a->im_self, b->im_self);
2389 static PyObject *
2390 instancemethod_repr(PyMethodObject *a)
2392 PyObject *self = a->im_self;
2393 PyObject *func = a->im_func;
2394 PyObject *klass = a->im_class;
2395 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2396 char *sfuncname = "?", *sklassname = "?";
2398 funcname = PyObject_GetAttrString(func, "__name__");
2399 if (funcname == NULL) {
2400 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2401 return NULL;
2402 PyErr_Clear();
2404 else if (!PyString_Check(funcname)) {
2405 Py_DECREF(funcname);
2406 funcname = NULL;
2408 else
2409 sfuncname = PyString_AS_STRING(funcname);
2410 if (klass == NULL)
2411 klassname = NULL;
2412 else {
2413 klassname = PyObject_GetAttrString(klass, "__name__");
2414 if (klassname == NULL) {
2415 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2416 return NULL;
2417 PyErr_Clear();
2419 else if (!PyString_Check(klassname)) {
2420 Py_DECREF(klassname);
2421 klassname = NULL;
2423 else
2424 sklassname = PyString_AS_STRING(klassname);
2426 if (self == NULL)
2427 result = PyString_FromFormat("<unbound method %s.%s>",
2428 sklassname, sfuncname);
2429 else {
2430 /* XXX Shouldn't use repr() here! */
2431 PyObject *selfrepr = PyObject_Repr(self);
2432 if (selfrepr == NULL)
2433 goto fail;
2434 if (!PyString_Check(selfrepr)) {
2435 Py_DECREF(selfrepr);
2436 goto fail;
2438 result = PyString_FromFormat("<bound method %s.%s of %s>",
2439 sklassname, sfuncname,
2440 PyString_AS_STRING(selfrepr));
2441 Py_DECREF(selfrepr);
2443 fail:
2444 Py_XDECREF(funcname);
2445 Py_XDECREF(klassname);
2446 return result;
2449 static long
2450 instancemethod_hash(PyMethodObject *a)
2452 long x, y;
2453 if (a->im_self == NULL)
2454 x = PyObject_Hash(Py_None);
2455 else
2456 x = PyObject_Hash(a->im_self);
2457 if (x == -1)
2458 return -1;
2459 y = PyObject_Hash(a->im_func);
2460 if (y == -1)
2461 return -1;
2462 x = x ^ y;
2463 if (x == -1)
2464 x = -2;
2465 return x;
2468 static int
2469 instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2471 Py_VISIT(im->im_func);
2472 Py_VISIT(im->im_self);
2473 Py_VISIT(im->im_class);
2474 return 0;
2477 static void
2478 getclassname(PyObject *klass, char *buf, int bufsize)
2480 PyObject *name;
2482 assert(bufsize > 1);
2483 strcpy(buf, "?"); /* Default outcome */
2484 if (klass == NULL)
2485 return;
2486 name = PyObject_GetAttrString(klass, "__name__");
2487 if (name == NULL) {
2488 /* This function cannot return an exception */
2489 PyErr_Clear();
2490 return;
2492 if (PyString_Check(name)) {
2493 strncpy(buf, PyString_AS_STRING(name), bufsize);
2494 buf[bufsize-1] = '\0';
2496 Py_DECREF(name);
2499 static void
2500 getinstclassname(PyObject *inst, char *buf, int bufsize)
2502 PyObject *klass;
2504 if (inst == NULL) {
2505 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2506 strcpy(buf, "nothing");
2507 return;
2510 klass = PyObject_GetAttrString(inst, "__class__");
2511 if (klass == NULL) {
2512 /* This function cannot return an exception */
2513 PyErr_Clear();
2514 klass = (PyObject *)(inst->ob_type);
2515 Py_INCREF(klass);
2517 getclassname(klass, buf, bufsize);
2518 Py_XDECREF(klass);
2521 static PyObject *
2522 instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2524 PyObject *self = PyMethod_GET_SELF(func);
2525 PyObject *klass = PyMethod_GET_CLASS(func);
2526 PyObject *result;
2528 func = PyMethod_GET_FUNCTION(func);
2529 if (self == NULL) {
2530 /* Unbound methods must be called with an instance of
2531 the class (or a derived class) as first argument */
2532 int ok;
2533 if (PyTuple_Size(arg) >= 1)
2534 self = PyTuple_GET_ITEM(arg, 0);
2535 if (self == NULL)
2536 ok = 0;
2537 else {
2538 ok = PyObject_IsInstance(self, klass);
2539 if (ok < 0)
2540 return NULL;
2542 if (!ok) {
2543 char clsbuf[256];
2544 char instbuf[256];
2545 getclassname(klass, clsbuf, sizeof(clsbuf));
2546 getinstclassname(self, instbuf, sizeof(instbuf));
2547 PyErr_Format(PyExc_TypeError,
2548 "unbound method %s%s must be called with "
2549 "%s instance as first argument "
2550 "(got %s%s instead)",
2551 PyEval_GetFuncName(func),
2552 PyEval_GetFuncDesc(func),
2553 clsbuf,
2554 instbuf,
2555 self == NULL ? "" : " instance");
2556 return NULL;
2558 Py_INCREF(arg);
2560 else {
2561 Py_ssize_t argcount = PyTuple_Size(arg);
2562 PyObject *newarg = PyTuple_New(argcount + 1);
2563 int i;
2564 if (newarg == NULL)
2565 return NULL;
2566 Py_INCREF(self);
2567 PyTuple_SET_ITEM(newarg, 0, self);
2568 for (i = 0; i < argcount; i++) {
2569 PyObject *v = PyTuple_GET_ITEM(arg, i);
2570 Py_XINCREF(v);
2571 PyTuple_SET_ITEM(newarg, i+1, v);
2573 arg = newarg;
2575 result = PyObject_Call((PyObject *)func, arg, kw);
2576 Py_DECREF(arg);
2577 return result;
2580 static PyObject *
2581 instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
2583 /* Don't rebind an already bound method, or an unbound method
2584 of a class that's not a base class of cls. */
2586 if (PyMethod_GET_SELF(meth) != NULL) {
2587 /* Already bound */
2588 Py_INCREF(meth);
2589 return meth;
2591 /* No, it is an unbound method */
2592 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2593 /* Do subclass test. If it fails, return meth unchanged. */
2594 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2595 if (ok < 0)
2596 return NULL;
2597 if (!ok) {
2598 Py_INCREF(meth);
2599 return meth;
2602 /* Bind it to obj */
2603 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
2606 PyTypeObject PyMethod_Type = {
2607 PyObject_HEAD_INIT(&PyType_Type)
2609 "instancemethod",
2610 sizeof(PyMethodObject),
2612 (destructor)instancemethod_dealloc, /* tp_dealloc */
2613 0, /* tp_print */
2614 0, /* tp_getattr */
2615 0, /* tp_setattr */
2616 (cmpfunc)instancemethod_compare, /* tp_compare */
2617 (reprfunc)instancemethod_repr, /* tp_repr */
2618 0, /* tp_as_number */
2619 0, /* tp_as_sequence */
2620 0, /* tp_as_mapping */
2621 (hashfunc)instancemethod_hash, /* tp_hash */
2622 instancemethod_call, /* tp_call */
2623 0, /* tp_str */
2624 instancemethod_getattro, /* tp_getattro */
2625 PyObject_GenericSetAttr, /* tp_setattro */
2626 0, /* tp_as_buffer */
2627 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2628 instancemethod_doc, /* tp_doc */
2629 (traverseproc)instancemethod_traverse, /* tp_traverse */
2630 0, /* tp_clear */
2631 0, /* tp_richcompare */
2632 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2633 0, /* tp_iter */
2634 0, /* tp_iternext */
2635 0, /* tp_methods */
2636 instancemethod_memberlist, /* tp_members */
2637 instancemethod_getset, /* tp_getset */
2638 0, /* tp_base */
2639 0, /* tp_dict */
2640 instancemethod_descr_get, /* tp_descr_get */
2641 0, /* tp_descr_set */
2642 0, /* tp_dictoffset */
2643 0, /* tp_init */
2644 0, /* tp_alloc */
2645 instancemethod_new, /* tp_new */
2648 /* Clear out the free list */
2651 PyMethod_ClearFreeList(void)
2653 int freelist_size = numfree;
2655 while (free_list) {
2656 PyMethodObject *im = free_list;
2657 free_list = (PyMethodObject *)(im->im_self);
2658 PyObject_GC_Del(im);
2659 numfree--;
2661 assert(numfree == 0);
2662 return freelist_size;
2665 void
2666 PyMethod_Fini(void)
2668 (void)PyMethod_ClearFreeList();