2 /* Class object implementation */
5 #include "structmember.h"
7 #define TP_DESCR_GET(t) \
8 (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
12 static PyObject
*class_lookup(PyClassObject
*, PyObject
*,
14 static PyObject
*instance_getattr1(PyInstanceObject
*, PyObject
*);
15 static PyObject
*instance_getattr2(PyInstanceObject
*, PyObject
*);
17 static PyObject
*getattrstr
, *setattrstr
, *delattrstr
;
21 PyClass_New(PyObject
*bases
, PyObject
*dict
, PyObject
*name
)
22 /* bases is NULL or tuple of classobjects! */
24 PyClassObject
*op
, *dummy
;
25 static PyObject
*docstr
, *modstr
, *namestr
;
27 docstr
= PyString_InternFromString("__doc__");
32 modstr
= PyString_InternFromString("__module__");
36 if (namestr
== NULL
) {
37 namestr
= PyString_InternFromString("__name__");
41 if (name
== NULL
|| !PyString_Check(name
)) {
42 PyErr_SetString(PyExc_TypeError
,
43 "PyClass_New: name must be a string");
46 if (dict
== NULL
|| !PyDict_Check(dict
)) {
47 PyErr_SetString(PyExc_TypeError
,
48 "PyClass_New: dict must be a dictionary");
51 if (PyDict_GetItem(dict
, docstr
) == NULL
) {
52 if (PyDict_SetItem(dict
, docstr
, Py_None
) < 0)
55 if (PyDict_GetItem(dict
, modstr
) == NULL
) {
56 PyObject
*globals
= PyEval_GetGlobals();
57 if (globals
!= NULL
) {
58 PyObject
*modname
= PyDict_GetItem(globals
, namestr
);
59 if (modname
!= NULL
) {
60 if (PyDict_SetItem(dict
, modstr
, modname
) < 0)
66 bases
= PyTuple_New(0);
73 if (!PyTuple_Check(bases
)) {
74 PyErr_SetString(PyExc_TypeError
,
75 "PyClass_New: bases must be a tuple");
78 n
= PyTuple_Size(bases
);
79 for (i
= 0; i
< n
; i
++) {
80 base
= PyTuple_GET_ITEM(bases
, i
);
81 if (!PyClass_Check(base
)) {
83 (PyObject
*) base
->ob_type
))
84 return PyObject_CallFunction(
85 (PyObject
*) base
->ob_type
,
90 PyErr_SetString(PyExc_TypeError
,
91 "PyClass_New: base must be a class");
97 op
= PyObject_GC_New(PyClassObject
, &PyClass_Type
);
102 op
->cl_bases
= bases
;
107 if (getattrstr
== NULL
) {
108 getattrstr
= PyString_InternFromString("__getattr__");
109 setattrstr
= PyString_InternFromString("__setattr__");
110 delattrstr
= PyString_InternFromString("__delattr__");
112 op
->cl_getattr
= class_lookup(op
, getattrstr
, &dummy
);
113 op
->cl_setattr
= class_lookup(op
, setattrstr
, &dummy
);
114 op
->cl_delattr
= class_lookup(op
, delattrstr
, &dummy
);
115 Py_XINCREF(op
->cl_getattr
);
116 Py_XINCREF(op
->cl_setattr
);
117 Py_XINCREF(op
->cl_delattr
);
118 _PyObject_GC_TRACK(op
);
119 return (PyObject
*) op
;
123 PyMethod_Function(PyObject
*im
)
125 if (!PyMethod_Check(im
)) {
126 PyErr_BadInternalCall();
129 return ((PyMethodObject
*)im
)->im_func
;
133 PyMethod_Self(PyObject
*im
)
135 if (!PyMethod_Check(im
)) {
136 PyErr_BadInternalCall();
139 return ((PyMethodObject
*)im
)->im_self
;
143 PyMethod_Class(PyObject
*im
)
145 if (!PyMethod_Check(im
)) {
146 PyErr_BadInternalCall();
149 return ((PyMethodObject
*)im
)->im_class
;
152 PyDoc_STRVAR(class_doc
,
153 "classobj(name, bases, dict)\n\
155 Create a class object. The name must be a string; the second argument\n\
156 a tuple of classes, and the third a dictionary.");
159 class_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
161 PyObject
*name
, *bases
, *dict
;
162 static const char *kwlist
[] = {"name", "bases", "dict", 0};
164 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "SOO", kwlist
,
165 &name
, &bases
, &dict
))
167 return PyClass_New(bases
, dict
, name
);
173 class_dealloc(PyClassObject
*op
)
175 _PyObject_GC_UNTRACK(op
);
176 Py_DECREF(op
->cl_bases
);
177 Py_DECREF(op
->cl_dict
);
178 Py_XDECREF(op
->cl_name
);
179 Py_XDECREF(op
->cl_getattr
);
180 Py_XDECREF(op
->cl_setattr
);
181 Py_XDECREF(op
->cl_delattr
);
186 class_lookup(PyClassObject
*cp
, PyObject
*name
, PyClassObject
**pclass
)
189 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
194 n
= PyTuple_Size(cp
->cl_bases
);
195 for (i
= 0; i
< n
; i
++) {
196 /* XXX What if one of the bases is not a class? */
197 PyObject
*v
= class_lookup(
199 PyTuple_GetItem(cp
->cl_bases
, i
), name
, pclass
);
207 class_getattr(register PyClassObject
*op
, PyObject
*name
)
209 register PyObject
*v
;
210 register char *sname
= PyString_AsString(name
);
211 PyClassObject
*class;
214 if (sname
[0] == '_' && sname
[1] == '_') {
215 if (strcmp(sname
, "__dict__") == 0) {
216 if (PyEval_GetRestricted()) {
217 PyErr_SetString(PyExc_RuntimeError
,
218 "class.__dict__ not accessible in restricted mode");
221 Py_INCREF(op
->cl_dict
);
224 if (strcmp(sname
, "__bases__") == 0) {
225 Py_INCREF(op
->cl_bases
);
228 if (strcmp(sname
, "__name__") == 0) {
229 if (op
->cl_name
== NULL
)
237 v
= class_lookup(op
, name
, &class);
239 PyErr_Format(PyExc_AttributeError
,
240 "class %.50s has no attribute '%.400s'",
241 PyString_AS_STRING(op
->cl_name
), sname
);
244 f
= TP_DESCR_GET(v
->ob_type
);
248 v
= f(v
, (PyObject
*)NULL
, (PyObject
*)op
);
253 set_slot(PyObject
**slot
, PyObject
*v
)
255 PyObject
*temp
= *slot
;
262 set_attr_slots(PyClassObject
*c
)
264 PyClassObject
*dummy
;
266 set_slot(&c
->cl_getattr
, class_lookup(c
, getattrstr
, &dummy
));
267 set_slot(&c
->cl_setattr
, class_lookup(c
, setattrstr
, &dummy
));
268 set_slot(&c
->cl_delattr
, class_lookup(c
, delattrstr
, &dummy
));
272 set_dict(PyClassObject
*c
, PyObject
*v
)
274 if (v
== NULL
|| !PyDict_Check(v
))
275 return "__dict__ must be a dictionary object";
276 set_slot(&c
->cl_dict
, v
);
282 set_bases(PyClassObject
*c
, PyObject
*v
)
286 if (v
== NULL
|| !PyTuple_Check(v
))
287 return "__bases__ must be a tuple object";
289 for (i
= 0; i
< n
; i
++) {
290 PyObject
*x
= PyTuple_GET_ITEM(v
, i
);
291 if (!PyClass_Check(x
))
292 return "__bases__ items must be classes";
293 if (PyClass_IsSubclass(x
, (PyObject
*)c
))
294 return "a __bases__ item causes an inheritance cycle";
296 set_slot(&c
->cl_bases
, v
);
302 set_name(PyClassObject
*c
, PyObject
*v
)
304 if (v
== NULL
|| !PyString_Check(v
))
305 return "__name__ must be a string object";
306 if (strlen(PyString_AS_STRING(v
)) != (size_t)PyString_GET_SIZE(v
))
307 return "__name__ must not contain null bytes";
308 set_slot(&c
->cl_name
, v
);
313 class_setattr(PyClassObject
*op
, PyObject
*name
, PyObject
*v
)
316 if (PyEval_GetRestricted()) {
317 PyErr_SetString(PyExc_RuntimeError
,
318 "classes are read-only in restricted mode");
321 sname
= PyString_AsString(name
);
322 if (sname
[0] == '_' && sname
[1] == '_') {
323 int n
= PyString_Size(name
);
324 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
326 if (strcmp(sname
, "__dict__") == 0)
327 err
= set_dict(op
, v
);
328 else if (strcmp(sname
, "__bases__") == 0)
329 err
= set_bases(op
, v
);
330 else if (strcmp(sname
, "__name__") == 0)
331 err
= set_name(op
, v
);
332 else if (strcmp(sname
, "__getattr__") == 0)
333 set_slot(&op
->cl_getattr
, v
);
334 else if (strcmp(sname
, "__setattr__") == 0)
335 set_slot(&op
->cl_setattr
, v
);
336 else if (strcmp(sname
, "__delattr__") == 0)
337 set_slot(&op
->cl_delattr
, v
);
338 /* For the last three, we fall through to update the
339 dictionary as well. */
343 PyErr_SetString(PyExc_TypeError
, err
);
349 int rv
= PyDict_DelItem(op
->cl_dict
, name
);
351 PyErr_Format(PyExc_AttributeError
,
352 "class %.50s has no attribute '%.400s'",
353 PyString_AS_STRING(op
->cl_name
), sname
);
357 return PyDict_SetItem(op
->cl_dict
, name
, v
);
361 class_repr(PyClassObject
*op
)
363 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
365 if (op
->cl_name
== NULL
|| !PyString_Check(op
->cl_name
))
368 name
= PyString_AsString(op
->cl_name
);
369 if (mod
== NULL
|| !PyString_Check(mod
))
370 return PyString_FromFormat("<class ?.%s at %p>", name
, op
);
372 return PyString_FromFormat("<class %s.%s at %p>",
373 PyString_AsString(mod
),
378 class_str(PyClassObject
*op
)
380 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
381 PyObject
*name
= op
->cl_name
;
385 if (name
== NULL
|| !PyString_Check(name
))
386 return class_repr(op
);
387 if (mod
== NULL
|| !PyString_Check(mod
)) {
391 m
= PyString_Size(mod
);
392 n
= PyString_Size(name
);
393 res
= PyString_FromStringAndSize((char *)NULL
, m
+1+n
);
395 char *s
= PyString_AsString(res
);
396 memcpy(s
, PyString_AsString(mod
), m
);
399 memcpy(s
, PyString_AsString(name
), n
);
405 class_traverse(PyClassObject
*o
, visitproc visit
, void *arg
)
409 err
= visit(o
->cl_bases
, arg
);
414 err
= visit(o
->cl_dict
, arg
);
419 err
= visit(o
->cl_name
, arg
);
424 err
= visit(o
->cl_getattr
, arg
);
429 err
= visit(o
->cl_setattr
, arg
);
434 err
= visit(o
->cl_delattr
, arg
);
441 PyTypeObject PyClass_Type
= {
442 PyObject_HEAD_INIT(&PyType_Type
)
445 sizeof(PyClassObject
),
447 (destructor
)class_dealloc
, /* tp_dealloc */
452 (reprfunc
)class_repr
, /* tp_repr */
453 0, /* tp_as_number */
454 0, /* tp_as_sequence */
455 0, /* tp_as_mapping */
457 PyInstance_New
, /* tp_call */
458 (reprfunc
)class_str
, /* tp_str */
459 (getattrofunc
)class_getattr
, /* tp_getattro */
460 (setattrofunc
)class_setattr
, /* tp_setattro */
461 0, /* tp_as_buffer */
462 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
463 class_doc
, /* tp_doc */
464 (traverseproc
)class_traverse
, /* tp_traverse */
466 0, /* tp_richcompare */
467 0, /* tp_weaklistoffset */
475 0, /* tp_descr_get */
476 0, /* tp_descr_set */
477 0, /* tp_dictoffset */
480 class_new
, /* tp_new */
484 PyClass_IsSubclass(PyObject
*class, PyObject
*base
)
490 if (PyTuple_Check(base
)) {
491 n
= PyTuple_GET_SIZE(base
);
492 for (i
= 0; i
< n
; i
++) {
493 if (PyClass_IsSubclass(class, PyTuple_GET_ITEM(base
, i
)))
498 if (class == NULL
|| !PyClass_Check(class))
500 cp
= (PyClassObject
*)class;
501 n
= PyTuple_Size(cp
->cl_bases
);
502 for (i
= 0; i
< n
; i
++) {
503 if (PyClass_IsSubclass(PyTuple_GetItem(cp
->cl_bases
, i
), base
))
510 /* Instance objects */
513 PyInstance_NewRaw(PyObject
*klass
, PyObject
*dict
)
515 PyInstanceObject
*inst
;
517 if (!PyClass_Check(klass
)) {
518 PyErr_BadInternalCall();
527 if (!PyDict_Check(dict
)) {
528 PyErr_BadInternalCall();
533 inst
= PyObject_GC_New(PyInstanceObject
, &PyInstance_Type
);
538 inst
->in_weakreflist
= NULL
;
540 inst
->in_class
= (PyClassObject
*)klass
;
541 inst
->in_dict
= dict
;
542 _PyObject_GC_TRACK(inst
);
543 return (PyObject
*)inst
;
547 PyInstance_New(PyObject
*klass
, PyObject
*arg
, PyObject
*kw
)
549 register PyInstanceObject
*inst
;
551 static PyObject
*initstr
;
553 inst
= (PyInstanceObject
*) PyInstance_NewRaw(klass
, NULL
);
557 initstr
= PyString_InternFromString("__init__");
558 init
= instance_getattr2(inst
, initstr
);
560 if (PyErr_Occurred()) {
564 if ((arg
!= NULL
&& (!PyTuple_Check(arg
) ||
565 PyTuple_Size(arg
) != 0))
566 || (kw
!= NULL
&& (!PyDict_Check(kw
) ||
567 PyDict_Size(kw
) != 0))) {
568 PyErr_SetString(PyExc_TypeError
,
569 "this constructor takes no arguments");
575 PyObject
*res
= PyEval_CallObjectWithKeywords(init
, arg
, kw
);
582 if (res
!= Py_None
) {
583 PyErr_SetString(PyExc_TypeError
,
584 "__init__() should return None");
591 return (PyObject
*)inst
;
594 /* Instance methods */
596 PyDoc_STRVAR(instance_doc
,
597 "instance(class[, dict])\n\
599 Create an instance without calling its __init__() method.\n\
600 The class must be a classic class.\n\
601 If present, dict must be a dictionary or None.");
604 instance_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
607 PyObject
*dict
= Py_None
;
609 if (!PyArg_ParseTuple(args
, "O!|O:instance",
610 &PyClass_Type
, &klass
, &dict
))
615 else if (!PyDict_Check(dict
)) {
616 PyErr_SetString(PyExc_TypeError
,
617 "instance() second arg must be dictionary or None");
620 return PyInstance_NewRaw(klass
, dict
);
625 instance_dealloc(register PyInstanceObject
*inst
)
627 PyObject
*error_type
, *error_value
, *error_traceback
;
629 static PyObject
*delstr
;
631 _PyObject_GC_UNTRACK(inst
);
632 if (inst
->in_weakreflist
!= NULL
)
633 PyObject_ClearWeakRefs((PyObject
*) inst
);
635 /* Temporarily resurrect the object. */
636 assert(inst
->ob_type
== &PyInstance_Type
);
637 assert(inst
->ob_refcnt
== 0);
640 /* Save the current exception, if any. */
641 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
642 /* Execute __del__ method, if any. */
644 delstr
= PyString_InternFromString("__del__");
645 if ((del
= instance_getattr2(inst
, delstr
)) != NULL
) {
646 PyObject
*res
= PyEval_CallObject(del
, (PyObject
*)NULL
);
648 PyErr_WriteUnraisable(del
);
653 /* Restore the saved exception. */
654 PyErr_Restore(error_type
, error_value
, error_traceback
);
656 /* Undo the temporary resurrection; can't use DECREF here, it would
657 * cause a recursive call.
659 assert(inst
->ob_refcnt
> 0);
660 if (--inst
->ob_refcnt
== 0) {
661 Py_DECREF(inst
->in_class
);
662 Py_XDECREF(inst
->in_dict
);
663 PyObject_GC_Del(inst
);
666 int refcnt
= inst
->ob_refcnt
;
667 /* __del__ resurrected it! Make it look like the original
668 * Py_DECREF never happened.
670 _Py_NewReference((PyObject
*)inst
);
671 inst
->ob_refcnt
= refcnt
;
672 _PyObject_GC_TRACK(inst
);
673 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
674 * we need to undo that. */
676 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
677 * object chain, so no more to do there.
678 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
679 * _Py_NewReference bumped tp_allocs: both of those need to be
683 --inst
->ob_type
->tp_frees
;
684 --inst
->ob_type
->tp_allocs
;
690 instance_getattr1(register PyInstanceObject
*inst
, PyObject
*name
)
692 register PyObject
*v
;
693 register char *sname
= PyString_AsString(name
);
694 if (sname
[0] == '_' && sname
[1] == '_') {
695 if (strcmp(sname
, "__dict__") == 0) {
696 if (PyEval_GetRestricted()) {
697 PyErr_SetString(PyExc_RuntimeError
,
698 "instance.__dict__ not accessible in restricted mode");
701 Py_INCREF(inst
->in_dict
);
702 return inst
->in_dict
;
704 if (strcmp(sname
, "__class__") == 0) {
705 Py_INCREF(inst
->in_class
);
706 return (PyObject
*)inst
->in_class
;
709 v
= instance_getattr2(inst
, name
);
710 if (v
== NULL
&& !PyErr_Occurred()) {
711 PyErr_Format(PyExc_AttributeError
,
712 "%.50s instance has no attribute '%.400s'",
713 PyString_AS_STRING(inst
->in_class
->cl_name
), sname
);
719 instance_getattr2(register PyInstanceObject
*inst
, PyObject
*name
)
721 register PyObject
*v
;
722 PyClassObject
*class;
725 v
= PyDict_GetItem(inst
->in_dict
, name
);
730 v
= class_lookup(inst
->in_class
, name
, &class);
733 f
= TP_DESCR_GET(v
->ob_type
);
735 PyObject
*w
= f(v
, (PyObject
*)inst
,
736 (PyObject
*)(inst
->in_class
));
745 instance_getattr(register PyInstanceObject
*inst
, PyObject
*name
)
747 register PyObject
*func
, *res
;
748 res
= instance_getattr1(inst
, name
);
749 if (res
== NULL
&& (func
= inst
->in_class
->cl_getattr
) != NULL
) {
751 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
754 args
= PyTuple_Pack(2, inst
, name
);
757 res
= PyEval_CallObject(func
, args
);
763 /* See classobject.h comments: this only does dict lookups, and is always
767 _PyInstance_Lookup(PyObject
*pinst
, PyObject
*name
)
770 PyClassObject
*class;
771 PyInstanceObject
*inst
; /* pinst cast to the right type */
773 assert(PyInstance_Check(pinst
));
774 inst
= (PyInstanceObject
*)pinst
;
776 assert(PyString_Check(name
));
778 v
= PyDict_GetItem(inst
->in_dict
, name
);
780 v
= class_lookup(inst
->in_class
, name
, &class);
785 instance_setattr1(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
788 int rv
= PyDict_DelItem(inst
->in_dict
, name
);
790 PyErr_Format(PyExc_AttributeError
,
791 "%.50s instance has no attribute '%.400s'",
792 PyString_AS_STRING(inst
->in_class
->cl_name
),
793 PyString_AS_STRING(name
));
797 return PyDict_SetItem(inst
->in_dict
, name
, v
);
801 instance_setattr(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
803 PyObject
*func
, *args
, *res
, *tmp
;
804 char *sname
= PyString_AsString(name
);
805 if (sname
[0] == '_' && sname
[1] == '_') {
806 int n
= PyString_Size(name
);
807 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
808 if (strcmp(sname
, "__dict__") == 0) {
809 if (PyEval_GetRestricted()) {
810 PyErr_SetString(PyExc_RuntimeError
,
811 "__dict__ not accessible in restricted mode");
814 if (v
== NULL
|| !PyDict_Check(v
)) {
815 PyErr_SetString(PyExc_TypeError
,
816 "__dict__ must be set to a dictionary");
825 if (strcmp(sname
, "__class__") == 0) {
826 if (PyEval_GetRestricted()) {
827 PyErr_SetString(PyExc_RuntimeError
,
828 "__class__ not accessible in restricted mode");
831 if (v
== NULL
|| !PyClass_Check(v
)) {
832 PyErr_SetString(PyExc_TypeError
,
833 "__class__ must be set to a class");
836 tmp
= (PyObject
*)(inst
->in_class
);
838 inst
->in_class
= (PyClassObject
*)v
;
845 func
= inst
->in_class
->cl_delattr
;
847 func
= inst
->in_class
->cl_setattr
;
849 return instance_setattr1(inst
, name
, v
);
851 args
= PyTuple_Pack(2, inst
, name
);
853 args
= PyTuple_Pack(3, inst
, name
, v
);
856 res
= PyEval_CallObject(func
, args
);
865 instance_repr(PyInstanceObject
*inst
)
869 static PyObject
*reprstr
;
872 reprstr
= PyString_InternFromString("__repr__");
873 func
= instance_getattr(inst
, reprstr
);
875 PyObject
*classname
, *mod
;
877 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
880 classname
= inst
->in_class
->cl_name
;
881 mod
= PyDict_GetItemString(inst
->in_class
->cl_dict
,
883 if (classname
!= NULL
&& PyString_Check(classname
))
884 cname
= PyString_AsString(classname
);
887 if (mod
== NULL
|| !PyString_Check(mod
))
888 return PyString_FromFormat("<?.%s instance at %p>",
891 return PyString_FromFormat("<%s.%s instance at %p>",
892 PyString_AsString(mod
),
895 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
901 instance_str(PyInstanceObject
*inst
)
905 static PyObject
*strstr
;
908 strstr
= PyString_InternFromString("__str__");
909 func
= instance_getattr(inst
, strstr
);
911 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
914 return instance_repr(inst
);
916 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
922 instance_hash(PyInstanceObject
*inst
)
927 static PyObject
*hashstr
, *eqstr
, *cmpstr
;
930 hashstr
= PyString_InternFromString("__hash__");
931 func
= instance_getattr(inst
, hashstr
);
933 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
936 /* If there is no __eq__ and no __cmp__ method, we hash on the
937 address. If an __eq__ or __cmp__ method exists, there must
940 eqstr
= PyString_InternFromString("__eq__");
941 func
= instance_getattr(inst
, eqstr
);
943 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
947 cmpstr
= PyString_InternFromString("__cmp__");
948 func
= instance_getattr(inst
, cmpstr
);
950 if (!PyErr_ExceptionMatches(
951 PyExc_AttributeError
))
954 return _Py_HashPointer(inst
);
958 PyErr_SetString(PyExc_TypeError
, "unhashable instance");
961 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
965 if (PyInt_Check(res
)) {
966 outcome
= PyInt_AsLong(res
);
971 PyErr_SetString(PyExc_TypeError
,
972 "__hash__() should return an int");
980 instance_traverse(PyInstanceObject
*o
, visitproc visit
, void *arg
)
984 err
= visit((PyObject
*)(o
->in_class
), arg
);
989 err
= visit(o
->in_dict
, arg
);
996 static PyObject
*getitemstr
, *setitemstr
, *delitemstr
, *lenstr
;
997 static PyObject
*iterstr
, *nextstr
;
1000 instance_length(PyInstanceObject
*inst
)
1007 lenstr
= PyString_InternFromString("__len__");
1008 func
= instance_getattr(inst
, lenstr
);
1011 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1015 if (PyInt_Check(res
)) {
1016 long temp
= PyInt_AsLong(res
);
1017 outcome
= (int)temp
;
1018 #if SIZEOF_INT < SIZEOF_LONG
1019 /* Overflow check -- range of PyInt is more than C int */
1020 if (outcome
!= temp
) {
1021 PyErr_SetString(PyExc_OverflowError
,
1022 "__len__() should return 0 <= outcome < 2**31");
1028 PyErr_SetString(PyExc_ValueError
,
1029 "__len__() should return >= 0");
1032 PyErr_SetString(PyExc_TypeError
,
1033 "__len__() should return an int");
1041 instance_subscript(PyInstanceObject
*inst
, PyObject
*key
)
1047 if (getitemstr
== NULL
)
1048 getitemstr
= PyString_InternFromString("__getitem__");
1049 func
= instance_getattr(inst
, getitemstr
);
1052 arg
= PyTuple_Pack(1, key
);
1057 res
= PyEval_CallObject(func
, arg
);
1064 instance_ass_subscript(PyInstanceObject
*inst
, PyObject
*key
, PyObject
*value
)
1070 if (value
== NULL
) {
1071 if (delitemstr
== NULL
)
1072 delitemstr
= PyString_InternFromString("__delitem__");
1073 func
= instance_getattr(inst
, delitemstr
);
1076 if (setitemstr
== NULL
)
1077 setitemstr
= PyString_InternFromString("__setitem__");
1078 func
= instance_getattr(inst
, setitemstr
);
1083 arg
= PyTuple_Pack(1, key
);
1085 arg
= PyTuple_Pack(2, key
, value
);
1090 res
= PyEval_CallObject(func
, arg
);
1099 static PyMappingMethods instance_as_mapping
= {
1100 (inquiry
)instance_length
, /* mp_length */
1101 (binaryfunc
)instance_subscript
, /* mp_subscript */
1102 (objobjargproc
)instance_ass_subscript
, /* mp_ass_subscript */
1106 instance_item(PyInstanceObject
*inst
, int i
)
1108 PyObject
*func
, *arg
, *res
;
1110 if (getitemstr
== NULL
)
1111 getitemstr
= PyString_InternFromString("__getitem__");
1112 func
= instance_getattr(inst
, getitemstr
);
1115 arg
= Py_BuildValue("(i)", i
);
1120 res
= PyEval_CallObject(func
, arg
);
1127 sliceobj_from_intint(int i
, int j
)
1129 PyObject
*start
, *end
, *res
;
1131 start
= PyInt_FromLong((long)i
);
1135 end
= PyInt_FromLong((long)j
);
1140 res
= PySlice_New(start
, end
, NULL
);
1148 instance_slice(PyInstanceObject
*inst
, int i
, int j
)
1150 PyObject
*func
, *arg
, *res
;
1151 static PyObject
*getslicestr
;
1153 if (getslicestr
== NULL
)
1154 getslicestr
= PyString_InternFromString("__getslice__");
1155 func
= instance_getattr(inst
, getslicestr
);
1158 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1162 if (getitemstr
== NULL
)
1163 getitemstr
= PyString_InternFromString("__getitem__");
1164 func
= instance_getattr(inst
, getitemstr
);
1167 arg
= Py_BuildValue("(N)", sliceobj_from_intint(i
, j
));
1169 arg
= Py_BuildValue("(ii)", i
, j
);
1175 res
= PyEval_CallObject(func
, arg
);
1182 instance_ass_item(PyInstanceObject
*inst
, int i
, PyObject
*item
)
1184 PyObject
*func
, *arg
, *res
;
1187 if (delitemstr
== NULL
)
1188 delitemstr
= PyString_InternFromString("__delitem__");
1189 func
= instance_getattr(inst
, delitemstr
);
1192 if (setitemstr
== NULL
)
1193 setitemstr
= PyString_InternFromString("__setitem__");
1194 func
= instance_getattr(inst
, setitemstr
);
1199 arg
= Py_BuildValue("i", i
);
1201 arg
= Py_BuildValue("(iO)", i
, item
);
1206 res
= PyEval_CallObject(func
, arg
);
1216 instance_ass_slice(PyInstanceObject
*inst
, int i
, int j
, PyObject
*value
)
1218 PyObject
*func
, *arg
, *res
;
1219 static PyObject
*setslicestr
, *delslicestr
;
1221 if (value
== NULL
) {
1222 if (delslicestr
== NULL
)
1224 PyString_InternFromString("__delslice__");
1225 func
= instance_getattr(inst
, delslicestr
);
1227 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1230 if (delitemstr
== NULL
)
1232 PyString_InternFromString("__delitem__");
1233 func
= instance_getattr(inst
, delitemstr
);
1237 arg
= Py_BuildValue("(N)",
1238 sliceobj_from_intint(i
, j
));
1240 arg
= Py_BuildValue("(ii)", i
, j
);
1243 if (setslicestr
== NULL
)
1245 PyString_InternFromString("__setslice__");
1246 func
= instance_getattr(inst
, setslicestr
);
1248 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1251 if (setitemstr
== NULL
)
1253 PyString_InternFromString("__setitem__");
1254 func
= instance_getattr(inst
, setitemstr
);
1258 arg
= Py_BuildValue("(NO)",
1259 sliceobj_from_intint(i
, j
), value
);
1261 arg
= Py_BuildValue("(iiO)", i
, j
, value
);
1267 res
= PyEval_CallObject(func
, arg
);
1277 instance_contains(PyInstanceObject
*inst
, PyObject
*member
)
1279 static PyObject
*__contains__
;
1282 /* Try __contains__ first.
1283 * If that can't be done, try iterator-based searching.
1286 if(__contains__
== NULL
) {
1287 __contains__
= PyString_InternFromString("__contains__");
1288 if(__contains__
== NULL
)
1291 func
= instance_getattr(inst
, __contains__
);
1295 PyObject
*arg
= PyTuple_Pack(1, member
);
1300 res
= PyEval_CallObject(func
, arg
);
1305 ret
= PyObject_IsTrue(res
);
1310 /* Couldn't find __contains__. */
1311 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1312 /* Assume the failure was simply due to that there is no
1313 * __contains__ attribute, and try iterating instead.
1316 return _PySequence_IterSearch((PyObject
*)inst
, member
,
1317 PY_ITERSEARCH_CONTAINS
);
1323 static PySequenceMethods
1324 instance_as_sequence
= {
1325 (inquiry
)instance_length
, /* sq_length */
1328 (intargfunc
)instance_item
, /* sq_item */
1329 (intintargfunc
)instance_slice
, /* sq_slice */
1330 (intobjargproc
)instance_ass_item
, /* sq_ass_item */
1331 (intintobjargproc
)instance_ass_slice
, /* sq_ass_slice */
1332 (objobjproc
)instance_contains
, /* sq_contains */
1336 generic_unary_op(PyInstanceObject
*self
, PyObject
*methodname
)
1338 PyObject
*func
, *res
;
1340 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1342 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1348 generic_binary_op(PyObject
*v
, PyObject
*w
, char *opname
)
1352 PyObject
*func
= PyObject_GetAttrString(v
, opname
);
1354 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1357 Py_INCREF(Py_NotImplemented
);
1358 return Py_NotImplemented
;
1360 args
= PyTuple_Pack(1, w
);
1365 result
= PyEval_CallObject(func
, args
);
1372 static PyObject
*coerce_obj
;
1374 /* Try one half of a binary operator involving a class instance. */
1376 half_binop(PyObject
*v
, PyObject
*w
, char *opname
, binaryfunc thisfunc
,
1380 PyObject
*coercefunc
;
1381 PyObject
*coerced
= NULL
;
1385 if (!PyInstance_Check(v
)) {
1386 Py_INCREF(Py_NotImplemented
);
1387 return Py_NotImplemented
;
1390 if (coerce_obj
== NULL
) {
1391 coerce_obj
= PyString_InternFromString("__coerce__");
1392 if (coerce_obj
== NULL
)
1395 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1396 if (coercefunc
== NULL
) {
1397 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1400 return generic_binary_op(v
, w
, opname
);
1403 args
= PyTuple_Pack(1, w
);
1405 Py_DECREF(coercefunc
);
1408 coerced
= PyEval_CallObject(coercefunc
, args
);
1410 Py_DECREF(coercefunc
);
1411 if (coerced
== NULL
) {
1414 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1416 return generic_binary_op(v
, w
, opname
);
1418 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1420 PyErr_SetString(PyExc_TypeError
,
1421 "coercion should return None or 2-tuple");
1424 v1
= PyTuple_GetItem(coerced
, 0);
1425 w
= PyTuple_GetItem(coerced
, 1);
1426 if (v1
->ob_type
== v
->ob_type
&& PyInstance_Check(v
)) {
1427 /* prevent recursion if __coerce__ returns self as the first
1429 result
= generic_binary_op(v1
, w
, opname
);
1432 result
= (thisfunc
)(w
, v1
);
1434 result
= (thisfunc
)(v1
, w
);
1440 /* Implement a binary operator involving at least one class instance. */
1442 do_binop(PyObject
*v
, PyObject
*w
, char *opname
, char *ropname
,
1443 binaryfunc thisfunc
)
1445 PyObject
*result
= half_binop(v
, w
, opname
, thisfunc
, 0);
1446 if (result
== Py_NotImplemented
) {
1448 result
= half_binop(w
, v
, ropname
, thisfunc
, 1);
1454 do_binop_inplace(PyObject
*v
, PyObject
*w
, char *iopname
, char *opname
,
1455 char *ropname
, binaryfunc thisfunc
)
1457 PyObject
*result
= half_binop(v
, w
, iopname
, thisfunc
, 0);
1458 if (result
== Py_NotImplemented
) {
1460 result
= do_binop(v
, w
, opname
, ropname
, thisfunc
);
1466 instance_coerce(PyObject
**pv
, PyObject
**pw
)
1470 PyObject
*coercefunc
;
1474 if (coerce_obj
== NULL
) {
1475 coerce_obj
= PyString_InternFromString("__coerce__");
1476 if (coerce_obj
== NULL
)
1479 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1480 if (coercefunc
== NULL
) {
1481 /* No __coerce__ method */
1482 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1487 /* Has __coerce__ method: call it */
1488 args
= PyTuple_Pack(1, w
);
1492 coerced
= PyEval_CallObject(coercefunc
, args
);
1494 Py_DECREF(coercefunc
);
1495 if (coerced
== NULL
) {
1496 /* __coerce__ call raised an exception */
1499 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1500 /* __coerce__ says "I can't do it" */
1504 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1505 /* __coerce__ return value is malformed */
1507 PyErr_SetString(PyExc_TypeError
,
1508 "coercion should return None or 2-tuple");
1511 /* __coerce__ returned two new values */
1512 *pv
= PyTuple_GetItem(coerced
, 0);
1513 *pw
= PyTuple_GetItem(coerced
, 1);
1520 #define UNARY(funcname, methodname) \
1521 static PyObject *funcname(PyInstanceObject *self) { \
1522 static PyObject *o; \
1523 if (o == NULL) o = PyString_InternFromString(methodname); \
1524 return generic_unary_op(self, o); \
1527 #define BINARY(f, m, n) \
1528 static PyObject *f(PyObject *v, PyObject *w) { \
1529 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1532 #define BINARY_INPLACE(f, m, n) \
1533 static PyObject *f(PyObject *v, PyObject *w) { \
1534 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1538 UNARY(instance_neg
, "__neg__")
1539 UNARY(instance_pos
, "__pos__")
1540 UNARY(instance_abs
, "__abs__")
1542 BINARY(instance_or
, "or", PyNumber_Or
)
1543 BINARY(instance_and
, "and", PyNumber_And
)
1544 BINARY(instance_xor
, "xor", PyNumber_Xor
)
1545 BINARY(instance_lshift
, "lshift", PyNumber_Lshift
)
1546 BINARY(instance_rshift
, "rshift", PyNumber_Rshift
)
1547 BINARY(instance_add
, "add", PyNumber_Add
)
1548 BINARY(instance_sub
, "sub", PyNumber_Subtract
)
1549 BINARY(instance_mul
, "mul", PyNumber_Multiply
)
1550 BINARY(instance_div
, "div", PyNumber_Divide
)
1551 BINARY(instance_mod
, "mod", PyNumber_Remainder
)
1552 BINARY(instance_divmod
, "divmod", PyNumber_Divmod
)
1553 BINARY(instance_floordiv
, "floordiv", PyNumber_FloorDivide
)
1554 BINARY(instance_truediv
, "truediv", PyNumber_TrueDivide
)
1556 BINARY_INPLACE(instance_ior
, "or", PyNumber_InPlaceOr
)
1557 BINARY_INPLACE(instance_ixor
, "xor", PyNumber_InPlaceXor
)
1558 BINARY_INPLACE(instance_iand
, "and", PyNumber_InPlaceAnd
)
1559 BINARY_INPLACE(instance_ilshift
, "lshift", PyNumber_InPlaceLshift
)
1560 BINARY_INPLACE(instance_irshift
, "rshift", PyNumber_InPlaceRshift
)
1561 BINARY_INPLACE(instance_iadd
, "add", PyNumber_InPlaceAdd
)
1562 BINARY_INPLACE(instance_isub
, "sub", PyNumber_InPlaceSubtract
)
1563 BINARY_INPLACE(instance_imul
, "mul", PyNumber_InPlaceMultiply
)
1564 BINARY_INPLACE(instance_idiv
, "div", PyNumber_InPlaceDivide
)
1565 BINARY_INPLACE(instance_imod
, "mod", PyNumber_InPlaceRemainder
)
1566 BINARY_INPLACE(instance_ifloordiv
, "floordiv", PyNumber_InPlaceFloorDivide
)
1567 BINARY_INPLACE(instance_itruediv
, "truediv", PyNumber_InPlaceTrueDivide
)
1569 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1570 -2 for an exception;
1574 2 if this particular 3-way comparison is not implemented or undefined.
1577 half_cmp(PyObject
*v
, PyObject
*w
)
1579 static PyObject
*cmp_obj
;
1585 assert(PyInstance_Check(v
));
1587 if (cmp_obj
== NULL
) {
1588 cmp_obj
= PyString_InternFromString("__cmp__");
1589 if (cmp_obj
== NULL
)
1593 cmp_func
= PyObject_GetAttr(v
, cmp_obj
);
1594 if (cmp_func
== NULL
) {
1595 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1601 args
= PyTuple_Pack(1, w
);
1603 Py_DECREF(cmp_func
);
1607 result
= PyEval_CallObject(cmp_func
, args
);
1609 Py_DECREF(cmp_func
);
1614 if (result
== Py_NotImplemented
) {
1619 l
= PyInt_AsLong(result
);
1621 if (l
== -1 && PyErr_Occurred()) {
1622 PyErr_SetString(PyExc_TypeError
,
1623 "comparison did not return an int");
1627 return l
< 0 ? -1 : l
> 0 ? 1 : 0;
1630 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1631 We first try a coercion. Return:
1632 -2 for an exception;
1636 2 if this particular 3-way comparison is not implemented or undefined.
1637 THIS IS ONLY CALLED FROM object.c!
1640 instance_compare(PyObject
*v
, PyObject
*w
)
1644 c
= PyNumber_CoerceEx(&v
, &w
);
1648 /* If neither is now an instance, use regular comparison */
1649 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1650 c
= PyObject_Compare(v
, w
);
1653 if (PyErr_Occurred())
1655 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
1659 /* The coercion didn't do anything.
1660 Treat this the same as returning v and w unchanged. */
1665 if (PyInstance_Check(v
)) {
1673 if (PyInstance_Check(w
)) {
1689 instance_nonzero(PyInstanceObject
*self
)
1691 PyObject
*func
, *res
;
1693 static PyObject
*nonzerostr
;
1695 if (nonzerostr
== NULL
)
1696 nonzerostr
= PyString_InternFromString("__nonzero__");
1697 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1698 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1702 lenstr
= PyString_InternFromString("__len__");
1703 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1704 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1707 /* Fall back to the default behavior:
1708 all instances are nonzero */
1712 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1716 if (!PyInt_Check(res
)) {
1718 PyErr_SetString(PyExc_TypeError
,
1719 "__nonzero__ should return an int");
1722 outcome
= PyInt_AsLong(res
);
1725 PyErr_SetString(PyExc_ValueError
,
1726 "__nonzero__ should return >= 0");
1732 UNARY(instance_invert
, "__invert__")
1733 UNARY(instance_int
, "__int__")
1734 UNARY(instance_long
, "__long__")
1735 UNARY(instance_float
, "__float__")
1736 UNARY(instance_oct
, "__oct__")
1737 UNARY(instance_hex
, "__hex__")
1740 bin_power(PyObject
*v
, PyObject
*w
)
1742 return PyNumber_Power(v
, w
, Py_None
);
1745 /* This version is for ternary calls only (z != None) */
1747 instance_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1750 return do_binop(v
, w
, "__pow__", "__rpow__", bin_power
);
1757 /* XXX Doesn't do coercions... */
1758 func
= PyObject_GetAttrString(v
, "__pow__");
1761 args
= PyTuple_Pack(2, w
, z
);
1766 result
= PyEval_CallObject(func
, args
);
1774 bin_inplace_power(PyObject
*v
, PyObject
*w
)
1776 return PyNumber_InPlacePower(v
, w
, Py_None
);
1781 instance_ipow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1784 return do_binop_inplace(v
, w
, "__ipow__", "__pow__",
1785 "__rpow__", bin_inplace_power
);
1788 /* XXX Doesn't do coercions... */
1793 func
= PyObject_GetAttrString(v
, "__ipow__");
1795 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1798 return instance_pow(v
, w
, z
);
1800 args
= PyTuple_Pack(2, w
, z
);
1805 result
= PyEval_CallObject(func
, args
);
1813 /* Map rich comparison operators to their __xx__ namesakes */
1815 static PyObject
**name_op
= NULL
;
1821 char *_name_op
[] = {
1830 name_op
= (PyObject
**)malloc(sizeof(PyObject
*) * NAME_OPS
);
1831 if (name_op
== NULL
)
1833 for (i
= 0; i
< NAME_OPS
; ++i
) {
1834 name_op
[i
] = PyString_InternFromString(_name_op
[i
]);
1835 if (name_op
[i
] == NULL
)
1842 half_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1848 assert(PyInstance_Check(v
));
1850 if (name_op
== NULL
) {
1851 if (init_name_op() < 0)
1854 /* If the instance doesn't define an __getattr__ method, use
1855 instance_getattr2 directly because it will not set an
1856 exception on failure. */
1857 if (((PyInstanceObject
*)v
)->in_class
->cl_getattr
== NULL
)
1858 method
= instance_getattr2((PyInstanceObject
*)v
,
1861 method
= PyObject_GetAttr(v
, name_op
[op
]);
1862 if (method
== NULL
) {
1863 if (PyErr_Occurred()) {
1864 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1868 res
= Py_NotImplemented
;
1873 args
= PyTuple_Pack(1, w
);
1879 res
= PyEval_CallObject(method
, args
);
1887 instance_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1891 if (PyInstance_Check(v
)) {
1892 res
= half_richcompare(v
, w
, op
);
1893 if (res
!= Py_NotImplemented
)
1898 if (PyInstance_Check(w
)) {
1899 res
= half_richcompare(w
, v
, _Py_SwappedOp
[op
]);
1900 if (res
!= Py_NotImplemented
)
1905 Py_INCREF(Py_NotImplemented
);
1906 return Py_NotImplemented
;
1910 /* Get the iterator */
1912 instance_getiter(PyInstanceObject
*self
)
1916 if (iterstr
== NULL
) {
1917 iterstr
= PyString_InternFromString("__iter__");
1918 if (iterstr
== NULL
)
1921 if (getitemstr
== NULL
) {
1922 getitemstr
= PyString_InternFromString("__getitem__");
1923 if (getitemstr
== NULL
)
1927 if ((func
= instance_getattr(self
, iterstr
)) != NULL
) {
1928 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1930 if (res
!= NULL
&& !PyIter_Check(res
)) {
1931 PyErr_Format(PyExc_TypeError
,
1932 "__iter__ returned non-iterator "
1934 res
->ob_type
->tp_name
);
1940 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1943 if ((func
= instance_getattr(self
, getitemstr
)) == NULL
) {
1944 PyErr_SetString(PyExc_TypeError
,
1945 "iteration over non-sequence");
1949 return PySeqIter_New((PyObject
*)self
);
1953 /* Call the iterator's next */
1955 instance_iternext(PyInstanceObject
*self
)
1959 if (nextstr
== NULL
)
1960 nextstr
= PyString_InternFromString("next");
1962 if ((func
= instance_getattr(self
, nextstr
)) != NULL
) {
1963 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1968 if (PyErr_ExceptionMatches(PyExc_StopIteration
)) {
1974 PyErr_SetString(PyExc_TypeError
, "instance has no next() method");
1979 instance_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
1981 PyObject
*res
, *call
= PyObject_GetAttrString(func
, "__call__");
1983 PyInstanceObject
*inst
= (PyInstanceObject
*) func
;
1984 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1987 PyErr_Format(PyExc_AttributeError
,
1988 "%.200s instance has no __call__ method",
1989 PyString_AsString(inst
->in_class
->cl_name
));
1992 /* We must check and increment the recursion depth here. Scenario:
1995 A.__call__ = A() # that's right
1997 a() # infinite recursion
1998 This bounces between instance_call() and PyObject_Call() without
1999 ever hitting eval_frame() (which has the main recursion check). */
2000 if (Py_EnterRecursiveCall(" in __call__")) {
2004 res
= PyObject_Call(call
, arg
, kw
);
2005 Py_LeaveRecursiveCall();
2012 static PyNumberMethods instance_as_number
= {
2013 (binaryfunc
)instance_add
, /* nb_add */
2014 (binaryfunc
)instance_sub
, /* nb_subtract */
2015 (binaryfunc
)instance_mul
, /* nb_multiply */
2016 (binaryfunc
)instance_div
, /* nb_divide */
2017 (binaryfunc
)instance_mod
, /* nb_remainder */
2018 (binaryfunc
)instance_divmod
, /* nb_divmod */
2019 (ternaryfunc
)instance_pow
, /* nb_power */
2020 (unaryfunc
)instance_neg
, /* nb_negative */
2021 (unaryfunc
)instance_pos
, /* nb_positive */
2022 (unaryfunc
)instance_abs
, /* nb_absolute */
2023 (inquiry
)instance_nonzero
, /* nb_nonzero */
2024 (unaryfunc
)instance_invert
, /* nb_invert */
2025 (binaryfunc
)instance_lshift
, /* nb_lshift */
2026 (binaryfunc
)instance_rshift
, /* nb_rshift */
2027 (binaryfunc
)instance_and
, /* nb_and */
2028 (binaryfunc
)instance_xor
, /* nb_xor */
2029 (binaryfunc
)instance_or
, /* nb_or */
2030 (coercion
)instance_coerce
, /* nb_coerce */
2031 (unaryfunc
)instance_int
, /* nb_int */
2032 (unaryfunc
)instance_long
, /* nb_long */
2033 (unaryfunc
)instance_float
, /* nb_float */
2034 (unaryfunc
)instance_oct
, /* nb_oct */
2035 (unaryfunc
)instance_hex
, /* nb_hex */
2036 (binaryfunc
)instance_iadd
, /* nb_inplace_add */
2037 (binaryfunc
)instance_isub
, /* nb_inplace_subtract */
2038 (binaryfunc
)instance_imul
, /* nb_inplace_multiply */
2039 (binaryfunc
)instance_idiv
, /* nb_inplace_divide */
2040 (binaryfunc
)instance_imod
, /* nb_inplace_remainder */
2041 (ternaryfunc
)instance_ipow
, /* nb_inplace_power */
2042 (binaryfunc
)instance_ilshift
, /* nb_inplace_lshift */
2043 (binaryfunc
)instance_irshift
, /* nb_inplace_rshift */
2044 (binaryfunc
)instance_iand
, /* nb_inplace_and */
2045 (binaryfunc
)instance_ixor
, /* nb_inplace_xor */
2046 (binaryfunc
)instance_ior
, /* nb_inplace_or */
2047 (binaryfunc
)instance_floordiv
, /* nb_floor_divide */
2048 (binaryfunc
)instance_truediv
, /* nb_true_divide */
2049 (binaryfunc
)instance_ifloordiv
, /* nb_inplace_floor_divide */
2050 (binaryfunc
)instance_itruediv
, /* nb_inplace_true_divide */
2053 PyTypeObject PyInstance_Type
= {
2054 PyObject_HEAD_INIT(&PyType_Type
)
2057 sizeof(PyInstanceObject
),
2059 (destructor
)instance_dealloc
, /* tp_dealloc */
2063 instance_compare
, /* tp_compare */
2064 (reprfunc
)instance_repr
, /* tp_repr */
2065 &instance_as_number
, /* tp_as_number */
2066 &instance_as_sequence
, /* tp_as_sequence */
2067 &instance_as_mapping
, /* tp_as_mapping */
2068 (hashfunc
)instance_hash
, /* tp_hash */
2069 instance_call
, /* tp_call */
2070 (reprfunc
)instance_str
, /* tp_str */
2071 (getattrofunc
)instance_getattr
, /* tp_getattro */
2072 (setattrofunc
)instance_setattr
, /* tp_setattro */
2073 0, /* tp_as_buffer */
2074 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
,/*tp_flags*/
2075 instance_doc
, /* tp_doc */
2076 (traverseproc
)instance_traverse
, /* tp_traverse */
2078 instance_richcompare
, /* tp_richcompare */
2079 offsetof(PyInstanceObject
, in_weakreflist
), /* tp_weaklistoffset */
2080 (getiterfunc
)instance_getiter
, /* tp_iter */
2081 (iternextfunc
)instance_iternext
, /* tp_iternext */
2087 0, /* tp_descr_get */
2088 0, /* tp_descr_set */
2089 0, /* tp_dictoffset */
2092 instance_new
, /* tp_new */
2096 /* Instance method objects are used for two purposes:
2097 (a) as bound instance methods (returned by instancename.methodname)
2098 (b) as unbound methods (returned by ClassName.methodname)
2099 In case (b), im_self is NULL
2102 static PyMethodObject
*free_list
;
2105 PyMethod_New(PyObject
*func
, PyObject
*self
, PyObject
*class)
2107 register PyMethodObject
*im
;
2108 if (!PyCallable_Check(func
)) {
2109 PyErr_BadInternalCall();
2114 free_list
= (PyMethodObject
*)(im
->im_self
);
2115 PyObject_INIT(im
, &PyMethod_Type
);
2118 im
= PyObject_GC_New(PyMethodObject
, &PyMethod_Type
);
2122 im
->im_weakreflist
= NULL
;
2128 im
->im_class
= class;
2129 _PyObject_GC_TRACK(im
);
2130 return (PyObject
*)im
;
2133 /* Descriptors for PyMethod attributes */
2135 /* im_class, im_func and im_self are stored in the PyMethod object */
2137 #define OFF(x) offsetof(PyMethodObject, x)
2139 static PyMemberDef instancemethod_memberlist
[] = {
2140 {"im_class", T_OBJECT
, OFF(im_class
), READONLY
|RESTRICTED
,
2141 "the class associated with a method"},
2142 {"im_func", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2143 "the function (or other callable) implementing a method"},
2144 {"im_self", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2145 "the instance to which a method is bound; None for unbound methods"},
2146 {NULL
} /* Sentinel */
2149 /* Christian Tismer argued convincingly that method attributes should
2150 (nearly) always override function attributes.
2151 The one exception is __doc__; there's a default __doc__ which
2152 should only be used for the class, not for instances */
2155 instancemethod_get_doc(PyMethodObject
*im
, void *context
)
2157 static PyObject
*docstr
;
2158 if (docstr
== NULL
) {
2159 docstr
= PyString_InternFromString("__doc__");
2163 return PyObject_GetAttr(im
->im_func
, docstr
);
2166 static PyGetSetDef instancemethod_getset
[] = {
2167 {"__doc__", (getter
)instancemethod_get_doc
, NULL
, NULL
},
2172 instancemethod_getattro(PyObject
*obj
, PyObject
*name
)
2174 PyMethodObject
*im
= (PyMethodObject
*)obj
;
2175 PyTypeObject
*tp
= obj
->ob_type
;
2176 PyObject
*descr
= NULL
;
2178 if (PyType_HasFeature(tp
, Py_TPFLAGS_HAVE_CLASS
)) {
2179 if (tp
->tp_dict
== NULL
) {
2180 if (PyType_Ready(tp
) < 0)
2183 descr
= _PyType_Lookup(tp
, name
);
2186 if (descr
!= NULL
) {
2187 descrgetfunc f
= TP_DESCR_GET(descr
->ob_type
);
2189 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2196 return PyObject_GetAttr(im
->im_func
, name
);
2199 PyDoc_STRVAR(instancemethod_doc
,
2200 "instancemethod(function, instance, class)\n\
2202 Create an instance method object.");
2205 instancemethod_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
2209 PyObject
*classObj
= NULL
;
2211 if (!PyArg_UnpackTuple(args
, "instancemethod", 2, 3,
2212 &func
, &self
, &classObj
))
2214 if (!PyCallable_Check(func
)) {
2215 PyErr_SetString(PyExc_TypeError
,
2216 "first argument must be callable");
2219 if (self
== Py_None
)
2221 if (self
== NULL
&& classObj
== NULL
) {
2222 PyErr_SetString(PyExc_TypeError
,
2223 "unbound methods must have non-NULL im_class");
2227 return PyMethod_New(func
, self
, classObj
);
2231 instancemethod_dealloc(register PyMethodObject
*im
)
2233 _PyObject_GC_UNTRACK(im
);
2234 if (im
->im_weakreflist
!= NULL
)
2235 PyObject_ClearWeakRefs((PyObject
*)im
);
2236 Py_DECREF(im
->im_func
);
2237 Py_XDECREF(im
->im_self
);
2238 Py_XDECREF(im
->im_class
);
2239 im
->im_self
= (PyObject
*)free_list
;
2244 instancemethod_compare(PyMethodObject
*a
, PyMethodObject
*b
)
2246 if (a
->im_self
!= b
->im_self
)
2247 return (a
->im_self
< b
->im_self
) ? -1 : 1;
2248 return PyObject_Compare(a
->im_func
, b
->im_func
);
2252 instancemethod_repr(PyMethodObject
*a
)
2254 PyObject
*self
= a
->im_self
;
2255 PyObject
*func
= a
->im_func
;
2256 PyObject
*klass
= a
->im_class
;
2257 PyObject
*funcname
= NULL
, *klassname
= NULL
, *result
= NULL
;
2258 char *sfuncname
= "?", *sklassname
= "?";
2260 funcname
= PyObject_GetAttrString(func
, "__name__");
2261 if (funcname
== NULL
) {
2262 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2266 else if (!PyString_Check(funcname
)) {
2267 Py_DECREF(funcname
);
2271 sfuncname
= PyString_AS_STRING(funcname
);
2275 klassname
= PyObject_GetAttrString(klass
, "__name__");
2276 if (klassname
== NULL
) {
2277 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2281 else if (!PyString_Check(klassname
)) {
2282 Py_DECREF(klassname
);
2286 sklassname
= PyString_AS_STRING(klassname
);
2289 result
= PyString_FromFormat("<unbound method %s.%s>",
2290 sklassname
, sfuncname
);
2292 /* XXX Shouldn't use repr() here! */
2293 PyObject
*selfrepr
= PyObject_Repr(self
);
2294 if (selfrepr
== NULL
)
2296 if (!PyString_Check(selfrepr
)) {
2297 Py_DECREF(selfrepr
);
2300 result
= PyString_FromFormat("<bound method %s.%s of %s>",
2301 sklassname
, sfuncname
,
2302 PyString_AS_STRING(selfrepr
));
2303 Py_DECREF(selfrepr
);
2306 Py_XDECREF(funcname
);
2307 Py_XDECREF(klassname
);
2312 instancemethod_hash(PyMethodObject
*a
)
2315 if (a
->im_self
== NULL
)
2316 x
= PyObject_Hash(Py_None
);
2318 x
= PyObject_Hash(a
->im_self
);
2321 y
= PyObject_Hash(a
->im_func
);
2328 instancemethod_traverse(PyMethodObject
*im
, visitproc visit
, void *arg
)
2332 err
= visit(im
->im_func
, arg
);
2337 err
= visit(im
->im_self
, arg
);
2342 err
= visit(im
->im_class
, arg
);
2350 getclassname(PyObject
*class, char *buf
, int bufsize
)
2354 assert(bufsize
> 1);
2355 strcpy(buf
, "?"); /* Default outcome */
2358 name
= PyObject_GetAttrString(class, "__name__");
2360 /* This function cannot return an exception */
2364 if (PyString_Check(name
)) {
2365 strncpy(buf
, PyString_AS_STRING(name
), bufsize
);
2366 buf
[bufsize
-1] = '\0';
2372 getinstclassname(PyObject
*inst
, char *buf
, int bufsize
)
2377 assert(bufsize
> 0 && (size_t)bufsize
> strlen("nothing"));
2378 strcpy(buf
, "nothing");
2382 class = PyObject_GetAttrString(inst
, "__class__");
2383 if (class == NULL
) {
2384 /* This function cannot return an exception */
2386 class = (PyObject
*)(inst
->ob_type
);
2389 getclassname(class, buf
, bufsize
);
2394 instancemethod_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2396 PyObject
*self
= PyMethod_GET_SELF(func
);
2397 PyObject
*class = PyMethod_GET_CLASS(func
);
2400 func
= PyMethod_GET_FUNCTION(func
);
2402 /* Unbound methods must be called with an instance of
2403 the class (or a derived class) as first argument */
2405 if (PyTuple_Size(arg
) >= 1)
2406 self
= PyTuple_GET_ITEM(arg
, 0);
2410 ok
= PyObject_IsInstance(self
, class);
2417 getclassname(class, clsbuf
, sizeof(clsbuf
));
2418 getinstclassname(self
, instbuf
, sizeof(instbuf
));
2419 PyErr_Format(PyExc_TypeError
,
2420 "unbound method %s%s must be called with "
2421 "%s instance as first argument "
2422 "(got %s%s instead)",
2423 PyEval_GetFuncName(func
),
2424 PyEval_GetFuncDesc(func
),
2427 self
== NULL
? "" : " instance");
2433 int argcount
= PyTuple_Size(arg
);
2434 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2439 PyTuple_SET_ITEM(newarg
, 0, self
);
2440 for (i
= 0; i
< argcount
; i
++) {
2441 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2443 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2447 result
= PyObject_Call((PyObject
*)func
, arg
, kw
);
2453 instancemethod_descr_get(PyObject
*meth
, PyObject
*obj
, PyObject
*cls
)
2455 /* Don't rebind an already bound method, or an unbound method
2456 of a class that's not a base class of cls. */
2458 if (PyMethod_GET_SELF(meth
) != NULL
) {
2463 /* No, it is an unbound method */
2464 if (PyMethod_GET_CLASS(meth
) != NULL
&& cls
!= NULL
) {
2465 /* Do subclass test. If it fails, return meth unchanged. */
2466 int ok
= PyObject_IsSubclass(cls
, PyMethod_GET_CLASS(meth
));
2474 /* Bind it to obj */
2475 return PyMethod_New(PyMethod_GET_FUNCTION(meth
), obj
, cls
);
2478 PyTypeObject PyMethod_Type
= {
2479 PyObject_HEAD_INIT(&PyType_Type
)
2482 sizeof(PyMethodObject
),
2484 (destructor
)instancemethod_dealloc
, /* tp_dealloc */
2488 (cmpfunc
)instancemethod_compare
, /* tp_compare */
2489 (reprfunc
)instancemethod_repr
, /* tp_repr */
2490 0, /* tp_as_number */
2491 0, /* tp_as_sequence */
2492 0, /* tp_as_mapping */
2493 (hashfunc
)instancemethod_hash
, /* tp_hash */
2494 instancemethod_call
, /* tp_call */
2496 (getattrofunc
)instancemethod_getattro
, /* tp_getattro */
2497 PyObject_GenericSetAttr
, /* tp_setattro */
2498 0, /* tp_as_buffer */
2499 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
2500 instancemethod_doc
, /* tp_doc */
2501 (traverseproc
)instancemethod_traverse
, /* tp_traverse */
2503 0, /* tp_richcompare */
2504 offsetof(PyMethodObject
, im_weakreflist
), /* tp_weaklistoffset */
2506 0, /* tp_iternext */
2508 instancemethod_memberlist
, /* tp_members */
2509 instancemethod_getset
, /* tp_getset */
2512 instancemethod_descr_get
, /* tp_descr_get */
2513 0, /* tp_descr_set */
2514 0, /* tp_dictoffset */
2517 instancemethod_new
, /* tp_new */
2520 /* Clear out the free list */
2526 PyMethodObject
*im
= free_list
;
2527 free_list
= (PyMethodObject
*)(im
->im_self
);
2528 PyObject_GC_Del(im
);