blob: 0832531422de83c2603ac99df66a849b59f7a405 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Class object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005#include "structmember.h"
Guido van Rossum04691fc1992-08-12 15:35:34 +00006
Christian Heimes6075a822008-02-06 12:44:34 +00007/* Free list for method objects to safe malloc/free overhead
8 * The im_self element is used to chain the elements.
9 */
10static PyMethodObject *free_list;
11static int numfree = 0;
Christian Heimes5b970ad2008-02-06 13:33:44 +000012#ifndef PyMethod_MAXFREELIST
13#define PyMethod_MAXFREELIST 256
14#endif
Christian Heimes6075a822008-02-06 12:44:34 +000015
Guido van Rossum915f0eb2001-10-17 20:26:38 +000016#define TP_DESCR_GET(t) \
17 (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
18
Guido van Rossum52ca98a1994-09-05 07:32:29 +000019/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000020static PyObject *class_lookup(PyClassObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000021 PyClassObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +000022static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
23static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
Guido van Rossum52ca98a1994-09-05 07:32:29 +000024
Guido van Rossuma63eff61998-05-29 21:37:21 +000025static PyObject *getattrstr, *setattrstr, *delattrstr;
26
Fred Drake79912472000-07-09 04:06:11 +000027
Guido van Rossumc0b618a1997-05-02 03:12:38 +000028PyObject *
Fred Drake79912472000-07-09 04:06:11 +000029PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
30 /* bases is NULL or tuple of classobjects! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000032 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;
38 }
39 if (modstr == NULL) {
40 modstr= PyString_InternFromString("__module__");
41 if (modstr == NULL)
42 return NULL;
43 }
44 if (namestr == NULL) {
45 namestr= PyString_InternFromString("__name__");
46 if (namestr == NULL)
47 return NULL;
48 }
49 if (name == NULL || !PyString_Check(name)) {
50 PyErr_SetString(PyExc_TypeError,
51 "PyClass_New: name must be a string");
52 return NULL;
53 }
54 if (dict == NULL || !PyDict_Check(dict)) {
55 PyErr_SetString(PyExc_TypeError,
56 "PyClass_New: dict must be a dictionary");
57 return NULL;
58 }
59 if (PyDict_GetItem(dict, docstr) == NULL) {
60 if (PyDict_SetItem(dict, docstr, Py_None) < 0)
61 return NULL;
62 }
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;
70 }
71 }
72 }
73 if (bases == NULL) {
74 bases = PyTuple_New(0);
75 if (bases == NULL)
76 return NULL;
77 }
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;
85 }
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;
98 }
99 }
100 Py_INCREF(bases);
101 }
Neal Norwitz6cbb7262006-08-19 04:22:33 +0000102
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000103 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;
113 }
Neal Norwitz6cbb7262006-08-19 04:22:33 +0000114
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000115 op = PyObject_GC_New(PyClassObject, &PyClass_Type);
116 if (op == NULL) {
Neal Norwitz6cbb7262006-08-19 04:22:33 +0000117alloc_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000118 Py_DECREF(bases);
119 return NULL;
120 }
121 op->cl_bases = bases;
122 Py_INCREF(dict);
123 op->cl_dict = dict;
124 Py_XINCREF(name);
125 op->cl_name = name;
126 op->cl_weakreflist = NULL;
Neal Norwitz6cbb7262006-08-19 04:22:33 +0000127
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000128 op->cl_getattr = class_lookup(op, getattrstr, &dummy);
129 op->cl_setattr = class_lookup(op, setattrstr, &dummy);
130 op->cl_delattr = class_lookup(op, delattrstr, &dummy);
131 Py_XINCREF(op->cl_getattr);
132 Py_XINCREF(op->cl_setattr);
133 Py_XINCREF(op->cl_delattr);
134 _PyObject_GC_TRACK(op);
135 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136}
137
Guido van Rossumb479dc52001-09-05 22:52:50 +0000138PyObject *
139PyMethod_Function(PyObject *im)
140{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000141 if (!PyMethod_Check(im)) {
142 PyErr_BadInternalCall();
143 return NULL;
144 }
145 return ((PyMethodObject *)im)->im_func;
Guido van Rossumb479dc52001-09-05 22:52:50 +0000146}
147
148PyObject *
149PyMethod_Self(PyObject *im)
150{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000151 if (!PyMethod_Check(im)) {
152 PyErr_BadInternalCall();
153 return NULL;
154 }
155 return ((PyMethodObject *)im)->im_self;
Guido van Rossumb479dc52001-09-05 22:52:50 +0000156}
157
158PyObject *
159PyMethod_Class(PyObject *im)
160{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000161 if (!PyMethod_Check(im)) {
162 PyErr_BadInternalCall();
163 return NULL;
164 }
165 return ((PyMethodObject *)im)->im_class;
Guido van Rossumb479dc52001-09-05 22:52:50 +0000166}
167
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000168PyDoc_STRVAR(class_doc,
169"classobj(name, bases, dict)\n\
170\n\
171Create a class object. The name must be a string; the second argument\n\
172a tuple of classes, and the third a dictionary.");
173
174static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000175class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
176{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000177 PyObject *name, *bases, *dict;
178 static char *kwlist[] = {"name", "bases", "dict", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000180 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
181 &name, &bases, &dict))
182 return NULL;
183 return PyClass_New(bases, dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000184}
185
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186/* Class methods */
187
188static void
Fred Drake79912472000-07-09 04:06:11 +0000189class_dealloc(PyClassObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000191 _PyObject_GC_UNTRACK(op);
192 if (op->cl_weakreflist != NULL)
193 PyObject_ClearWeakRefs((PyObject *) op);
194 Py_DECREF(op->cl_bases);
195 Py_DECREF(op->cl_dict);
196 Py_XDECREF(op->cl_name);
197 Py_XDECREF(op->cl_getattr);
198 Py_XDECREF(op->cl_setattr);
199 Py_XDECREF(op->cl_delattr);
200 PyObject_GC_Del(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201}
202
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000203static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000204class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
Guido van Rossum81daa321993-05-20 14:24:46 +0000205{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000206 Py_ssize_t i, n;
207 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
208 if (value != NULL) {
209 *pclass = cp;
210 return value;
211 }
212 n = PyTuple_Size(cp->cl_bases);
213 for (i = 0; i < n; i++) {
214 /* XXX What if one of the bases is not a class? */
215 PyObject *v = class_lookup(
216 (PyClassObject *)
217 PyTuple_GetItem(cp->cl_bases, i), name, pclass);
218 if (v != NULL)
219 return v;
220 }
221 return NULL;
Guido van Rossum81daa321993-05-20 14:24:46 +0000222}
223
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000224static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000225class_getattr(register PyClassObject *op, PyObject *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227 register PyObject *v;
228 register char *sname = PyString_AsString(name);
229 PyClassObject *klass;
230 descrgetfunc f;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000232 if (sname[0] == '_' && sname[1] == '_') {
233 if (strcmp(sname, "__dict__") == 0) {
234 if (PyEval_GetRestricted()) {
235 PyErr_SetString(PyExc_RuntimeError,
236 "class.__dict__ not accessible in restricted mode");
237 return NULL;
238 }
239 Py_INCREF(op->cl_dict);
240 return op->cl_dict;
241 }
242 if (strcmp(sname, "__bases__") == 0) {
243 Py_INCREF(op->cl_bases);
244 return op->cl_bases;
245 }
246 if (strcmp(sname, "__name__") == 0) {
247 if (op->cl_name == NULL)
248 v = Py_None;
249 else
250 v = op->cl_name;
251 Py_INCREF(v);
252 return v;
253 }
254 }
255 v = class_lookup(op, name, &klass);
256 if (v == NULL) {
257 PyErr_Format(PyExc_AttributeError,
258 "class %.50s has no attribute '%.400s'",
259 PyString_AS_STRING(op->cl_name), sname);
260 return NULL;
261 }
262 f = TP_DESCR_GET(v->ob_type);
263 if (f == NULL)
264 Py_INCREF(v);
265 else
266 v = f(v, (PyObject *)NULL, (PyObject *)op);
267 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000268}
269
Guido van Rossuma63eff61998-05-29 21:37:21 +0000270static void
Fred Drake79912472000-07-09 04:06:11 +0000271set_slot(PyObject **slot, PyObject *v)
Guido van Rossuma63eff61998-05-29 21:37:21 +0000272{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000273 PyObject *temp = *slot;
274 Py_XINCREF(v);
275 *slot = v;
276 Py_XDECREF(temp);
Guido van Rossuma63eff61998-05-29 21:37:21 +0000277}
278
Guido van Rossum7ba30431998-07-08 13:34:48 +0000279static void
Fred Drake79912472000-07-09 04:06:11 +0000280set_attr_slots(PyClassObject *c)
Guido van Rossum7ba30431998-07-08 13:34:48 +0000281{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000282 PyClassObject *dummy;
Guido van Rossum7ba30431998-07-08 13:34:48 +0000283
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000284 set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
285 set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
286 set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
Guido van Rossum7ba30431998-07-08 13:34:48 +0000287}
288
Guido van Rossuma63eff61998-05-29 21:37:21 +0000289static char *
Fred Drake79912472000-07-09 04:06:11 +0000290set_dict(PyClassObject *c, PyObject *v)
Guido van Rossuma63eff61998-05-29 21:37:21 +0000291{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 if (v == NULL || !PyDict_Check(v))
293 return "__dict__ must be a dictionary object";
294 set_slot(&c->cl_dict, v);
295 set_attr_slots(c);
296 return "";
Guido van Rossuma63eff61998-05-29 21:37:21 +0000297}
298
299static char *
Fred Drake79912472000-07-09 04:06:11 +0000300set_bases(PyClassObject *c, PyObject *v)
Guido van Rossuma63eff61998-05-29 21:37:21 +0000301{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000302 Py_ssize_t i, n;
Guido van Rossuma63eff61998-05-29 21:37:21 +0000303
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000304 if (v == NULL || !PyTuple_Check(v))
305 return "__bases__ must be a tuple object";
306 n = PyTuple_Size(v);
307 for (i = 0; i < n; i++) {
308 PyObject *x = PyTuple_GET_ITEM(v, i);
309 if (!PyClass_Check(x))
310 return "__bases__ items must be classes";
311 if (PyClass_IsSubclass(x, (PyObject *)c))
312 return "a __bases__ item causes an inheritance cycle";
313 }
314 set_slot(&c->cl_bases, v);
315 set_attr_slots(c);
316 return "";
Guido van Rossuma63eff61998-05-29 21:37:21 +0000317}
318
319static char *
Fred Drake79912472000-07-09 04:06:11 +0000320set_name(PyClassObject *c, PyObject *v)
Guido van Rossuma63eff61998-05-29 21:37:21 +0000321{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000322 if (v == NULL || !PyString_Check(v))
323 return "__name__ must be a string object";
324 if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
325 return "__name__ must not contain null bytes";
326 set_slot(&c->cl_name, v);
327 return "";
Guido van Rossuma63eff61998-05-29 21:37:21 +0000328}
329
Guido van Rossum94308391991-10-20 20:11:48 +0000330static int
Fred Drake79912472000-07-09 04:06:11 +0000331class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
Guido van Rossum94308391991-10-20 20:11:48 +0000332{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000333 char *sname;
334 if (PyEval_GetRestricted()) {
335 PyErr_SetString(PyExc_RuntimeError,
336 "classes are read-only in restricted mode");
337 return -1;
338 }
339 sname = PyString_AsString(name);
340 if (sname[0] == '_' && sname[1] == '_') {
341 Py_ssize_t n = PyString_Size(name);
342 if (sname[n-1] == '_' && sname[n-2] == '_') {
343 char *err = NULL;
344 if (strcmp(sname, "__dict__") == 0)
345 err = set_dict(op, v);
346 else if (strcmp(sname, "__bases__") == 0)
347 err = set_bases(op, v);
348 else if (strcmp(sname, "__name__") == 0)
349 err = set_name(op, v);
350 else if (strcmp(sname, "__getattr__") == 0)
351 set_slot(&op->cl_getattr, v);
352 else if (strcmp(sname, "__setattr__") == 0)
353 set_slot(&op->cl_setattr, v);
354 else if (strcmp(sname, "__delattr__") == 0)
355 set_slot(&op->cl_delattr, v);
356 /* For the last three, we fall through to update the
357 dictionary as well. */
358 if (err != NULL) {
359 if (*err == '\0')
360 return 0;
361 PyErr_SetString(PyExc_TypeError, err);
362 return -1;
363 }
364 }
365 }
366 if (v == NULL) {
367 int rv = PyDict_DelItem(op->cl_dict, name);
368 if (rv < 0)
369 PyErr_Format(PyExc_AttributeError,
370 "class %.50s has no attribute '%.400s'",
371 PyString_AS_STRING(op->cl_name), sname);
372 return rv;
373 }
374 else
375 return PyDict_SetItem(op->cl_dict, name, v);
Guido van Rossum94308391991-10-20 20:11:48 +0000376}
377
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000378static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000379class_repr(PyClassObject *op)
Guido van Rossum25831651993-05-19 14:50:45 +0000380{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000381 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
382 char *name;
383 if (op->cl_name == NULL || !PyString_Check(op->cl_name))
384 name = "?";
385 else
386 name = PyString_AsString(op->cl_name);
387 if (mod == NULL || !PyString_Check(mod))
388 return PyString_FromFormat("<class ?.%s at %p>", name, op);
389 else
390 return PyString_FromFormat("<class %s.%s at %p>",
391 PyString_AsString(mod),
392 name, op);
Guido van Rossum25831651993-05-19 14:50:45 +0000393}
394
Guido van Rossum4a2a6211997-10-20 23:26:11 +0000395static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000396class_str(PyClassObject *op)
Guido van Rossum4a2a6211997-10-20 23:26:11 +0000397{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000398 PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
399 PyObject *name = op->cl_name;
400 PyObject *res;
401 Py_ssize_t m, n;
Guido van Rossum4a2a6211997-10-20 23:26:11 +0000402
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000403 if (name == NULL || !PyString_Check(name))
404 return class_repr(op);
405 if (mod == NULL || !PyString_Check(mod)) {
406 Py_INCREF(name);
407 return name;
408 }
409 m = PyString_GET_SIZE(mod);
410 n = PyString_GET_SIZE(name);
411 res = PyString_FromStringAndSize((char *)NULL, m+1+n);
412 if (res != NULL) {
413 char *s = PyString_AS_STRING(res);
414 memcpy(s, PyString_AS_STRING(mod), m);
415 s += m;
416 *s++ = '.';
417 memcpy(s, PyString_AS_STRING(name), n);
418 }
419 return res;
Guido van Rossum4a2a6211997-10-20 23:26:11 +0000420}
421
Jeremy Hylton8caad492000-06-23 14:18:11 +0000422static int
423class_traverse(PyClassObject *o, visitproc visit, void *arg)
424{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000425 Py_VISIT(o->cl_bases);
426 Py_VISIT(o->cl_dict);
427 Py_VISIT(o->cl_name);
428 Py_VISIT(o->cl_getattr);
429 Py_VISIT(o->cl_setattr);
430 Py_VISIT(o->cl_delattr);
431 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +0000432}
433
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434PyTypeObject PyClass_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000435 PyObject_HEAD_INIT(&PyType_Type)
436 0,
437 "classobj",
438 sizeof(PyClassObject),
439 0,
440 (destructor)class_dealloc, /* tp_dealloc */
441 0, /* tp_print */
442 0, /* tp_getattr */
443 0, /* tp_setattr */
444 0, /* tp_compare */
445 (reprfunc)class_repr, /* tp_repr */
446 0, /* tp_as_number */
447 0, /* tp_as_sequence */
448 0, /* tp_as_mapping */
449 0, /* tp_hash */
450 PyInstance_New, /* tp_call */
451 (reprfunc)class_str, /* tp_str */
452 (getattrofunc)class_getattr, /* tp_getattro */
453 (setattrofunc)class_setattr, /* tp_setattro */
454 0, /* tp_as_buffer */
455 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
456 class_doc, /* tp_doc */
457 (traverseproc)class_traverse, /* tp_traverse */
458 0, /* tp_clear */
459 0, /* tp_richcompare */
460 offsetof(PyClassObject, cl_weakreflist), /* tp_weaklistoffset */
461 0, /* tp_iter */
462 0, /* tp_iternext */
463 0, /* tp_methods */
464 0, /* tp_members */
465 0, /* tp_getset */
466 0, /* tp_base */
467 0, /* tp_dict */
468 0, /* tp_descr_get */
469 0, /* tp_descr_set */
470 0, /* tp_dictoffset */
471 0, /* tp_init */
472 0, /* tp_alloc */
473 class_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000474};
475
Guido van Rossum81daa321993-05-20 14:24:46 +0000476int
Anthony Baxter377be112006-04-11 06:54:30 +0000477PyClass_IsSubclass(PyObject *klass, PyObject *base)
Guido van Rossum81daa321993-05-20 14:24:46 +0000478{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000479 Py_ssize_t i, n;
480 PyClassObject *cp;
481 if (klass == base)
482 return 1;
483 if (PyTuple_Check(base)) {
484 n = PyTuple_GET_SIZE(base);
485 for (i = 0; i < n; i++) {
486 if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
487 return 1;
488 }
489 return 0;
490 }
491 if (klass == NULL || !PyClass_Check(klass))
492 return 0;
493 cp = (PyClassObject *)klass;
494 n = PyTuple_Size(cp->cl_bases);
495 for (i = 0; i < n; i++) {
496 if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
497 return 1;
498 }
499 return 0;
Guido van Rossum81daa321993-05-20 14:24:46 +0000500}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501
Guido van Rossum81daa321993-05-20 14:24:46 +0000502
503/* Instance objects */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000504
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505PyObject *
Fred Drake5cc2c8c2001-01-28 03:53:08 +0000506PyInstance_NewRaw(PyObject *klass, PyObject *dict)
507{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 PyInstanceObject *inst;
Fred Drake5cc2c8c2001-01-28 03:53:08 +0000509
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000510 if (!PyClass_Check(klass)) {
511 PyErr_BadInternalCall();
512 return NULL;
513 }
514 if (dict == NULL) {
515 dict = PyDict_New();
516 if (dict == NULL)
517 return NULL;
518 }
519 else {
520 if (!PyDict_Check(dict)) {
521 PyErr_BadInternalCall();
522 return NULL;
523 }
524 Py_INCREF(dict);
525 }
526 inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
527 if (inst == NULL) {
528 Py_DECREF(dict);
529 return NULL;
530 }
531 inst->in_weakreflist = NULL;
532 Py_INCREF(klass);
533 inst->in_class = (PyClassObject *)klass;
534 inst->in_dict = dict;
535 _PyObject_GC_TRACK(inst);
536 return (PyObject *)inst;
Fred Drake5cc2c8c2001-01-28 03:53:08 +0000537}
538
539PyObject *
540PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000542 register PyInstanceObject *inst;
543 PyObject *init;
544 static PyObject *initstr;
Fred Drake5cc2c8c2001-01-28 03:53:08 +0000545
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000546 if (initstr == NULL) {
547 initstr = PyString_InternFromString("__init__");
548 if (initstr == NULL)
549 return NULL;
550 }
551 inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
552 if (inst == NULL)
553 return NULL;
554 init = instance_getattr2(inst, initstr);
555 if (init == NULL) {
556 if (PyErr_Occurred()) {
557 Py_DECREF(inst);
558 return NULL;
559 }
560 if ((arg != NULL && (!PyTuple_Check(arg) ||
561 PyTuple_Size(arg) != 0))
562 || (kw != NULL && (!PyDict_Check(kw) ||
563 PyDict_Size(kw) != 0))) {
564 PyErr_SetString(PyExc_TypeError,
565 "this constructor takes no arguments");
566 Py_DECREF(inst);
567 inst = NULL;
568 }
569 }
570 else {
571 PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
572 Py_DECREF(init);
573 if (res == NULL) {
574 Py_DECREF(inst);
575 inst = NULL;
576 }
577 else {
578 if (res != Py_None) {
579 PyErr_SetString(PyExc_TypeError,
580 "__init__() should return None");
581 Py_DECREF(inst);
582 inst = NULL;
583 }
584 Py_DECREF(res);
585 }
586 }
587 return (PyObject *)inst;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000588}
589
Guido van Rossum21ed88c1991-04-04 10:42:10 +0000590/* Instance methods */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000592PyDoc_STRVAR(instance_doc,
593"instance(class[, dict])\n\
594\n\
595Create an instance without calling its __init__() method.\n\
596The class must be a classic class.\n\
597If present, dict must be a dictionary or None.");
598
599static PyObject *
600instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
601{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000602 PyObject *klass;
603 PyObject *dict = Py_None;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000604
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000605 if (!PyArg_ParseTuple(args, "O!|O:instance",
606 &PyClass_Type, &klass, &dict))
607 return NULL;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000608
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000609 if (dict == Py_None)
610 dict = NULL;
611 else if (!PyDict_Check(dict)) {
612 PyErr_SetString(PyExc_TypeError,
613 "instance() second arg must be dictionary or None");
614 return NULL;
615 }
616 return PyInstance_NewRaw(klass, dict);
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000617}
618
619
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000620static void
Fred Drake79912472000-07-09 04:06:11 +0000621instance_dealloc(register PyInstanceObject *inst)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000622{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000623 PyObject *error_type, *error_value, *error_traceback;
624 PyObject *del;
625 static PyObject *delstr;
Tim Peters34592512002-07-11 06:23:50 +0000626
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000627 _PyObject_GC_UNTRACK(inst);
628 if (inst->in_weakreflist != NULL)
629 PyObject_ClearWeakRefs((PyObject *) inst);
Fred Drake41deb1e2001-02-01 05:27:45 +0000630
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000631 /* Temporarily resurrect the object. */
632 assert(inst->ob_type == &PyInstance_Type);
633 assert(inst->ob_refcnt == 0);
634 inst->ob_refcnt = 1;
Tim Peters6b184912000-09-17 14:40:17 +0000635
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 /* Save the current exception, if any. */
637 PyErr_Fetch(&error_type, &error_value, &error_traceback);
638 /* Execute __del__ method, if any. */
639 if (delstr == NULL) {
640 delstr = PyString_InternFromString("__del__");
641 if (delstr == NULL)
642 PyErr_WriteUnraisable((PyObject*)inst);
643 }
644 if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
645 PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
646 if (res == NULL)
647 PyErr_WriteUnraisable(del);
648 else
649 Py_DECREF(res);
650 Py_DECREF(del);
651 }
652 /* Restore the saved exception. */
653 PyErr_Restore(error_type, error_value, error_traceback);
Tim Peters34592512002-07-11 06:23:50 +0000654
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000655 /* Undo the temporary resurrection; can't use DECREF here, it would
656 * cause a recursive call.
657 */
658 assert(inst->ob_refcnt > 0);
659 if (--inst->ob_refcnt == 0) {
Guido van Rossum9ff1a442008-01-18 20:56:30 +0000660
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000661 /* New weakrefs could be created during the finalizer call.
662 If this occurs, clear them out without calling their
663 finalizers since they might rely on part of the object
664 being finalized that has already been destroyed. */
665 while (inst->in_weakreflist != NULL) {
666 _PyWeakref_ClearRef((PyWeakReference *)
667 (inst->in_weakreflist));
668 }
Guido van Rossum9ff1a442008-01-18 20:56:30 +0000669
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000670 Py_DECREF(inst->in_class);
671 Py_XDECREF(inst->in_dict);
672 PyObject_GC_Del(inst);
673 }
674 else {
675 Py_ssize_t refcnt = inst->ob_refcnt;
676 /* __del__ resurrected it! Make it look like the original
677 * Py_DECREF never happened.
678 */
679 _Py_NewReference((PyObject *)inst);
680 inst->ob_refcnt = refcnt;
681 _PyObject_GC_TRACK(inst);
682 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
683 * we need to undo that. */
684 _Py_DEC_REFTOTAL;
685 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
686 * object chain, so no more to do there.
687 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
688 * _Py_NewReference bumped tp_allocs: both of those need to be
689 * undone.
690 */
Tim Peters6b184912000-09-17 14:40:17 +0000691#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000692 --inst->ob_type->tp_frees;
693 --inst->ob_type->tp_allocs;
Tim Peters6b184912000-09-17 14:40:17 +0000694#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000695 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000696}
697
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000698static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000699instance_getattr1(register PyInstanceObject *inst, PyObject *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000701 register PyObject *v;
702 register char *sname = PyString_AsString(name);
703 if (sname[0] == '_' && sname[1] == '_') {
704 if (strcmp(sname, "__dict__") == 0) {
705 if (PyEval_GetRestricted()) {
706 PyErr_SetString(PyExc_RuntimeError,
707 "instance.__dict__ not accessible in restricted mode");
708 return NULL;
709 }
710 Py_INCREF(inst->in_dict);
711 return inst->in_dict;
712 }
713 if (strcmp(sname, "__class__") == 0) {
714 Py_INCREF(inst->in_class);
715 return (PyObject *)inst->in_class;
716 }
717 }
718 v = instance_getattr2(inst, name);
719 if (v == NULL && !PyErr_Occurred()) {
720 PyErr_Format(PyExc_AttributeError,
721 "%.50s instance has no attribute '%.400s'",
722 PyString_AS_STRING(inst->in_class->cl_name), sname);
723 }
724 return v;
Jeremy Hylton9e392e22000-04-26 20:39:20 +0000725}
726
727static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000728instance_getattr2(register PyInstanceObject *inst, PyObject *name)
Jeremy Hylton9e392e22000-04-26 20:39:20 +0000729{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000730 register PyObject *v;
731 PyClassObject *klass;
732 descrgetfunc f;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000734 v = PyDict_GetItem(inst->in_dict, name);
735 if (v != NULL) {
736 Py_INCREF(v);
737 return v;
738 }
739 v = class_lookup(inst->in_class, name, &klass);
740 if (v != NULL) {
741 Py_INCREF(v);
742 f = TP_DESCR_GET(v->ob_type);
743 if (f != NULL) {
744 PyObject *w = f(v, (PyObject *)inst,
745 (PyObject *)(inst->in_class));
746 Py_DECREF(v);
747 v = w;
748 }
749 }
750 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000751}
752
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000753static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000754instance_getattr(register PyInstanceObject *inst, PyObject *name)
Guido van Rossume7737541994-09-05 07:31:41 +0000755{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000756 register PyObject *func, *res;
757 res = instance_getattr1(inst, name);
758 if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
759 PyObject *args;
760 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
761 return NULL;
762 PyErr_Clear();
763 args = PyTuple_Pack(2, inst, name);
764 if (args == NULL)
765 return NULL;
766 res = PyEval_CallObject(func, args);
767 Py_DECREF(args);
768 }
769 return res;
Guido van Rossume7737541994-09-05 07:31:41 +0000770}
771
Tim Petersdf875b92003-04-07 17:51:59 +0000772/* See classobject.h comments: this only does dict lookups, and is always
773 * safe to call.
774 */
775PyObject *
776_PyInstance_Lookup(PyObject *pinst, PyObject *name)
777{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000778 PyObject *v;
779 PyClassObject *klass;
780 PyInstanceObject *inst; /* pinst cast to the right type */
Tim Petersdf875b92003-04-07 17:51:59 +0000781
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000782 assert(PyInstance_Check(pinst));
783 inst = (PyInstanceObject *)pinst;
Tim Petersdf875b92003-04-07 17:51:59 +0000784
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000785 assert(PyString_Check(name));
Tim Petersdf875b92003-04-07 17:51:59 +0000786
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000787 v = PyDict_GetItem(inst->in_dict, name);
788 if (v == NULL)
789 v = class_lookup(inst->in_class, name, &klass);
790 return v;
Tim Petersdf875b92003-04-07 17:51:59 +0000791}
792
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000793static int
Fred Drake79912472000-07-09 04:06:11 +0000794instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000796 if (v == NULL) {
797 int rv = PyDict_DelItem(inst->in_dict, name);
798 if (rv < 0)
799 PyErr_Format(PyExc_AttributeError,
800 "%.50s instance has no attribute '%.400s'",
801 PyString_AS_STRING(inst->in_class->cl_name),
802 PyString_AS_STRING(name));
803 return rv;
804 }
805 else
806 return PyDict_SetItem(inst->in_dict, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000807}
808
Guido van Rossume7737541994-09-05 07:31:41 +0000809static int
Fred Drake79912472000-07-09 04:06:11 +0000810instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
Guido van Rossume7737541994-09-05 07:31:41 +0000811{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000812 PyObject *func, *args, *res, *tmp;
813 char *sname = PyString_AsString(name);
814 if (sname[0] == '_' && sname[1] == '_') {
815 Py_ssize_t n = PyString_Size(name);
816 if (sname[n-1] == '_' && sname[n-2] == '_') {
817 if (strcmp(sname, "__dict__") == 0) {
818 if (PyEval_GetRestricted()) {
819 PyErr_SetString(PyExc_RuntimeError,
820 "__dict__ not accessible in restricted mode");
821 return -1;
822 }
823 if (v == NULL || !PyDict_Check(v)) {
824 PyErr_SetString(PyExc_TypeError,
825 "__dict__ must be set to a dictionary");
826 return -1;
827 }
828 tmp = inst->in_dict;
829 Py_INCREF(v);
830 inst->in_dict = v;
831 Py_DECREF(tmp);
832 return 0;
833 }
834 if (strcmp(sname, "__class__") == 0) {
835 if (PyEval_GetRestricted()) {
836 PyErr_SetString(PyExc_RuntimeError,
837 "__class__ not accessible in restricted mode");
838 return -1;
839 }
840 if (v == NULL || !PyClass_Check(v)) {
841 PyErr_SetString(PyExc_TypeError,
842 "__class__ must be set to a class");
843 return -1;
844 }
845 tmp = (PyObject *)(inst->in_class);
846 Py_INCREF(v);
847 inst->in_class = (PyClassObject *)v;
848 Py_DECREF(tmp);
849 return 0;
850 }
851 }
852 }
853 if (v == NULL)
854 func = inst->in_class->cl_delattr;
855 else
856 func = inst->in_class->cl_setattr;
857 if (func == NULL)
858 return instance_setattr1(inst, name, v);
859 if (v == NULL)
860 args = PyTuple_Pack(2, inst, name);
861 else
862 args = PyTuple_Pack(3, inst, name, v);
863 if (args == NULL)
864 return -1;
865 res = PyEval_CallObject(func, args);
866 Py_DECREF(args);
867 if (res == NULL)
868 return -1;
869 Py_DECREF(res);
870 return 0;
Guido van Rossume7737541994-09-05 07:31:41 +0000871}
872
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000873static PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000874instance_repr(PyInstanceObject *inst)
Guido van Rossum04691fc1992-08-12 15:35:34 +0000875{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000876 PyObject *func;
877 PyObject *res;
878 static PyObject *reprstr;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000879
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000880 if (reprstr == NULL) {
881 reprstr = PyString_InternFromString("__repr__");
882 if (reprstr == NULL)
883 return NULL;
884 }
885 func = instance_getattr(inst, reprstr);
886 if (func == NULL) {
887 PyObject *classname, *mod;
888 char *cname;
889 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
890 return NULL;
891 PyErr_Clear();
892 classname = inst->in_class->cl_name;
893 mod = PyDict_GetItemString(inst->in_class->cl_dict,
894 "__module__");
895 if (classname != NULL && PyString_Check(classname))
896 cname = PyString_AsString(classname);
897 else
898 cname = "?";
899 if (mod == NULL || !PyString_Check(mod))
900 return PyString_FromFormat("<?.%s instance at %p>",
901 cname, inst);
902 else
903 return PyString_FromFormat("<%s.%s instance at %p>",
904 PyString_AsString(mod),
905 cname, inst);
906 }
907 res = PyEval_CallObject(func, (PyObject *)NULL);
908 Py_DECREF(func);
909 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000910}
911
Guido van Rossum82c690f2001-04-30 14:39:18 +0000912static PyObject *
913instance_str(PyInstanceObject *inst)
914{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000915 PyObject *func;
916 PyObject *res;
917 static PyObject *strstr;
Guido van Rossum82c690f2001-04-30 14:39:18 +0000918
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000919 if (strstr == NULL) {
920 strstr = PyString_InternFromString("__str__");
921 if (strstr == NULL)
922 return NULL;
923 }
924 func = instance_getattr(inst, strstr);
925 if (func == NULL) {
926 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
927 return NULL;
928 PyErr_Clear();
929 return instance_repr(inst);
930 }
931 res = PyEval_CallObject(func, (PyObject *)NULL);
932 Py_DECREF(func);
933 return res;
Guido van Rossum82c690f2001-04-30 14:39:18 +0000934}
935
Guido van Rossum9bfef441993-03-29 10:43:31 +0000936static long
Fred Drake79912472000-07-09 04:06:11 +0000937instance_hash(PyInstanceObject *inst)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000938{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000939 PyObject *func;
940 PyObject *res;
941 long outcome;
942 static PyObject *hashstr, *eqstr, *cmpstr;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000943
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000944 if (hashstr == NULL) {
945 hashstr = PyString_InternFromString("__hash__");
946 if (hashstr == NULL)
947 return -1;
948 }
949 func = instance_getattr(inst, hashstr);
950 if (func == NULL) {
951 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
952 return -1;
953 PyErr_Clear();
954 /* If there is no __eq__ and no __cmp__ method, we hash on the
955 address. If an __eq__ or __cmp__ method exists, there must
956 be a __hash__. */
957 if (eqstr == NULL) {
958 eqstr = PyString_InternFromString("__eq__");
959 if (eqstr == NULL)
960 return -1;
961 }
962 func = instance_getattr(inst, eqstr);
963 if (func == NULL) {
964 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
965 return -1;
966 PyErr_Clear();
967 if (cmpstr == NULL) {
968 cmpstr = PyString_InternFromString("__cmp__");
969 if (cmpstr == NULL)
970 return -1;
971 }
972 func = instance_getattr(inst, cmpstr);
973 if (func == NULL) {
974 if (!PyErr_ExceptionMatches(
975 PyExc_AttributeError))
976 return -1;
977 PyErr_Clear();
978 return _Py_HashPointer(inst);
979 }
980 }
981 Py_XDECREF(func);
982 PyErr_SetString(PyExc_TypeError, "unhashable instance");
983 return -1;
984 }
985 res = PyEval_CallObject(func, (PyObject *)NULL);
986 Py_DECREF(func);
987 if (res == NULL)
988 return -1;
989 if (PyInt_Check(res) || PyLong_Check(res))
990 /* This already converts a -1 result to -2. */
991 outcome = res->ob_type->tp_hash(res);
992 else {
993 PyErr_SetString(PyExc_TypeError,
994 "__hash__() should return an int");
995 outcome = -1;
996 }
997 Py_DECREF(res);
998 return outcome;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000999}
1000
Jeremy Hylton8caad492000-06-23 14:18:11 +00001001static int
1002instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
1003{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001004 Py_VISIT(o->in_class);
1005 Py_VISIT(o->in_dict);
1006 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00001007}
1008
Guido van Rossum213c7a62001-04-23 14:08:49 +00001009static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
1010static PyObject *iterstr, *nextstr;
Guido van Rossum2878a691996-08-09 20:53:24 +00001011
Martin v. Löwis18e16552006-02-15 17:27:45 +00001012static Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00001013instance_length(PyInstanceObject *inst)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001014{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 PyObject *func;
1016 PyObject *res;
1017 Py_ssize_t outcome;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001018
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001019 if (lenstr == NULL) {
1020 lenstr = PyString_InternFromString("__len__");
1021 if (lenstr == NULL)
1022 return -1;
1023 }
1024 func = instance_getattr(inst, lenstr);
1025 if (func == NULL)
1026 return -1;
1027 res = PyEval_CallObject(func, (PyObject *)NULL);
1028 Py_DECREF(func);
1029 if (res == NULL)
1030 return -1;
1031 if (PyInt_Check(res)) {
1032 outcome = PyInt_AsSsize_t(res);
1033 if (outcome == -1 && PyErr_Occurred()) {
1034 Py_DECREF(res);
1035 return -1;
1036 }
Neal Norwitz1872b1c2006-08-12 18:44:06 +00001037#if SIZEOF_SIZE_T < SIZEOF_INT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 /* Overflow check -- range of PyInt is more than C int */
1039 if (outcome != (int)outcome) {
1040 PyErr_SetString(PyExc_OverflowError,
1041 "__len__() should return 0 <= outcome < 2**31");
1042 outcome = -1;
1043 }
1044 else
Guido van Rossumba3e6ec2005-09-19 22:42:41 +00001045#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001046 if (outcome < 0) {
1047 PyErr_SetString(PyExc_ValueError,
1048 "__len__() should return >= 0");
1049 outcome = -1;
1050 }
1051 }
1052 else {
1053 PyErr_SetString(PyExc_TypeError,
1054 "__len__() should return an int");
1055 outcome = -1;
1056 }
1057 Py_DECREF(res);
1058 return outcome;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001059}
1060
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001061static PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001062instance_subscript(PyInstanceObject *inst, PyObject *key)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001063{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001064 PyObject *func;
1065 PyObject *arg;
1066 PyObject *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001067
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001068 if (getitemstr == NULL) {
1069 getitemstr = PyString_InternFromString("__getitem__");
1070 if (getitemstr == NULL)
1071 return NULL;
1072 }
1073 func = instance_getattr(inst, getitemstr);
1074 if (func == NULL)
1075 return NULL;
1076 arg = PyTuple_Pack(1, key);
1077 if (arg == NULL) {
1078 Py_DECREF(func);
1079 return NULL;
1080 }
1081 res = PyEval_CallObject(func, arg);
1082 Py_DECREF(func);
1083 Py_DECREF(arg);
1084 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001085}
1086
Guido van Rossum9bfef441993-03-29 10:43:31 +00001087static int
Fred Drake79912472000-07-09 04:06:11 +00001088instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001089{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001090 PyObject *func;
1091 PyObject *arg;
1092 PyObject *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001094 if (value == NULL) {
1095 if (delitemstr == NULL) {
1096 delitemstr = PyString_InternFromString("__delitem__");
1097 if (delitemstr == NULL)
1098 return -1;
1099 }
1100 func = instance_getattr(inst, delitemstr);
1101 }
1102 else {
1103 if (setitemstr == NULL) {
1104 setitemstr = PyString_InternFromString("__setitem__");
1105 if (setitemstr == NULL)
1106 return -1;
1107 }
1108 func = instance_getattr(inst, setitemstr);
1109 }
1110 if (func == NULL)
1111 return -1;
1112 if (value == NULL)
1113 arg = PyTuple_Pack(1, key);
1114 else
1115 arg = PyTuple_Pack(2, key, value);
1116 if (arg == NULL) {
1117 Py_DECREF(func);
1118 return -1;
1119 }
1120 res = PyEval_CallObject(func, arg);
1121 Py_DECREF(func);
1122 Py_DECREF(arg);
1123 if (res == NULL)
1124 return -1;
1125 Py_DECREF(res);
1126 return 0;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001127}
1128
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001129static PyMappingMethods instance_as_mapping = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001130 (lenfunc)instance_length, /* mp_length */
1131 (binaryfunc)instance_subscript, /* mp_subscript */
1132 (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
Guido van Rossum04691fc1992-08-12 15:35:34 +00001133};
1134
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001135static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001136instance_item(PyInstanceObject *inst, Py_ssize_t i)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001137{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001138 PyObject *func, *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001139
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001140 if (getitemstr == NULL) {
1141 getitemstr = PyString_InternFromString("__getitem__");
1142 if (getitemstr == NULL)
1143 return NULL;
1144 }
1145 func = instance_getattr(inst, getitemstr);
1146 if (func == NULL)
1147 return NULL;
1148 res = PyObject_CallFunction(func, "n", i);
1149 Py_DECREF(func);
1150 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001151}
1152
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001153static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001154instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001155{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001156 PyObject *func, *arg, *res;
1157 static PyObject *getslicestr;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001158
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001159 if (getslicestr == NULL) {
1160 getslicestr = PyString_InternFromString("__getslice__");
1161 if (getslicestr == NULL)
1162 return NULL;
1163 }
1164 func = instance_getattr(inst, getslicestr);
Thomas Wouters1d75a792000-08-17 22:37:32 +00001165
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001166 if (func == NULL) {
1167 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1168 return NULL;
1169 PyErr_Clear();
Thomas Wouters1d75a792000-08-17 22:37:32 +00001170
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001171 if (getitemstr == NULL) {
1172 getitemstr = PyString_InternFromString("__getitem__");
1173 if (getitemstr == NULL)
1174 return NULL;
1175 }
1176 func = instance_getattr(inst, getitemstr);
1177 if (func == NULL)
1178 return NULL;
1179 arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
1180 }
1181 else {
1182 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
1183 "use __getitem__", 1) < 0) {
1184 Py_DECREF(func);
1185 return NULL;
1186 }
1187 arg = Py_BuildValue("(nn)", i, j);
1188 }
Tim Peters34592512002-07-11 06:23:50 +00001189
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001190 if (arg == NULL) {
1191 Py_DECREF(func);
1192 return NULL;
1193 }
1194 res = PyEval_CallObject(func, arg);
1195 Py_DECREF(func);
1196 Py_DECREF(arg);
1197 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001198}
1199
1200static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001201instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001202{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001203 PyObject *func, *arg, *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001204
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001205 if (item == NULL) {
1206 if (delitemstr == NULL) {
1207 delitemstr = PyString_InternFromString("__delitem__");
1208 if (delitemstr == NULL)
1209 return -1;
1210 }
1211 func = instance_getattr(inst, delitemstr);
1212 }
1213 else {
1214 if (setitemstr == NULL) {
1215 setitemstr = PyString_InternFromString("__setitem__");
1216 if (setitemstr == NULL)
1217 return -1;
1218 }
1219 func = instance_getattr(inst, setitemstr);
1220 }
1221 if (func == NULL)
1222 return -1;
1223 if (item == NULL)
1224 arg = PyInt_FromSsize_t(i);
1225 else
1226 arg = Py_BuildValue("(nO)", i, item);
1227 if (arg == NULL) {
1228 Py_DECREF(func);
1229 return -1;
1230 }
1231 res = PyEval_CallObject(func, arg);
1232 Py_DECREF(func);
1233 Py_DECREF(arg);
1234 if (res == NULL)
1235 return -1;
1236 Py_DECREF(res);
1237 return 0;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001238}
1239
1240static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001241instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001242{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001243 PyObject *func, *arg, *res;
1244 static PyObject *setslicestr, *delslicestr;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001245
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001246 if (value == NULL) {
1247 if (delslicestr == NULL) {
1248 delslicestr =
1249 PyString_InternFromString("__delslice__");
1250 if (delslicestr == NULL)
1251 return -1;
1252 }
1253 func = instance_getattr(inst, delslicestr);
1254 if (func == NULL) {
1255 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1256 return -1;
1257 PyErr_Clear();
1258 if (delitemstr == NULL) {
1259 delitemstr =
1260 PyString_InternFromString("__delitem__");
1261 if (delitemstr == NULL)
1262 return -1;
1263 }
1264 func = instance_getattr(inst, delitemstr);
1265 if (func == NULL)
1266 return -1;
Thomas Wouters1d75a792000-08-17 22:37:32 +00001267
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001268 arg = Py_BuildValue("(N)",
1269 _PySlice_FromIndices(i, j));
1270 }
1271 else {
1272 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
1273 "removed; use __delitem__", 1) < 0) {
1274 Py_DECREF(func);
1275 return -1;
1276 }
1277 arg = Py_BuildValue("(nn)", i, j);
1278 }
1279 }
1280 else {
1281 if (setslicestr == NULL) {
1282 setslicestr =
1283 PyString_InternFromString("__setslice__");
1284 if (setslicestr == NULL)
1285 return -1;
1286 }
1287 func = instance_getattr(inst, setslicestr);
1288 if (func == NULL) {
1289 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1290 return -1;
1291 PyErr_Clear();
1292 if (setitemstr == NULL) {
1293 setitemstr =
1294 PyString_InternFromString("__setitem__");
1295 if (setitemstr == NULL)
1296 return -1;
1297 }
1298 func = instance_getattr(inst, setitemstr);
1299 if (func == NULL)
1300 return -1;
Thomas Wouters1d75a792000-08-17 22:37:32 +00001301
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001302 arg = Py_BuildValue("(NO)",
1303 _PySlice_FromIndices(i, j), value);
1304 }
1305 else {
1306 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
1307 "removed; use __setitem__", 1) < 0) {
1308 Py_DECREF(func);
1309 return -1;
1310 }
1311 arg = Py_BuildValue("(nnO)", i, j, value);
1312 }
1313 }
1314 if (arg == NULL) {
1315 Py_DECREF(func);
1316 return -1;
1317 }
1318 res = PyEval_CallObject(func, arg);
1319 Py_DECREF(func);
1320 Py_DECREF(arg);
1321 if (res == NULL)
1322 return -1;
1323 Py_DECREF(res);
1324 return 0;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001325}
1326
Tim Peterscb8d3682001-05-05 21:05:01 +00001327static int
1328instance_contains(PyInstanceObject *inst, PyObject *member)
Guido van Rossumee28c3a2000-02-28 15:03:15 +00001329{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001330 static PyObject *__contains__;
1331 PyObject *func;
Tim Peterscb8d3682001-05-05 21:05:01 +00001332
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001333 /* Try __contains__ first.
1334 * If that can't be done, try iterator-based searching.
1335 */
Guido van Rossumee28c3a2000-02-28 15:03:15 +00001336
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001337 if(__contains__ == NULL) {
1338 __contains__ = PyString_InternFromString("__contains__");
1339 if(__contains__ == NULL)
1340 return -1;
1341 }
1342 func = instance_getattr(inst, __contains__);
1343 if (func) {
1344 PyObject *res;
1345 int ret;
1346 PyObject *arg = PyTuple_Pack(1, member);
1347 if(arg == NULL) {
1348 Py_DECREF(func);
1349 return -1;
1350 }
1351 res = PyEval_CallObject(func, arg);
1352 Py_DECREF(func);
1353 Py_DECREF(arg);
1354 if(res == NULL)
1355 return -1;
1356 ret = PyObject_IsTrue(res);
1357 Py_DECREF(res);
1358 return ret;
1359 }
Tim Peterscb8d3682001-05-05 21:05:01 +00001360
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001361 /* Couldn't find __contains__. */
1362 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1363 Py_ssize_t rc;
1364 /* Assume the failure was simply due to that there is no
1365 * __contains__ attribute, and try iterating instead.
1366 */
1367 PyErr_Clear();
1368 rc = _PySequence_IterSearch((PyObject *)inst, member,
1369 PY_ITERSEARCH_CONTAINS);
1370 if (rc >= 0)
1371 return rc > 0;
1372 }
1373 return -1;
Guido van Rossumee28c3a2000-02-28 15:03:15 +00001374}
1375
Fred Drake79912472000-07-09 04:06:11 +00001376static PySequenceMethods
1377instance_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001378 (lenfunc)instance_length, /* sq_length */
1379 0, /* sq_concat */
1380 0, /* sq_repeat */
1381 (ssizeargfunc)instance_item, /* sq_item */
1382 (ssizessizeargfunc)instance_slice, /* sq_slice */
1383 (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
1384 (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1385 (objobjproc)instance_contains, /* sq_contains */
Guido van Rossum04691fc1992-08-12 15:35:34 +00001386};
1387
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001388static PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001389generic_unary_op(PyInstanceObject *self, PyObject *methodname)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001390{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001391 PyObject *func, *res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001392
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001393 if ((func = instance_getattr(self, methodname)) == NULL)
1394 return NULL;
1395 res = PyEval_CallObject(func, (PyObject *)NULL);
1396 Py_DECREF(func);
1397 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001398}
1399
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001400static PyObject *
1401generic_binary_op(PyObject *v, PyObject *w, char *opname)
Guido van Rossum03093a21994-09-28 15:51:32 +00001402{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001403 PyObject *result;
1404 PyObject *args;
1405 PyObject *func = PyObject_GetAttrString(v, opname);
1406 if (func == NULL) {
1407 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1408 return NULL;
1409 PyErr_Clear();
1410 Py_INCREF(Py_NotImplemented);
1411 return Py_NotImplemented;
1412 }
1413 args = PyTuple_Pack(1, w);
1414 if (args == NULL) {
1415 Py_DECREF(func);
1416 return NULL;
1417 }
1418 result = PyEval_CallObject(func, args);
1419 Py_DECREF(args);
1420 Py_DECREF(func);
1421 return result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001422}
1423
1424
1425static PyObject *coerce_obj;
1426
1427/* Try one half of a binary operator involving a class instance. */
1428static PyObject *
Tim Peters34592512002-07-11 06:23:50 +00001429half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001430 int swapped)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001431{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001432 PyObject *args;
1433 PyObject *coercefunc;
1434 PyObject *coerced = NULL;
1435 PyObject *v1;
1436 PyObject *result;
Tim Peters34592512002-07-11 06:23:50 +00001437
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001438 if (!PyInstance_Check(v)) {
1439 Py_INCREF(Py_NotImplemented);
1440 return Py_NotImplemented;
1441 }
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001442
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 if (coerce_obj == NULL) {
1444 coerce_obj = PyString_InternFromString("__coerce__");
1445 if (coerce_obj == NULL)
1446 return NULL;
1447 }
1448 coercefunc = PyObject_GetAttr(v, coerce_obj);
1449 if (coercefunc == NULL) {
1450 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1451 return NULL;
1452 PyErr_Clear();
1453 return generic_binary_op(v, w, opname);
1454 }
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001455
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001456 args = PyTuple_Pack(1, w);
1457 if (args == NULL) {
1458 Py_DECREF(coercefunc);
1459 return NULL;
1460 }
1461 coerced = PyEval_CallObject(coercefunc, args);
1462 Py_DECREF(args);
1463 Py_DECREF(coercefunc);
1464 if (coerced == NULL) {
1465 return NULL;
1466 }
1467 if (coerced == Py_None || coerced == Py_NotImplemented) {
1468 Py_DECREF(coerced);
1469 return generic_binary_op(v, w, opname);
1470 }
1471 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1472 Py_DECREF(coerced);
1473 PyErr_SetString(PyExc_TypeError,
1474 "coercion should return None or 2-tuple");
1475 return NULL;
1476 }
1477 v1 = PyTuple_GetItem(coerced, 0);
1478 w = PyTuple_GetItem(coerced, 1);
1479 if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1480 /* prevent recursion if __coerce__ returns self as the first
1481 * argument */
1482 result = generic_binary_op(v1, w, opname);
1483 } else {
1484 if (Py_EnterRecursiveCall(" after coercion"))
1485 return NULL;
1486 if (swapped)
1487 result = (thisfunc)(w, v1);
1488 else
1489 result = (thisfunc)(v1, w);
1490 Py_LeaveRecursiveCall();
1491 }
1492 Py_DECREF(coerced);
1493 return result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001494}
1495
1496/* Implement a binary operator involving at least one class instance. */
1497static PyObject *
1498do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1499 binaryfunc thisfunc)
1500{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001501 PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1502 if (result == Py_NotImplemented) {
1503 Py_DECREF(result);
1504 result = half_binop(w, v, ropname, thisfunc, 1);
1505 }
1506 return result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001507}
1508
1509static PyObject *
1510do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001511 char *ropname, binaryfunc thisfunc)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001512{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001513 PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1514 if (result == Py_NotImplemented) {
1515 Py_DECREF(result);
1516 result = do_binop(v, w, opname, ropname, thisfunc);
1517 }
1518 return result;
Guido van Rossum03093a21994-09-28 15:51:32 +00001519}
1520
Guido van Rossum879c5811995-01-10 15:24:06 +00001521static int
Fred Drake79912472000-07-09 04:06:11 +00001522instance_coerce(PyObject **pv, PyObject **pw)
Guido van Rossum879c5811995-01-10 15:24:06 +00001523{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001524 PyObject *v = *pv;
1525 PyObject *w = *pw;
1526 PyObject *coercefunc;
1527 PyObject *args;
1528 PyObject *coerced;
Guido van Rossum879c5811995-01-10 15:24:06 +00001529
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001530 if (coerce_obj == NULL) {
1531 coerce_obj = PyString_InternFromString("__coerce__");
1532 if (coerce_obj == NULL)
1533 return -1;
1534 }
1535 coercefunc = PyObject_GetAttr(v, coerce_obj);
1536 if (coercefunc == NULL) {
1537 /* No __coerce__ method */
1538 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1539 return -1;
1540 PyErr_Clear();
1541 return 1;
1542 }
1543 /* Has __coerce__ method: call it */
1544 args = PyTuple_Pack(1, w);
1545 if (args == NULL) {
1546 return -1;
1547 }
1548 coerced = PyEval_CallObject(coercefunc, args);
1549 Py_DECREF(args);
1550 Py_DECREF(coercefunc);
1551 if (coerced == NULL) {
1552 /* __coerce__ call raised an exception */
1553 return -1;
1554 }
1555 if (coerced == Py_None || coerced == Py_NotImplemented) {
1556 /* __coerce__ says "I can't do it" */
1557 Py_DECREF(coerced);
1558 return 1;
1559 }
1560 if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1561 /* __coerce__ return value is malformed */
1562 Py_DECREF(coerced);
1563 PyErr_SetString(PyExc_TypeError,
1564 "coercion should return None or 2-tuple");
1565 return -1;
1566 }
1567 /* __coerce__ returned two new values */
1568 *pv = PyTuple_GetItem(coerced, 0);
1569 *pw = PyTuple_GetItem(coerced, 1);
1570 Py_INCREF(*pv);
1571 Py_INCREF(*pw);
1572 Py_DECREF(coerced);
1573 return 0;
Guido van Rossum879c5811995-01-10 15:24:06 +00001574}
1575
Guido van Rossum04691fc1992-08-12 15:35:34 +00001576#define UNARY(funcname, methodname) \
Thomas Woutersc3073522000-07-23 22:09:59 +00001577static PyObject *funcname(PyInstanceObject *self) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001578 static PyObject *o; \
1579 if (o == NULL) { o = PyString_InternFromString(methodname); \
1580 if (o == NULL) return NULL; } \
1581 return generic_unary_op(self, o); \
Guido van Rossum04691fc1992-08-12 15:35:34 +00001582}
1583
Kristján Valur Jónssonabe1d482007-05-07 16:46:54 +00001584/* unary function with a fallback */
1585#define UNARY_FB(funcname, methodname, funcname_fb) \
1586static PyObject *funcname(PyInstanceObject *self) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001587 static PyObject *o; \
1588 if (o == NULL) { o = PyString_InternFromString(methodname); \
1589 if (o == NULL) return NULL; } \
1590 if (PyObject_HasAttr((PyObject*)self, o)) \
1591 return generic_unary_op(self, o); \
1592 else \
1593 return funcname_fb(self); \
Kristján Valur Jónssonabe1d482007-05-07 16:46:54 +00001594}
1595
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001596#define BINARY(f, m, n) \
1597static PyObject *f(PyObject *v, PyObject *w) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001598 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001599}
1600
1601#define BINARY_INPLACE(f, m, n) \
1602static PyObject *f(PyObject *v, PyObject *w) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001603 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1604 "__r" m "__", n); \
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001605}
1606
Guido van Rossum04691fc1992-08-12 15:35:34 +00001607UNARY(instance_neg, "__neg__")
1608UNARY(instance_pos, "__pos__")
1609UNARY(instance_abs, "__abs__")
1610
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001611BINARY(instance_or, "or", PyNumber_Or)
1612BINARY(instance_and, "and", PyNumber_And)
1613BINARY(instance_xor, "xor", PyNumber_Xor)
1614BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1615BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1616BINARY(instance_add, "add", PyNumber_Add)
1617BINARY(instance_sub, "sub", PyNumber_Subtract)
1618BINARY(instance_mul, "mul", PyNumber_Multiply)
1619BINARY(instance_div, "div", PyNumber_Divide)
1620BINARY(instance_mod, "mod", PyNumber_Remainder)
1621BINARY(instance_divmod, "divmod", PyNumber_Divmod)
Guido van Rossum4668b002001-08-08 05:00:18 +00001622BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1623BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001624
1625BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1626BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1627BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1628BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1629BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1630BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1631BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1632BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1633BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1634BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
Guido van Rossum4668b002001-08-08 05:00:18 +00001635BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1636BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001637
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001638/* Try a 3-way comparison, returning an int; v is an instance. Return:
1639 -2 for an exception;
1640 -1 if v < w;
1641 0 if v == w;
1642 1 if v > w;
1643 2 if this particular 3-way comparison is not implemented or undefined.
1644*/
1645static int
1646half_cmp(PyObject *v, PyObject *w)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001647{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001648 static PyObject *cmp_obj;
1649 PyObject *args;
1650 PyObject *cmp_func;
1651 PyObject *result;
1652 long l;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001653
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001654 assert(PyInstance_Check(v));
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001655
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001656 if (cmp_obj == NULL) {
1657 cmp_obj = PyString_InternFromString("__cmp__");
1658 if (cmp_obj == NULL)
1659 return -2;
1660 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001662 cmp_func = PyObject_GetAttr(v, cmp_obj);
1663 if (cmp_func == NULL) {
1664 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1665 return -2;
1666 PyErr_Clear();
1667 return 2;
1668 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001669
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001670 args = PyTuple_Pack(1, w);
1671 if (args == NULL) {
1672 Py_DECREF(cmp_func);
1673 return -2;
1674 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001675
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001676 result = PyEval_CallObject(cmp_func, args);
1677 Py_DECREF(args);
1678 Py_DECREF(cmp_func);
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001679
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001680 if (result == NULL)
1681 return -2;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001682
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001683 if (result == Py_NotImplemented) {
1684 Py_DECREF(result);
1685 return 2;
1686 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001687
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001688 l = PyInt_AsLong(result);
1689 Py_DECREF(result);
1690 if (l == -1 && PyErr_Occurred()) {
1691 PyErr_SetString(PyExc_TypeError,
1692 "comparison did not return an int");
1693 return -2;
1694 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001695
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001696 return l < 0 ? -1 : l > 0 ? 1 : 0;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001697}
1698
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001699/* Try a 3-way comparison, returning an int; either v or w is an instance.
1700 We first try a coercion. Return:
1701 -2 for an exception;
1702 -1 if v < w;
1703 0 if v == w;
1704 1 if v > w;
1705 2 if this particular 3-way comparison is not implemented or undefined.
1706 THIS IS ONLY CALLED FROM object.c!
1707*/
1708static int
1709instance_compare(PyObject *v, PyObject *w)
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001710{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001711 int c;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001712
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001713 c = PyNumber_CoerceEx(&v, &w);
1714 if (c < 0)
1715 return -2;
1716 if (c == 0) {
1717 /* If neither is now an instance, use regular comparison */
1718 if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1719 c = PyObject_Compare(v, w);
1720 Py_DECREF(v);
1721 Py_DECREF(w);
1722 if (PyErr_Occurred())
1723 return -2;
1724 return c < 0 ? -1 : c > 0 ? 1 : 0;
1725 }
1726 }
1727 else {
1728 /* The coercion didn't do anything.
1729 Treat this the same as returning v and w unchanged. */
1730 Py_INCREF(v);
1731 Py_INCREF(w);
1732 }
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001733
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001734 if (PyInstance_Check(v)) {
1735 c = half_cmp(v, w);
1736 if (c <= 1) {
1737 Py_DECREF(v);
1738 Py_DECREF(w);
1739 return c;
1740 }
1741 }
1742 if (PyInstance_Check(w)) {
1743 c = half_cmp(w, v);
1744 if (c <= 1) {
1745 Py_DECREF(v);
1746 Py_DECREF(w);
1747 if (c >= -1)
1748 c = -c;
1749 return c;
1750 }
1751 }
1752 Py_DECREF(v);
1753 Py_DECREF(w);
1754 return 2;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001755}
1756
Guido van Rossum9bfef441993-03-29 10:43:31 +00001757static int
Fred Drake79912472000-07-09 04:06:11 +00001758instance_nonzero(PyInstanceObject *self)
Guido van Rossum04691fc1992-08-12 15:35:34 +00001759{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001760 PyObject *func, *res;
1761 long outcome;
1762 static PyObject *nonzerostr;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001763
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001764 if (nonzerostr == NULL) {
1765 nonzerostr = PyString_InternFromString("__nonzero__");
1766 if (nonzerostr == NULL)
1767 return -1;
1768 }
1769 if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1770 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1771 return -1;
1772 PyErr_Clear();
1773 if (lenstr == NULL) {
1774 lenstr = PyString_InternFromString("__len__");
1775 if (lenstr == NULL)
1776 return -1;
1777 }
1778 if ((func = instance_getattr(self, lenstr)) == NULL) {
1779 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1780 return -1;
1781 PyErr_Clear();
1782 /* Fall back to the default behavior:
1783 all instances are nonzero */
1784 return 1;
1785 }
1786 }
1787 res = PyEval_CallObject(func, (PyObject *)NULL);
1788 Py_DECREF(func);
1789 if (res == NULL)
1790 return -1;
1791 if (!PyInt_Check(res)) {
1792 Py_DECREF(res);
1793 PyErr_SetString(PyExc_TypeError,
1794 "__nonzero__ should return an int");
1795 return -1;
1796 }
1797 outcome = PyInt_AsLong(res);
1798 Py_DECREF(res);
1799 if (outcome < 0) {
1800 PyErr_SetString(PyExc_ValueError,
1801 "__nonzero__ should return >= 0");
1802 return -1;
1803 }
1804 return outcome > 0;
Guido van Rossum04691fc1992-08-12 15:35:34 +00001805}
1806
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001807static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001808instance_index(PyInstanceObject *self)
1809{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001810 PyObject *func, *res;
1811 static PyObject *indexstr = NULL;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001812
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001813 if (indexstr == NULL) {
1814 indexstr = PyString_InternFromString("__index__");
1815 if (indexstr == NULL)
1816 return NULL;
1817 }
1818 if ((func = instance_getattr(self, indexstr)) == NULL) {
1819 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1820 return NULL;
1821 PyErr_Clear();
1822 PyErr_SetString(PyExc_TypeError,
1823 "object cannot be interpreted as an index");
1824 return NULL;
1825 }
1826 res = PyEval_CallObject(func, (PyObject *)NULL);
1827 Py_DECREF(func);
1828 return res;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001829}
1830
1831
Guido van Rossum04691fc1992-08-12 15:35:34 +00001832UNARY(instance_invert, "__invert__")
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001833UNARY(_instance_trunc, "__trunc__")
1834
1835static PyObject *
1836instance_int(PyInstanceObject *self)
1837{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001838 PyObject *truncated;
1839 static PyObject *int_name;
1840 if (int_name == NULL) {
1841 int_name = PyString_InternFromString("__int__");
1842 if (int_name == NULL)
1843 return NULL;
1844 }
1845 if (PyObject_HasAttr((PyObject*)self, int_name))
1846 return generic_unary_op(self, int_name);
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001847
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001848 truncated = _instance_trunc(self);
1849 /* __trunc__ is specified to return an Integral type, but
1850 int() needs to return an int. */
1851 return _PyNumber_ConvertIntegralToInt(
1852 truncated,
1853 "__trunc__ returned non-Integral (type %.200s)");
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001854}
1855
Kristján Valur Jónssonabe1d482007-05-07 16:46:54 +00001856UNARY_FB(instance_long, "__long__", instance_int)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001857UNARY(instance_float, "__float__")
1858UNARY(instance_oct, "__oct__")
1859UNARY(instance_hex, "__hex__")
1860
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001861static PyObject *
1862bin_power(PyObject *v, PyObject *w)
1863{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001864 return PyNumber_Power(v, w, Py_None);
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001865}
1866
Guido van Rossum03093a21994-09-28 15:51:32 +00001867/* This version is for ternary calls only (z != None) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001868static PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001869instance_pow(PyObject *v, PyObject *w, PyObject *z)
Tim Peters34592512002-07-11 06:23:50 +00001870{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001871 if (z == Py_None) {
1872 return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1873 }
1874 else {
1875 PyObject *func;
1876 PyObject *args;
1877 PyObject *result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001878
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001879 /* XXX Doesn't do coercions... */
1880 func = PyObject_GetAttrString(v, "__pow__");
1881 if (func == NULL)
1882 return NULL;
1883 args = PyTuple_Pack(2, w, z);
1884 if (args == NULL) {
1885 Py_DECREF(func);
1886 return NULL;
1887 }
1888 result = PyEval_CallObject(func, args);
1889 Py_DECREF(func);
1890 Py_DECREF(args);
1891 return result;
1892 }
Guido van Rossum03093a21994-09-28 15:51:32 +00001893}
1894
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001895static PyObject *
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001896bin_inplace_power(PyObject *v, PyObject *w)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001897{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001898 return PyNumber_InPlacePower(v, w, Py_None);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001899}
1900
1901
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001902static PyObject *
1903instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1904{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001905 if (z == Py_None) {
1906 return do_binop_inplace(v, w, "__ipow__", "__pow__",
1907 "__rpow__", bin_inplace_power);
1908 }
1909 else {
1910 /* XXX Doesn't do coercions... */
1911 PyObject *func;
1912 PyObject *args;
1913 PyObject *result;
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001914
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001915 func = PyObject_GetAttrString(v, "__ipow__");
1916 if (func == NULL) {
1917 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1918 return NULL;
1919 PyErr_Clear();
1920 return instance_pow(v, w, z);
1921 }
1922 args = PyTuple_Pack(2, w, z);
1923 if (args == NULL) {
1924 Py_DECREF(func);
1925 return NULL;
1926 }
1927 result = PyEval_CallObject(func, args);
1928 Py_DECREF(func);
1929 Py_DECREF(args);
1930 return result;
1931 }
Neil Schemenauer29bfc072001-01-04 01:43:46 +00001932}
1933
1934
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001935/* Map rich comparison operators to their __xx__ namesakes */
Jeremy Hylton1b0feb42001-05-11 14:48:41 +00001936#define NAME_OPS 6
1937static PyObject **name_op = NULL;
1938
Tim Peters34592512002-07-11 06:23:50 +00001939static int
Guido van Rossum0ba9e3a2001-05-22 02:33:08 +00001940init_name_op(void)
Jeremy Hylton1b0feb42001-05-11 14:48:41 +00001941{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001942 int i;
1943 char *_name_op[] = {
1944 "__lt__",
1945 "__le__",
1946 "__eq__",
1947 "__ne__",
1948 "__gt__",
1949 "__ge__",
1950 };
Jeremy Hylton1b0feb42001-05-11 14:48:41 +00001951
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001952 name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1953 if (name_op == NULL)
1954 return -1;
1955 for (i = 0; i < NAME_OPS; ++i) {
1956 name_op[i] = PyString_InternFromString(_name_op[i]);
1957 if (name_op[i] == NULL)
1958 return -1;
1959 }
1960 return 0;
Jeremy Hylton1b0feb42001-05-11 14:48:41 +00001961}
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001962
1963static PyObject *
1964half_richcompare(PyObject *v, PyObject *w, int op)
1965{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001966 PyObject *method;
1967 PyObject *args;
1968 PyObject *res;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001969
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001970 assert(PyInstance_Check(v));
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001971
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001972 if (name_op == NULL) {
1973 if (init_name_op() < 0)
1974 return NULL;
1975 }
1976 /* If the instance doesn't define an __getattr__ method, use
1977 instance_getattr2 directly because it will not set an
1978 exception on failure. */
1979 if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1980 method = instance_getattr2((PyInstanceObject *)v,
1981 name_op[op]);
1982 else
1983 method = PyObject_GetAttr(v, name_op[op]);
1984 if (method == NULL) {
1985 if (PyErr_Occurred()) {
1986 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1987 return NULL;
1988 PyErr_Clear();
1989 }
1990 res = Py_NotImplemented;
1991 Py_INCREF(res);
1992 return res;
1993 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00001994
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001995 args = PyTuple_Pack(1, w);
1996 if (args == NULL) {
1997 Py_DECREF(method);
1998 return NULL;
1999 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002001 res = PyEval_CallObject(method, args);
2002 Py_DECREF(args);
2003 Py_DECREF(method);
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002005 return res;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002006}
2007
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002008static PyObject *
2009instance_richcompare(PyObject *v, PyObject *w, int op)
2010{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002011 PyObject *res;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002012
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002013 if (PyInstance_Check(v)) {
2014 res = half_richcompare(v, w, op);
2015 if (res != Py_NotImplemented)
2016 return res;
2017 Py_DECREF(res);
2018 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002019
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002020 if (PyInstance_Check(w)) {
2021 res = half_richcompare(w, v, _Py_SwappedOp[op]);
2022 if (res != Py_NotImplemented)
2023 return res;
2024 Py_DECREF(res);
2025 }
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002027 Py_INCREF(Py_NotImplemented);
2028 return Py_NotImplemented;
Guido van Rossum8998b4f2001-01-17 15:28:20 +00002029}
2030
Neil Schemenauer29bfc072001-01-04 01:43:46 +00002031
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002032/* Get the iterator */
2033static PyObject *
2034instance_getiter(PyInstanceObject *self)
2035{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002036 PyObject *func;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002037
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002038 if (iterstr == NULL) {
2039 iterstr = PyString_InternFromString("__iter__");
2040 if (iterstr == NULL)
2041 return NULL;
2042 }
2043 if (getitemstr == NULL) {
2044 getitemstr = PyString_InternFromString("__getitem__");
2045 if (getitemstr == NULL)
2046 return NULL;
2047 }
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002048
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002049 if ((func = instance_getattr(self, iterstr)) != NULL) {
2050 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2051 Py_DECREF(func);
2052 if (res != NULL && !PyIter_Check(res)) {
2053 PyErr_Format(PyExc_TypeError,
2054 "__iter__ returned non-iterator "
2055 "of type '%.100s'",
2056 res->ob_type->tp_name);
2057 Py_DECREF(res);
2058 res = NULL;
2059 }
2060 return res;
2061 }
2062 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2063 return NULL;
2064 PyErr_Clear();
2065 if ((func = instance_getattr(self, getitemstr)) == NULL) {
2066 PyErr_SetString(PyExc_TypeError,
2067 "iteration over non-sequence");
2068 return NULL;
2069 }
2070 Py_DECREF(func);
2071 return PySeqIter_New((PyObject *)self);
Guido van Rossum213c7a62001-04-23 14:08:49 +00002072}
2073
2074
2075/* Call the iterator's next */
2076static PyObject *
2077instance_iternext(PyInstanceObject *self)
2078{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002079 PyObject *func;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002080
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002081 if (nextstr == NULL) {
2082 nextstr = PyString_InternFromString("next");
2083 if (nextstr == NULL)
2084 return NULL;
2085 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00002086
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002087 if ((func = instance_getattr(self, nextstr)) != NULL) {
2088 PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2089 Py_DECREF(func);
2090 if (res != NULL) {
2091 return res;
2092 }
2093 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
2094 PyErr_Clear();
2095 return NULL;
2096 }
2097 return NULL;
2098 }
2099 PyErr_SetString(PyExc_TypeError, "instance has no next() method");
2100 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002101}
2102
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103static PyObject *
2104instance_call(PyObject *func, PyObject *arg, PyObject *kw)
2105{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002106 PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
2107 if (call == NULL) {
2108 PyInstanceObject *inst = (PyInstanceObject*) func;
2109 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2110 return NULL;
2111 PyErr_Clear();
2112 PyErr_Format(PyExc_AttributeError,
2113 "%.200s instance has no __call__ method",
2114 PyString_AsString(inst->in_class->cl_name));
2115 return NULL;
2116 }
2117 /* We must check and increment the recursion depth here. Scenario:
2118 class A:
2119 pass
2120 A.__call__ = A() # that's right
2121 a = A() # ok
2122 a() # infinite recursion
2123 This bounces between instance_call() and PyObject_Call() without
2124 ever hitting eval_frame() (which has the main recursion check). */
2125 if (Py_EnterRecursiveCall(" in __call__")) {
2126 res = NULL;
2127 }
2128 else {
2129 res = PyObject_Call(call, arg, kw);
2130 Py_LeaveRecursiveCall();
2131 }
2132 Py_DECREF(call);
2133 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002134}
2135
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002136
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002137static PyNumberMethods instance_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002138 instance_add, /* nb_add */
2139 instance_sub, /* nb_subtract */
2140 instance_mul, /* nb_multiply */
2141 instance_div, /* nb_divide */
2142 instance_mod, /* nb_remainder */
2143 instance_divmod, /* nb_divmod */
2144 instance_pow, /* nb_power */
2145 (unaryfunc)instance_neg, /* nb_negative */
2146 (unaryfunc)instance_pos, /* nb_positive */
2147 (unaryfunc)instance_abs, /* nb_absolute */
2148 (inquiry)instance_nonzero, /* nb_nonzero */
2149 (unaryfunc)instance_invert, /* nb_invert */
2150 instance_lshift, /* nb_lshift */
2151 instance_rshift, /* nb_rshift */
2152 instance_and, /* nb_and */
2153 instance_xor, /* nb_xor */
2154 instance_or, /* nb_or */
2155 instance_coerce, /* nb_coerce */
2156 (unaryfunc)instance_int, /* nb_int */
2157 (unaryfunc)instance_long, /* nb_long */
2158 (unaryfunc)instance_float, /* nb_float */
2159 (unaryfunc)instance_oct, /* nb_oct */
2160 (unaryfunc)instance_hex, /* nb_hex */
2161 instance_iadd, /* nb_inplace_add */
2162 instance_isub, /* nb_inplace_subtract */
2163 instance_imul, /* nb_inplace_multiply */
2164 instance_idiv, /* nb_inplace_divide */
2165 instance_imod, /* nb_inplace_remainder */
2166 instance_ipow, /* nb_inplace_power */
2167 instance_ilshift, /* nb_inplace_lshift */
2168 instance_irshift, /* nb_inplace_rshift */
2169 instance_iand, /* nb_inplace_and */
2170 instance_ixor, /* nb_inplace_xor */
2171 instance_ior, /* nb_inplace_or */
2172 instance_floordiv, /* nb_floor_divide */
2173 instance_truediv, /* nb_true_divide */
2174 instance_ifloordiv, /* nb_inplace_floor_divide */
2175 instance_itruediv, /* nb_inplace_true_divide */
2176 (unaryfunc)instance_index, /* nb_index */
Guido van Rossum04691fc1992-08-12 15:35:34 +00002177};
2178
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002179PyTypeObject PyInstance_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002180 PyObject_HEAD_INIT(&PyType_Type)
2181 0,
2182 "instance",
2183 sizeof(PyInstanceObject),
2184 0,
2185 (destructor)instance_dealloc, /* tp_dealloc */
2186 0, /* tp_print */
2187 0, /* tp_getattr */
2188 0, /* tp_setattr */
2189 instance_compare, /* tp_compare */
2190 (reprfunc)instance_repr, /* tp_repr */
2191 &instance_as_number, /* tp_as_number */
2192 &instance_as_sequence, /* tp_as_sequence */
2193 &instance_as_mapping, /* tp_as_mapping */
2194 (hashfunc)instance_hash, /* tp_hash */
2195 instance_call, /* tp_call */
2196 (reprfunc)instance_str, /* tp_str */
2197 (getattrofunc)instance_getattr, /* tp_getattro */
2198 (setattrofunc)instance_setattr, /* tp_setattro */
2199 0, /* tp_as_buffer */
2200 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
2201 instance_doc, /* tp_doc */
2202 (traverseproc)instance_traverse, /* tp_traverse */
2203 0, /* tp_clear */
2204 instance_richcompare, /* tp_richcompare */
2205 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
2206 (getiterfunc)instance_getiter, /* tp_iter */
2207 (iternextfunc)instance_iternext, /* tp_iternext */
2208 0, /* tp_methods */
2209 0, /* tp_members */
2210 0, /* tp_getset */
2211 0, /* tp_base */
2212 0, /* tp_dict */
2213 0, /* tp_descr_get */
2214 0, /* tp_descr_set */
2215 0, /* tp_dictoffset */
2216 0, /* tp_init */
2217 0, /* tp_alloc */
2218 instance_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002219};
2220
2221
Guido van Rossum81daa321993-05-20 14:24:46 +00002222/* Instance method objects are used for two purposes:
2223 (a) as bound instance methods (returned by instancename.methodname)
2224 (b) as unbound methods (returned by ClassName.methodname)
2225 In case (b), im_self is NULL
2226*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002227
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002228PyObject *
Anthony Baxter377be112006-04-11 06:54:30 +00002229PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002230{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002231 register PyMethodObject *im;
2232 im = free_list;
2233 if (im != NULL) {
2234 free_list = (PyMethodObject *)(im->im_self);
2235 PyObject_INIT(im, &PyMethod_Type);
2236 numfree--;
2237 }
2238 else {
2239 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
2240 if (im == NULL)
2241 return NULL;
2242 }
2243 im->im_weakreflist = NULL;
2244 Py_INCREF(func);
2245 im->im_func = func;
2246 Py_XINCREF(self);
2247 im->im_self = self;
2248 Py_XINCREF(klass);
2249 im->im_class = klass;
2250 _PyObject_GC_TRACK(im);
2251 return (PyObject *)im;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002252}
2253
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002254/* Descriptors for PyMethod attributes */
2255
2256/* im_class, im_func and im_self are stored in the PyMethod object */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002257
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002258#define OFF(x) offsetof(PyMethodObject, x)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002259
Guido van Rossum6f799372001-09-20 20:46:19 +00002260static PyMemberDef instancemethod_memberlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002261 {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
2262 "the class associated with a method"},
2263 {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2264 "the function (or other callable) implementing a method"},
2265 {"__func__", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
2266 "the function (or other callable) implementing a method"},
2267 {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2268 "the instance to which a method is bound; None for unbound methods"},
2269 {"__self__", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
2270 "the instance to which a method is bound; None for unbound methods"},
2271 {NULL} /* Sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002272};
2273
Guido van Rossumbaf0f8f2003-11-22 23:55:50 +00002274/* Christian Tismer argued convincingly that method attributes should
2275 (nearly) always override function attributes.
2276 The one exception is __doc__; there's a default __doc__ which
2277 should only be used for the class, not for instances */
2278
2279static PyObject *
2280instancemethod_get_doc(PyMethodObject *im, void *context)
2281{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002282 static PyObject *docstr;
2283 if (docstr == NULL) {
2284 docstr= PyString_InternFromString("__doc__");
2285 if (docstr == NULL)
2286 return NULL;
2287 }
2288 return PyObject_GetAttr(im->im_func, docstr);
Guido van Rossumbaf0f8f2003-11-22 23:55:50 +00002289}
2290
2291static PyGetSetDef instancemethod_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002292 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
2293 {0}
Guido van Rossumbaf0f8f2003-11-22 23:55:50 +00002294};
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002295
2296static PyObject *
2297instancemethod_getattro(PyObject *obj, PyObject *name)
2298{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002299 PyMethodObject *im = (PyMethodObject *)obj;
2300 PyTypeObject *tp = obj->ob_type;
2301 PyObject *descr = NULL;
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002302
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002303 if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
2304 if (tp->tp_dict == NULL) {
2305 if (PyType_Ready(tp) < 0)
2306 return NULL;
2307 }
2308 descr = _PyType_Lookup(tp, name);
2309 }
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002310
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002311 if (descr != NULL) {
2312 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
2313 if (f != NULL)
2314 return f(descr, obj, (PyObject *)obj->ob_type);
2315 else {
2316 Py_INCREF(descr);
2317 return descr;
2318 }
2319 }
Guido van Rossumf0b35e12001-09-18 03:53:24 +00002320
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002321 return PyObject_GetAttr(im->im_func, name);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002322}
2323
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002324PyDoc_STRVAR(instancemethod_doc,
2325"instancemethod(function, instance, class)\n\
2326\n\
2327Create an instance method object.");
2328
2329static PyObject *
2330instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2331{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002332 PyObject *func;
2333 PyObject *self;
2334 PyObject *classObj = NULL;
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002335
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002336 if (!_PyArg_NoKeywords("instancemethod", kw))
2337 return NULL;
2338 if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
2339 &func, &self, &classObj))
2340 return NULL;
2341 if (!PyCallable_Check(func)) {
2342 PyErr_SetString(PyExc_TypeError,
2343 "first argument must be callable");
2344 return NULL;
2345 }
2346 if (self == Py_None)
2347 self = NULL;
2348 if (self == NULL && classObj == NULL) {
2349 PyErr_SetString(PyExc_TypeError,
2350 "unbound methods must have non-NULL im_class");
2351 return NULL;
2352 }
Michael W. Hudsone2749cb2005-03-30 16:32:10 +00002353
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002354 return PyMethod_New(func, self, classObj);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002355}
2356
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002357static void
Fred Drake79912472000-07-09 04:06:11 +00002358instancemethod_dealloc(register PyMethodObject *im)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002359{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002360 _PyObject_GC_UNTRACK(im);
2361 if (im->im_weakreflist != NULL)
2362 PyObject_ClearWeakRefs((PyObject *)im);
2363 Py_DECREF(im->im_func);
2364 Py_XDECREF(im->im_self);
2365 Py_XDECREF(im->im_class);
2366 if (numfree < PyMethod_MAXFREELIST) {
2367 im->im_self = (PyObject *)free_list;
2368 free_list = im;
2369 numfree++;
2370 }
2371 else {
2372 PyObject_GC_Del(im);
2373 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002374}
2375
Guido van Rossumebc8c511992-09-03 20:39:51 +00002376static int
Fred Drake79912472000-07-09 04:06:11 +00002377instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
Guido van Rossumebc8c511992-09-03 20:39:51 +00002378{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002379 int cmp;
2380 cmp = PyObject_Compare(a->im_func, b->im_func);
2381 if (cmp)
2382 return cmp;
Armin Rigofd01d792006-06-08 10:56:24 +00002383
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002384 if (a->im_self == b->im_self)
2385 return 0;
2386 if (a->im_self == NULL || b->im_self == NULL)
2387 return (a->im_self < b->im_self) ? -1 : 1;
2388 else
2389 return PyObject_Compare(a->im_self, b->im_self);
Guido van Rossumebc8c511992-09-03 20:39:51 +00002390}
2391
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002392static PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002393instancemethod_repr(PyMethodObject *a)
Guido van Rossum25831651993-05-19 14:50:45 +00002394{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002395 PyObject *self = a->im_self;
2396 PyObject *func = a->im_func;
2397 PyObject *klass = a->im_class;
2398 PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
2399 char *sfuncname = "?", *sklassname = "?";
Tim Peters6d6c1a32001-08-02 04:15:00 +00002400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002401 funcname = PyObject_GetAttrString(func, "__name__");
2402 if (funcname == NULL) {
2403 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2404 return NULL;
2405 PyErr_Clear();
2406 }
2407 else if (!PyString_Check(funcname)) {
2408 Py_DECREF(funcname);
2409 funcname = NULL;
2410 }
2411 else
2412 sfuncname = PyString_AS_STRING(funcname);
2413 if (klass == NULL)
2414 klassname = NULL;
2415 else {
2416 klassname = PyObject_GetAttrString(klass, "__name__");
2417 if (klassname == NULL) {
2418 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2419 return NULL;
2420 PyErr_Clear();
2421 }
2422 else if (!PyString_Check(klassname)) {
2423 Py_DECREF(klassname);
2424 klassname = NULL;
2425 }
2426 else
2427 sklassname = PyString_AS_STRING(klassname);
2428 }
2429 if (self == NULL)
2430 result = PyString_FromFormat("<unbound method %s.%s>",
2431 sklassname, sfuncname);
2432 else {
2433 /* XXX Shouldn't use repr() here! */
2434 PyObject *selfrepr = PyObject_Repr(self);
2435 if (selfrepr == NULL)
2436 goto fail;
2437 if (!PyString_Check(selfrepr)) {
2438 Py_DECREF(selfrepr);
2439 goto fail;
2440 }
2441 result = PyString_FromFormat("<bound method %s.%s of %s>",
2442 sklassname, sfuncname,
2443 PyString_AS_STRING(selfrepr));
2444 Py_DECREF(selfrepr);
2445 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446 fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002447 Py_XDECREF(funcname);
2448 Py_XDECREF(klassname);
2449 return result;
Guido van Rossum25831651993-05-19 14:50:45 +00002450}
2451
Guido van Rossum9bfef441993-03-29 10:43:31 +00002452static long
Fred Drake79912472000-07-09 04:06:11 +00002453instancemethod_hash(PyMethodObject *a)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002454{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002455 long x, y;
2456 if (a->im_self == NULL)
2457 x = PyObject_Hash(Py_None);
2458 else
2459 x = PyObject_Hash(a->im_self);
2460 if (x == -1)
2461 return -1;
2462 y = PyObject_Hash(a->im_func);
2463 if (y == -1)
2464 return -1;
2465 x = x ^ y;
2466 if (x == -1)
2467 x = -2;
2468 return x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002469}
2470
Jeremy Hylton8caad492000-06-23 14:18:11 +00002471static int
2472instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
2473{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002474 Py_VISIT(im->im_func);
2475 Py_VISIT(im->im_self);
2476 Py_VISIT(im->im_class);
2477 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002478}
2479
Guido van Rossum45ec02a2002-08-19 21:43:18 +00002480static void
Anthony Baxter377be112006-04-11 06:54:30 +00002481getclassname(PyObject *klass, char *buf, int bufsize)
Guido van Rossuma15dece2001-08-24 18:48:27 +00002482{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002483 PyObject *name;
Guido van Rossuma15dece2001-08-24 18:48:27 +00002484
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002485 assert(bufsize > 1);
2486 strcpy(buf, "?"); /* Default outcome */
2487 if (klass == NULL)
2488 return;
2489 name = PyObject_GetAttrString(klass, "__name__");
2490 if (name == NULL) {
2491 /* This function cannot return an exception */
2492 PyErr_Clear();
2493 return;
2494 }
2495 if (PyString_Check(name)) {
2496 strncpy(buf, PyString_AS_STRING(name), bufsize);
2497 buf[bufsize-1] = '\0';
2498 }
2499 Py_DECREF(name);
Guido van Rossuma15dece2001-08-24 18:48:27 +00002500}
2501
Guido van Rossum45ec02a2002-08-19 21:43:18 +00002502static void
2503getinstclassname(PyObject *inst, char *buf, int bufsize)
Guido van Rossuma15dece2001-08-24 18:48:27 +00002504{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002505 PyObject *klass;
Guido van Rossuma15dece2001-08-24 18:48:27 +00002506
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002507 if (inst == NULL) {
2508 assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
2509 strcpy(buf, "nothing");
2510 return;
2511 }
Guido van Rossuma15dece2001-08-24 18:48:27 +00002512
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002513 klass = PyObject_GetAttrString(inst, "__class__");
2514 if (klass == NULL) {
2515 /* This function cannot return an exception */
2516 PyErr_Clear();
2517 klass = (PyObject *)(inst->ob_type);
2518 Py_INCREF(klass);
2519 }
2520 getclassname(klass, buf, bufsize);
2521 Py_XDECREF(klass);
Guido van Rossuma15dece2001-08-24 18:48:27 +00002522}
2523
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524static PyObject *
2525instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
2526{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002527 PyObject *self = PyMethod_GET_SELF(func);
2528 PyObject *klass = PyMethod_GET_CLASS(func);
2529 PyObject *result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002531 func = PyMethod_GET_FUNCTION(func);
2532 if (self == NULL) {
2533 /* Unbound methods must be called with an instance of
2534 the class (or a derived class) as first argument */
2535 int ok;
2536 if (PyTuple_Size(arg) >= 1)
2537 self = PyTuple_GET_ITEM(arg, 0);
2538 if (self == NULL)
2539 ok = 0;
2540 else {
2541 ok = PyObject_IsInstance(self, klass);
2542 if (ok < 0)
2543 return NULL;
2544 }
2545 if (!ok) {
2546 char clsbuf[256];
2547 char instbuf[256];
2548 getclassname(klass, clsbuf, sizeof(clsbuf));
2549 getinstclassname(self, instbuf, sizeof(instbuf));
2550 PyErr_Format(PyExc_TypeError,
2551 "unbound method %s%s must be called with "
2552 "%s instance as first argument "
2553 "(got %s%s instead)",
2554 PyEval_GetFuncName(func),
2555 PyEval_GetFuncDesc(func),
2556 clsbuf,
2557 instbuf,
2558 self == NULL ? "" : " instance");
2559 return NULL;
2560 }
2561 Py_INCREF(arg);
2562 }
2563 else {
2564 Py_ssize_t argcount = PyTuple_Size(arg);
2565 PyObject *newarg = PyTuple_New(argcount + 1);
2566 int i;
2567 if (newarg == NULL)
2568 return NULL;
2569 Py_INCREF(self);
2570 PyTuple_SET_ITEM(newarg, 0, self);
2571 for (i = 0; i < argcount; i++) {
2572 PyObject *v = PyTuple_GET_ITEM(arg, i);
2573 Py_XINCREF(v);
2574 PyTuple_SET_ITEM(newarg, i+1, v);
2575 }
2576 arg = newarg;
2577 }
2578 result = PyObject_Call((PyObject *)func, arg, kw);
2579 Py_DECREF(arg);
2580 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002581}
2582
Guido van Rossum23cc2b42001-08-15 17:52:31 +00002583static PyObject *
Guido van Rossum6bae46d2003-02-11 18:43:00 +00002584instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
Guido van Rossum23cc2b42001-08-15 17:52:31 +00002585{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002586 /* Don't rebind an already bound method, or an unbound method
2587 of a class that's not a base class of cls. */
Guido van Rossum6bae46d2003-02-11 18:43:00 +00002588
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002589 if (PyMethod_GET_SELF(meth) != NULL) {
2590 /* Already bound */
2591 Py_INCREF(meth);
2592 return meth;
2593 }
2594 /* No, it is an unbound method */
2595 if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
2596 /* Do subclass test. If it fails, return meth unchanged. */
2597 int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
2598 if (ok < 0)
2599 return NULL;
2600 if (!ok) {
2601 Py_INCREF(meth);
2602 return meth;
2603 }
2604 }
2605 /* Bind it to obj */
2606 return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
Guido van Rossum23cc2b42001-08-15 17:52:31 +00002607}
2608
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002609PyTypeObject PyMethod_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002610 PyObject_HEAD_INIT(&PyType_Type)
2611 0,
2612 "instancemethod",
2613 sizeof(PyMethodObject),
2614 0,
2615 (destructor)instancemethod_dealloc, /* tp_dealloc */
2616 0, /* tp_print */
2617 0, /* tp_getattr */
2618 0, /* tp_setattr */
2619 (cmpfunc)instancemethod_compare, /* tp_compare */
2620 (reprfunc)instancemethod_repr, /* tp_repr */
2621 0, /* tp_as_number */
2622 0, /* tp_as_sequence */
2623 0, /* tp_as_mapping */
2624 (hashfunc)instancemethod_hash, /* tp_hash */
2625 instancemethod_call, /* tp_call */
2626 0, /* tp_str */
2627 instancemethod_getattro, /* tp_getattro */
2628 PyObject_GenericSetAttr, /* tp_setattro */
2629 0, /* tp_as_buffer */
2630 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
2631 instancemethod_doc, /* tp_doc */
2632 (traverseproc)instancemethod_traverse, /* tp_traverse */
2633 0, /* tp_clear */
2634 0, /* tp_richcompare */
2635 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
2636 0, /* tp_iter */
2637 0, /* tp_iternext */
2638 0, /* tp_methods */
2639 instancemethod_memberlist, /* tp_members */
2640 instancemethod_getset, /* tp_getset */
2641 0, /* tp_base */
2642 0, /* tp_dict */
2643 instancemethod_descr_get, /* tp_descr_get */
2644 0, /* tp_descr_set */
2645 0, /* tp_dictoffset */
2646 0, /* tp_init */
2647 0, /* tp_alloc */
2648 instancemethod_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002649};
Guido van Rossuma0d349f1997-08-05 02:06:53 +00002650
2651/* Clear out the free list */
2652
Christian Heimes3b718a72008-02-14 12:47:33 +00002653int
2654PyMethod_ClearFreeList(void)
Guido van Rossuma0d349f1997-08-05 02:06:53 +00002655{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002656 int freelist_size = numfree;
2657
2658 while (free_list) {
2659 PyMethodObject *im = free_list;
2660 free_list = (PyMethodObject *)(im->im_self);
2661 PyObject_GC_Del(im);
2662 numfree--;
2663 }
2664 assert(numfree == 0);
2665 return freelist_size;
Christian Heimes3b718a72008-02-14 12:47:33 +00002666}
2667
2668void
2669PyMethod_Fini(void)
2670{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002671 (void)PyMethod_ClearFreeList();
Guido van Rossuma0d349f1997-08-05 02:06:53 +00002672}