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 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, the original decref dropped _Py_RefTotal,
674 * but _Py_NewReference bumped it again, so that's a wash.
675 * If Py_TRACE_REFS, _Py_NewReference re-added self to the
676 * object chain, so no more to do there either.
677 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
678 * _Py_NewReference bumped tp_allocs: both of those need to
682 --inst
->ob_type
->tp_frees
;
683 --inst
->ob_type
->tp_allocs
;
689 instance_getattr1(register PyInstanceObject
*inst
, PyObject
*name
)
691 register PyObject
*v
;
692 register char *sname
= PyString_AsString(name
);
693 if (sname
[0] == '_' && sname
[1] == '_') {
694 if (strcmp(sname
, "__dict__") == 0) {
695 if (PyEval_GetRestricted()) {
696 PyErr_SetString(PyExc_RuntimeError
,
697 "instance.__dict__ not accessible in restricted mode");
700 Py_INCREF(inst
->in_dict
);
701 return inst
->in_dict
;
703 if (strcmp(sname
, "__class__") == 0) {
704 Py_INCREF(inst
->in_class
);
705 return (PyObject
*)inst
->in_class
;
708 v
= instance_getattr2(inst
, name
);
709 if (v
== NULL
&& !PyErr_Occurred()) {
710 PyErr_Format(PyExc_AttributeError
,
711 "%.50s instance has no attribute '%.400s'",
712 PyString_AS_STRING(inst
->in_class
->cl_name
), sname
);
718 instance_getattr2(register PyInstanceObject
*inst
, PyObject
*name
)
720 register PyObject
*v
;
721 PyClassObject
*class;
724 v
= PyDict_GetItem(inst
->in_dict
, name
);
729 v
= class_lookup(inst
->in_class
, name
, &class);
732 f
= TP_DESCR_GET(v
->ob_type
);
734 PyObject
*w
= f(v
, (PyObject
*)inst
,
735 (PyObject
*)(inst
->in_class
));
744 instance_getattr(register PyInstanceObject
*inst
, PyObject
*name
)
746 register PyObject
*func
, *res
;
747 res
= instance_getattr1(inst
, name
);
748 if (res
== NULL
&& (func
= inst
->in_class
->cl_getattr
) != NULL
) {
750 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
753 args
= Py_BuildValue("(OO)", inst
, name
);
756 res
= PyEval_CallObject(func
, args
);
762 /* See classobject.h comments: this only does dict lookups, and is always
766 _PyInstance_Lookup(PyObject
*pinst
, PyObject
*name
)
769 PyClassObject
*class;
770 PyInstanceObject
*inst
; /* pinst cast to the right type */
772 assert(PyInstance_Check(pinst
));
773 inst
= (PyInstanceObject
*)pinst
;
775 assert(PyString_Check(name
));
777 v
= PyDict_GetItem(inst
->in_dict
, name
);
779 v
= class_lookup(inst
->in_class
, name
, &class);
784 instance_setattr1(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
787 int rv
= PyDict_DelItem(inst
->in_dict
, name
);
789 PyErr_Format(PyExc_AttributeError
,
790 "%.50s instance has no attribute '%.400s'",
791 PyString_AS_STRING(inst
->in_class
->cl_name
),
792 PyString_AS_STRING(name
));
796 return PyDict_SetItem(inst
->in_dict
, name
, v
);
800 instance_setattr(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
802 PyObject
*func
, *args
, *res
, *tmp
;
803 char *sname
= PyString_AsString(name
);
804 if (sname
[0] == '_' && sname
[1] == '_') {
805 int n
= PyString_Size(name
);
806 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
807 if (strcmp(sname
, "__dict__") == 0) {
808 if (PyEval_GetRestricted()) {
809 PyErr_SetString(PyExc_RuntimeError
,
810 "__dict__ not accessible in restricted mode");
813 if (v
== NULL
|| !PyDict_Check(v
)) {
814 PyErr_SetString(PyExc_TypeError
,
815 "__dict__ must be set to a dictionary");
824 if (strcmp(sname
, "__class__") == 0) {
825 if (PyEval_GetRestricted()) {
826 PyErr_SetString(PyExc_RuntimeError
,
827 "__class__ not accessible in restricted mode");
830 if (v
== NULL
|| !PyClass_Check(v
)) {
831 PyErr_SetString(PyExc_TypeError
,
832 "__class__ must be set to a class");
835 tmp
= (PyObject
*)(inst
->in_class
);
837 inst
->in_class
= (PyClassObject
*)v
;
844 func
= inst
->in_class
->cl_delattr
;
846 func
= inst
->in_class
->cl_setattr
;
848 return instance_setattr1(inst
, name
, v
);
850 args
= Py_BuildValue("(OO)", inst
, name
);
852 args
= Py_BuildValue("(OOO)", inst
, name
, v
);
855 res
= PyEval_CallObject(func
, args
);
864 instance_repr(PyInstanceObject
*inst
)
868 static PyObject
*reprstr
;
871 reprstr
= PyString_InternFromString("__repr__");
872 func
= instance_getattr(inst
, reprstr
);
874 PyObject
*classname
, *mod
;
876 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
879 classname
= inst
->in_class
->cl_name
;
880 mod
= PyDict_GetItemString(inst
->in_class
->cl_dict
,
882 if (classname
!= NULL
&& PyString_Check(classname
))
883 cname
= PyString_AsString(classname
);
886 if (mod
== NULL
|| !PyString_Check(mod
))
887 return PyString_FromFormat("<?.%s instance at %p>",
890 return PyString_FromFormat("<%s.%s instance at %p>",
891 PyString_AsString(mod
),
894 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
900 instance_str(PyInstanceObject
*inst
)
904 static PyObject
*strstr
;
907 strstr
= PyString_InternFromString("__str__");
908 func
= instance_getattr(inst
, strstr
);
910 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
913 return instance_repr(inst
);
915 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
921 instance_hash(PyInstanceObject
*inst
)
926 static PyObject
*hashstr
, *eqstr
, *cmpstr
;
929 hashstr
= PyString_InternFromString("__hash__");
930 func
= instance_getattr(inst
, hashstr
);
932 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
935 /* If there is no __eq__ and no __cmp__ method, we hash on the
936 address. If an __eq__ or __cmp__ method exists, there must
939 eqstr
= PyString_InternFromString("__eq__");
940 func
= instance_getattr(inst
, eqstr
);
942 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
946 cmpstr
= PyString_InternFromString("__cmp__");
947 func
= instance_getattr(inst
, cmpstr
);
949 if (!PyErr_ExceptionMatches(
950 PyExc_AttributeError
))
953 return _Py_HashPointer(inst
);
956 PyErr_SetString(PyExc_TypeError
, "unhashable instance");
959 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
963 if (PyInt_Check(res
)) {
964 outcome
= PyInt_AsLong(res
);
969 PyErr_SetString(PyExc_TypeError
,
970 "__hash__() should return an int");
978 instance_traverse(PyInstanceObject
*o
, visitproc visit
, void *arg
)
982 err
= visit((PyObject
*)(o
->in_class
), arg
);
987 err
= visit(o
->in_dict
, arg
);
994 static PyObject
*getitemstr
, *setitemstr
, *delitemstr
, *lenstr
;
995 static PyObject
*iterstr
, *nextstr
;
998 instance_length(PyInstanceObject
*inst
)
1005 lenstr
= PyString_InternFromString("__len__");
1006 func
= instance_getattr(inst
, lenstr
);
1009 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1013 if (PyInt_Check(res
)) {
1014 outcome
= PyInt_AsLong(res
);
1016 PyErr_SetString(PyExc_ValueError
,
1017 "__len__() should return >= 0");
1020 PyErr_SetString(PyExc_TypeError
,
1021 "__len__() should return an int");
1029 instance_subscript(PyInstanceObject
*inst
, PyObject
*key
)
1035 if (getitemstr
== NULL
)
1036 getitemstr
= PyString_InternFromString("__getitem__");
1037 func
= instance_getattr(inst
, getitemstr
);
1040 arg
= Py_BuildValue("(O)", key
);
1045 res
= PyEval_CallObject(func
, arg
);
1052 instance_ass_subscript(PyInstanceObject
*inst
, PyObject
*key
, PyObject
*value
)
1058 if (value
== NULL
) {
1059 if (delitemstr
== NULL
)
1060 delitemstr
= PyString_InternFromString("__delitem__");
1061 func
= instance_getattr(inst
, delitemstr
);
1064 if (setitemstr
== NULL
)
1065 setitemstr
= PyString_InternFromString("__setitem__");
1066 func
= instance_getattr(inst
, setitemstr
);
1071 arg
= Py_BuildValue("(O)", key
);
1073 arg
= Py_BuildValue("(OO)", key
, value
);
1078 res
= PyEval_CallObject(func
, arg
);
1087 static PyMappingMethods instance_as_mapping
= {
1088 (inquiry
)instance_length
, /* mp_length */
1089 (binaryfunc
)instance_subscript
, /* mp_subscript */
1090 (objobjargproc
)instance_ass_subscript
, /* mp_ass_subscript */
1094 instance_item(PyInstanceObject
*inst
, int i
)
1096 PyObject
*func
, *arg
, *res
;
1098 if (getitemstr
== NULL
)
1099 getitemstr
= PyString_InternFromString("__getitem__");
1100 func
= instance_getattr(inst
, getitemstr
);
1103 arg
= Py_BuildValue("(i)", i
);
1108 res
= PyEval_CallObject(func
, arg
);
1115 sliceobj_from_intint(int i
, int j
)
1117 PyObject
*start
, *end
, *res
;
1119 start
= PyInt_FromLong((long)i
);
1123 end
= PyInt_FromLong((long)j
);
1128 res
= PySlice_New(start
, end
, NULL
);
1136 instance_slice(PyInstanceObject
*inst
, int i
, int j
)
1138 PyObject
*func
, *arg
, *res
;
1139 static PyObject
*getslicestr
;
1141 if (getslicestr
== NULL
)
1142 getslicestr
= PyString_InternFromString("__getslice__");
1143 func
= instance_getattr(inst
, getslicestr
);
1146 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1150 if (getitemstr
== NULL
)
1151 getitemstr
= PyString_InternFromString("__getitem__");
1152 func
= instance_getattr(inst
, getitemstr
);
1155 arg
= Py_BuildValue("(N)", sliceobj_from_intint(i
, j
));
1157 arg
= Py_BuildValue("(ii)", i
, j
);
1163 res
= PyEval_CallObject(func
, arg
);
1170 instance_ass_item(PyInstanceObject
*inst
, int i
, PyObject
*item
)
1172 PyObject
*func
, *arg
, *res
;
1175 if (delitemstr
== NULL
)
1176 delitemstr
= PyString_InternFromString("__delitem__");
1177 func
= instance_getattr(inst
, delitemstr
);
1180 if (setitemstr
== NULL
)
1181 setitemstr
= PyString_InternFromString("__setitem__");
1182 func
= instance_getattr(inst
, setitemstr
);
1187 arg
= Py_BuildValue("i", i
);
1189 arg
= Py_BuildValue("(iO)", i
, item
);
1194 res
= PyEval_CallObject(func
, arg
);
1204 instance_ass_slice(PyInstanceObject
*inst
, int i
, int j
, PyObject
*value
)
1206 PyObject
*func
, *arg
, *res
;
1207 static PyObject
*setslicestr
, *delslicestr
;
1209 if (value
== NULL
) {
1210 if (delslicestr
== NULL
)
1212 PyString_InternFromString("__delslice__");
1213 func
= instance_getattr(inst
, delslicestr
);
1215 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1218 if (delitemstr
== NULL
)
1220 PyString_InternFromString("__delitem__");
1221 func
= instance_getattr(inst
, delitemstr
);
1225 arg
= Py_BuildValue("(N)",
1226 sliceobj_from_intint(i
, j
));
1228 arg
= Py_BuildValue("(ii)", i
, j
);
1231 if (setslicestr
== NULL
)
1233 PyString_InternFromString("__setslice__");
1234 func
= instance_getattr(inst
, setslicestr
);
1236 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1239 if (setitemstr
== NULL
)
1241 PyString_InternFromString("__setitem__");
1242 func
= instance_getattr(inst
, setitemstr
);
1246 arg
= Py_BuildValue("(NO)",
1247 sliceobj_from_intint(i
, j
), value
);
1249 arg
= Py_BuildValue("(iiO)", i
, j
, value
);
1255 res
= PyEval_CallObject(func
, arg
);
1265 instance_contains(PyInstanceObject
*inst
, PyObject
*member
)
1267 static PyObject
*__contains__
;
1270 /* Try __contains__ first.
1271 * If that can't be done, try iterator-based searching.
1274 if(__contains__
== NULL
) {
1275 __contains__
= PyString_InternFromString("__contains__");
1276 if(__contains__
== NULL
)
1279 func
= instance_getattr(inst
, __contains__
);
1283 PyObject
*arg
= Py_BuildValue("(O)", member
);
1288 res
= PyEval_CallObject(func
, arg
);
1293 ret
= PyObject_IsTrue(res
);
1298 /* Couldn't find __contains__. */
1299 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1300 /* Assume the failure was simply due to that there is no
1301 * __contains__ attribute, and try iterating instead.
1304 return _PySequence_IterSearch((PyObject
*)inst
, member
,
1305 PY_ITERSEARCH_CONTAINS
);
1311 static PySequenceMethods
1312 instance_as_sequence
= {
1313 (inquiry
)instance_length
, /* sq_length */
1316 (intargfunc
)instance_item
, /* sq_item */
1317 (intintargfunc
)instance_slice
, /* sq_slice */
1318 (intobjargproc
)instance_ass_item
, /* sq_ass_item */
1319 (intintobjargproc
)instance_ass_slice
, /* sq_ass_slice */
1320 (objobjproc
)instance_contains
, /* sq_contains */
1324 generic_unary_op(PyInstanceObject
*self
, PyObject
*methodname
)
1326 PyObject
*func
, *res
;
1328 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1330 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1336 generic_binary_op(PyObject
*v
, PyObject
*w
, char *opname
)
1340 PyObject
*func
= PyObject_GetAttrString(v
, opname
);
1342 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1345 Py_INCREF(Py_NotImplemented
);
1346 return Py_NotImplemented
;
1348 args
= Py_BuildValue("(O)", w
);
1353 result
= PyEval_CallObject(func
, args
);
1360 static PyObject
*coerce_obj
;
1362 /* Try one half of a binary operator involving a class instance. */
1364 half_binop(PyObject
*v
, PyObject
*w
, char *opname
, binaryfunc thisfunc
,
1368 PyObject
*coercefunc
;
1369 PyObject
*coerced
= NULL
;
1373 if (!PyInstance_Check(v
)) {
1374 Py_INCREF(Py_NotImplemented
);
1375 return Py_NotImplemented
;
1378 if (coerce_obj
== NULL
) {
1379 coerce_obj
= PyString_InternFromString("__coerce__");
1380 if (coerce_obj
== NULL
)
1383 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1384 if (coercefunc
== NULL
) {
1385 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1388 return generic_binary_op(v
, w
, opname
);
1391 args
= Py_BuildValue("(O)", w
);
1393 Py_DECREF(coercefunc
);
1396 coerced
= PyEval_CallObject(coercefunc
, args
);
1398 Py_DECREF(coercefunc
);
1399 if (coerced
== NULL
) {
1402 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1404 return generic_binary_op(v
, w
, opname
);
1406 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1408 PyErr_SetString(PyExc_TypeError
,
1409 "coercion should return None or 2-tuple");
1412 v1
= PyTuple_GetItem(coerced
, 0);
1413 w
= PyTuple_GetItem(coerced
, 1);
1414 if (v1
->ob_type
== v
->ob_type
&& PyInstance_Check(v
)) {
1415 /* prevent recursion if __coerce__ returns self as the first
1417 result
= generic_binary_op(v1
, w
, opname
);
1420 result
= (thisfunc
)(w
, v1
);
1422 result
= (thisfunc
)(v1
, w
);
1428 /* Implement a binary operator involving at least one class instance. */
1430 do_binop(PyObject
*v
, PyObject
*w
, char *opname
, char *ropname
,
1431 binaryfunc thisfunc
)
1433 PyObject
*result
= half_binop(v
, w
, opname
, thisfunc
, 0);
1434 if (result
== Py_NotImplemented
) {
1436 result
= half_binop(w
, v
, ropname
, thisfunc
, 1);
1442 do_binop_inplace(PyObject
*v
, PyObject
*w
, char *iopname
, char *opname
,
1443 char *ropname
, binaryfunc thisfunc
)
1445 PyObject
*result
= half_binop(v
, w
, iopname
, thisfunc
, 0);
1446 if (result
== Py_NotImplemented
) {
1448 result
= do_binop(v
, w
, opname
, ropname
, thisfunc
);
1454 instance_coerce(PyObject
**pv
, PyObject
**pw
)
1458 PyObject
*coercefunc
;
1462 if (coerce_obj
== NULL
) {
1463 coerce_obj
= PyString_InternFromString("__coerce__");
1464 if (coerce_obj
== NULL
)
1467 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1468 if (coercefunc
== NULL
) {
1469 /* No __coerce__ method */
1470 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1475 /* Has __coerce__ method: call it */
1476 args
= Py_BuildValue("(O)", w
);
1480 coerced
= PyEval_CallObject(coercefunc
, args
);
1482 Py_DECREF(coercefunc
);
1483 if (coerced
== NULL
) {
1484 /* __coerce__ call raised an exception */
1487 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1488 /* __coerce__ says "I can't do it" */
1492 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1493 /* __coerce__ return value is malformed */
1495 PyErr_SetString(PyExc_TypeError
,
1496 "coercion should return None or 2-tuple");
1499 /* __coerce__ returned two new values */
1500 *pv
= PyTuple_GetItem(coerced
, 0);
1501 *pw
= PyTuple_GetItem(coerced
, 1);
1508 #define UNARY(funcname, methodname) \
1509 static PyObject *funcname(PyInstanceObject *self) { \
1510 static PyObject *o; \
1511 if (o == NULL) o = PyString_InternFromString(methodname); \
1512 return generic_unary_op(self, o); \
1515 #define BINARY(f, m, n) \
1516 static PyObject *f(PyObject *v, PyObject *w) { \
1517 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1520 #define BINARY_INPLACE(f, m, n) \
1521 static PyObject *f(PyObject *v, PyObject *w) { \
1522 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1526 UNARY(instance_neg
, "__neg__")
1527 UNARY(instance_pos
, "__pos__")
1528 UNARY(instance_abs
, "__abs__")
1530 BINARY(instance_or
, "or", PyNumber_Or
)
1531 BINARY(instance_and
, "and", PyNumber_And
)
1532 BINARY(instance_xor
, "xor", PyNumber_Xor
)
1533 BINARY(instance_lshift
, "lshift", PyNumber_Lshift
)
1534 BINARY(instance_rshift
, "rshift", PyNumber_Rshift
)
1535 BINARY(instance_add
, "add", PyNumber_Add
)
1536 BINARY(instance_sub
, "sub", PyNumber_Subtract
)
1537 BINARY(instance_mul
, "mul", PyNumber_Multiply
)
1538 BINARY(instance_div
, "div", PyNumber_Divide
)
1539 BINARY(instance_mod
, "mod", PyNumber_Remainder
)
1540 BINARY(instance_divmod
, "divmod", PyNumber_Divmod
)
1541 BINARY(instance_floordiv
, "floordiv", PyNumber_FloorDivide
)
1542 BINARY(instance_truediv
, "truediv", PyNumber_TrueDivide
)
1544 BINARY_INPLACE(instance_ior
, "or", PyNumber_InPlaceOr
)
1545 BINARY_INPLACE(instance_ixor
, "xor", PyNumber_InPlaceXor
)
1546 BINARY_INPLACE(instance_iand
, "and", PyNumber_InPlaceAnd
)
1547 BINARY_INPLACE(instance_ilshift
, "lshift", PyNumber_InPlaceLshift
)
1548 BINARY_INPLACE(instance_irshift
, "rshift", PyNumber_InPlaceRshift
)
1549 BINARY_INPLACE(instance_iadd
, "add", PyNumber_InPlaceAdd
)
1550 BINARY_INPLACE(instance_isub
, "sub", PyNumber_InPlaceSubtract
)
1551 BINARY_INPLACE(instance_imul
, "mul", PyNumber_InPlaceMultiply
)
1552 BINARY_INPLACE(instance_idiv
, "div", PyNumber_InPlaceDivide
)
1553 BINARY_INPLACE(instance_imod
, "mod", PyNumber_InPlaceRemainder
)
1554 BINARY_INPLACE(instance_ifloordiv
, "floordiv", PyNumber_InPlaceFloorDivide
)
1555 BINARY_INPLACE(instance_itruediv
, "truediv", PyNumber_InPlaceTrueDivide
)
1557 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1558 -2 for an exception;
1562 2 if this particular 3-way comparison is not implemented or undefined.
1565 half_cmp(PyObject
*v
, PyObject
*w
)
1567 static PyObject
*cmp_obj
;
1573 assert(PyInstance_Check(v
));
1575 if (cmp_obj
== NULL
) {
1576 cmp_obj
= PyString_InternFromString("__cmp__");
1577 if (cmp_obj
== NULL
)
1581 cmp_func
= PyObject_GetAttr(v
, cmp_obj
);
1582 if (cmp_func
== NULL
) {
1583 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1589 args
= Py_BuildValue("(O)", w
);
1591 Py_DECREF(cmp_func
);
1595 result
= PyEval_CallObject(cmp_func
, args
);
1597 Py_DECREF(cmp_func
);
1602 if (result
== Py_NotImplemented
) {
1607 l
= PyInt_AsLong(result
);
1609 if (l
== -1 && PyErr_Occurred()) {
1610 PyErr_SetString(PyExc_TypeError
,
1611 "comparison did not return an int");
1615 return l
< 0 ? -1 : l
> 0 ? 1 : 0;
1618 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1619 We first try a coercion. Return:
1620 -2 for an exception;
1624 2 if this particular 3-way comparison is not implemented or undefined.
1625 THIS IS ONLY CALLED FROM object.c!
1628 instance_compare(PyObject
*v
, PyObject
*w
)
1632 c
= PyNumber_CoerceEx(&v
, &w
);
1636 /* If neither is now an instance, use regular comparison */
1637 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1638 c
= PyObject_Compare(v
, w
);
1641 if (PyErr_Occurred())
1643 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
1647 /* The coercion didn't do anything.
1648 Treat this the same as returning v and w unchanged. */
1653 if (PyInstance_Check(v
)) {
1661 if (PyInstance_Check(w
)) {
1677 instance_nonzero(PyInstanceObject
*self
)
1679 PyObject
*func
, *res
;
1681 static PyObject
*nonzerostr
;
1683 if (nonzerostr
== NULL
)
1684 nonzerostr
= PyString_InternFromString("__nonzero__");
1685 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1686 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1690 lenstr
= PyString_InternFromString("__len__");
1691 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1692 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1695 /* Fall back to the default behavior:
1696 all instances are nonzero */
1700 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1704 if (!PyInt_Check(res
)) {
1706 PyErr_SetString(PyExc_TypeError
,
1707 "__nonzero__ should return an int");
1710 outcome
= PyInt_AsLong(res
);
1713 PyErr_SetString(PyExc_ValueError
,
1714 "__nonzero__ should return >= 0");
1720 UNARY(instance_invert
, "__invert__")
1721 UNARY(instance_int
, "__int__")
1722 UNARY(instance_long
, "__long__")
1723 UNARY(instance_float
, "__float__")
1724 UNARY(instance_oct
, "__oct__")
1725 UNARY(instance_hex
, "__hex__")
1728 bin_power(PyObject
*v
, PyObject
*w
)
1730 return PyNumber_Power(v
, w
, Py_None
);
1733 /* This version is for ternary calls only (z != None) */
1735 instance_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1738 return do_binop(v
, w
, "__pow__", "__rpow__", bin_power
);
1745 /* XXX Doesn't do coercions... */
1746 func
= PyObject_GetAttrString(v
, "__pow__");
1749 args
= Py_BuildValue("(OO)", w
, z
);
1754 result
= PyEval_CallObject(func
, args
);
1762 bin_inplace_power(PyObject
*v
, PyObject
*w
)
1764 return PyNumber_InPlacePower(v
, w
, Py_None
);
1769 instance_ipow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1772 return do_binop_inplace(v
, w
, "__ipow__", "__pow__",
1773 "__rpow__", bin_inplace_power
);
1776 /* XXX Doesn't do coercions... */
1781 func
= PyObject_GetAttrString(v
, "__ipow__");
1783 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1786 return instance_pow(v
, w
, z
);
1788 args
= Py_BuildValue("(OO)", w
, z
);
1793 result
= PyEval_CallObject(func
, args
);
1801 /* Map rich comparison operators to their __xx__ namesakes */
1803 static PyObject
**name_op
= NULL
;
1809 char *_name_op
[] = {
1818 name_op
= (PyObject
**)malloc(sizeof(PyObject
*) * NAME_OPS
);
1819 if (name_op
== NULL
)
1821 for (i
= 0; i
< NAME_OPS
; ++i
) {
1822 name_op
[i
] = PyString_InternFromString(_name_op
[i
]);
1823 if (name_op
[i
] == NULL
)
1830 half_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1836 assert(PyInstance_Check(v
));
1838 if (name_op
== NULL
) {
1839 if (init_name_op() < 0)
1842 /* If the instance doesn't define an __getattr__ method, use
1843 instance_getattr2 directly because it will not set an
1844 exception on failure. */
1845 if (((PyInstanceObject
*)v
)->in_class
->cl_getattr
== NULL
)
1846 method
= instance_getattr2((PyInstanceObject
*)v
,
1849 method
= PyObject_GetAttr(v
, name_op
[op
]);
1850 if (method
== NULL
) {
1851 if (PyErr_Occurred()) {
1852 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1856 res
= Py_NotImplemented
;
1861 args
= Py_BuildValue("(O)", w
);
1867 res
= PyEval_CallObject(method
, args
);
1874 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1875 static int swapped_op
[] = {Py_GT
, Py_GE
, Py_EQ
, Py_NE
, Py_LT
, Py_LE
};
1878 instance_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1882 if (PyInstance_Check(v
)) {
1883 res
= half_richcompare(v
, w
, op
);
1884 if (res
!= Py_NotImplemented
)
1889 if (PyInstance_Check(w
)) {
1890 res
= half_richcompare(w
, v
, swapped_op
[op
]);
1891 if (res
!= Py_NotImplemented
)
1896 Py_INCREF(Py_NotImplemented
);
1897 return Py_NotImplemented
;
1901 /* Get the iterator */
1903 instance_getiter(PyInstanceObject
*self
)
1907 if (iterstr
== NULL
) {
1908 iterstr
= PyString_InternFromString("__iter__");
1909 if (iterstr
== NULL
)
1912 if (getitemstr
== NULL
) {
1913 getitemstr
= PyString_InternFromString("__getitem__");
1914 if (getitemstr
== NULL
)
1918 if ((func
= instance_getattr(self
, iterstr
)) != NULL
) {
1919 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1921 if (res
!= NULL
&& !PyIter_Check(res
)) {
1922 PyErr_Format(PyExc_TypeError
,
1923 "__iter__ returned non-iterator "
1925 res
->ob_type
->tp_name
);
1931 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1934 if ((func
= instance_getattr(self
, getitemstr
)) == NULL
) {
1935 PyErr_SetString(PyExc_TypeError
,
1936 "iteration over non-sequence");
1940 return PySeqIter_New((PyObject
*)self
);
1944 /* Call the iterator's next */
1946 instance_iternext(PyInstanceObject
*self
)
1950 if (nextstr
== NULL
)
1951 nextstr
= PyString_InternFromString("next");
1953 if ((func
= instance_getattr(self
, nextstr
)) != NULL
) {
1954 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1959 if (PyErr_ExceptionMatches(PyExc_StopIteration
)) {
1965 PyErr_SetString(PyExc_TypeError
, "instance has no next() method");
1970 instance_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
1972 PyThreadState
*tstate
= PyThreadState_GET();
1973 PyObject
*res
, *call
= PyObject_GetAttrString(func
, "__call__");
1975 PyInstanceObject
*inst
= (PyInstanceObject
*) func
;
1976 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1979 PyErr_Format(PyExc_AttributeError
,
1980 "%.200s instance has no __call__ method",
1981 PyString_AsString(inst
->in_class
->cl_name
));
1984 /* We must check and increment the recursion depth here. Scenario:
1987 A.__call__ = A() # that's right
1989 a() # infinite recursion
1990 This bounces between instance_call() and PyObject_Call() without
1991 ever hitting eval_frame() (which has the main recursion check). */
1992 if (tstate
->recursion_depth
++ > Py_GetRecursionLimit()) {
1993 PyErr_SetString(PyExc_RuntimeError
,
1994 "maximum __call__ recursion depth exceeded");
1998 res
= PyObject_Call(call
, arg
, kw
);
1999 tstate
->recursion_depth
--;
2005 static PyNumberMethods instance_as_number
= {
2006 (binaryfunc
)instance_add
, /* nb_add */
2007 (binaryfunc
)instance_sub
, /* nb_subtract */
2008 (binaryfunc
)instance_mul
, /* nb_multiply */
2009 (binaryfunc
)instance_div
, /* nb_divide */
2010 (binaryfunc
)instance_mod
, /* nb_remainder */
2011 (binaryfunc
)instance_divmod
, /* nb_divmod */
2012 (ternaryfunc
)instance_pow
, /* nb_power */
2013 (unaryfunc
)instance_neg
, /* nb_negative */
2014 (unaryfunc
)instance_pos
, /* nb_positive */
2015 (unaryfunc
)instance_abs
, /* nb_absolute */
2016 (inquiry
)instance_nonzero
, /* nb_nonzero */
2017 (unaryfunc
)instance_invert
, /* nb_invert */
2018 (binaryfunc
)instance_lshift
, /* nb_lshift */
2019 (binaryfunc
)instance_rshift
, /* nb_rshift */
2020 (binaryfunc
)instance_and
, /* nb_and */
2021 (binaryfunc
)instance_xor
, /* nb_xor */
2022 (binaryfunc
)instance_or
, /* nb_or */
2023 (coercion
)instance_coerce
, /* nb_coerce */
2024 (unaryfunc
)instance_int
, /* nb_int */
2025 (unaryfunc
)instance_long
, /* nb_long */
2026 (unaryfunc
)instance_float
, /* nb_float */
2027 (unaryfunc
)instance_oct
, /* nb_oct */
2028 (unaryfunc
)instance_hex
, /* nb_hex */
2029 (binaryfunc
)instance_iadd
, /* nb_inplace_add */
2030 (binaryfunc
)instance_isub
, /* nb_inplace_subtract */
2031 (binaryfunc
)instance_imul
, /* nb_inplace_multiply */
2032 (binaryfunc
)instance_idiv
, /* nb_inplace_divide */
2033 (binaryfunc
)instance_imod
, /* nb_inplace_remainder */
2034 (ternaryfunc
)instance_ipow
, /* nb_inplace_power */
2035 (binaryfunc
)instance_ilshift
, /* nb_inplace_lshift */
2036 (binaryfunc
)instance_irshift
, /* nb_inplace_rshift */
2037 (binaryfunc
)instance_iand
, /* nb_inplace_and */
2038 (binaryfunc
)instance_ixor
, /* nb_inplace_xor */
2039 (binaryfunc
)instance_ior
, /* nb_inplace_or */
2040 (binaryfunc
)instance_floordiv
, /* nb_floor_divide */
2041 (binaryfunc
)instance_truediv
, /* nb_true_divide */
2042 (binaryfunc
)instance_ifloordiv
, /* nb_inplace_floor_divide */
2043 (binaryfunc
)instance_itruediv
, /* nb_inplace_true_divide */
2046 PyTypeObject PyInstance_Type
= {
2047 PyObject_HEAD_INIT(&PyType_Type
)
2050 sizeof(PyInstanceObject
),
2052 (destructor
)instance_dealloc
, /* tp_dealloc */
2056 instance_compare
, /* tp_compare */
2057 (reprfunc
)instance_repr
, /* tp_repr */
2058 &instance_as_number
, /* tp_as_number */
2059 &instance_as_sequence
, /* tp_as_sequence */
2060 &instance_as_mapping
, /* tp_as_mapping */
2061 (hashfunc
)instance_hash
, /* tp_hash */
2062 instance_call
, /* tp_call */
2063 (reprfunc
)instance_str
, /* tp_str */
2064 (getattrofunc
)instance_getattr
, /* tp_getattro */
2065 (setattrofunc
)instance_setattr
, /* tp_setattro */
2066 0, /* tp_as_buffer */
2067 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
,/*tp_flags*/
2068 instance_doc
, /* tp_doc */
2069 (traverseproc
)instance_traverse
, /* tp_traverse */
2071 instance_richcompare
, /* tp_richcompare */
2072 offsetof(PyInstanceObject
, in_weakreflist
), /* tp_weaklistoffset */
2073 (getiterfunc
)instance_getiter
, /* tp_iter */
2074 (iternextfunc
)instance_iternext
, /* tp_iternext */
2080 0, /* tp_descr_get */
2081 0, /* tp_descr_set */
2082 0, /* tp_dictoffset */
2085 instance_new
, /* tp_new */
2089 /* Instance method objects are used for two purposes:
2090 (a) as bound instance methods (returned by instancename.methodname)
2091 (b) as unbound methods (returned by ClassName.methodname)
2092 In case (b), im_self is NULL
2095 static PyMethodObject
*free_list
;
2098 PyMethod_New(PyObject
*func
, PyObject
*self
, PyObject
*class)
2100 register PyMethodObject
*im
;
2101 if (!PyCallable_Check(func
)) {
2102 PyErr_BadInternalCall();
2107 free_list
= (PyMethodObject
*)(im
->im_self
);
2108 PyObject_INIT(im
, &PyMethod_Type
);
2111 im
= PyObject_GC_New(PyMethodObject
, &PyMethod_Type
);
2115 im
->im_weakreflist
= NULL
;
2121 im
->im_class
= class;
2122 _PyObject_GC_TRACK(im
);
2123 return (PyObject
*)im
;
2126 /* Descriptors for PyMethod attributes */
2128 /* im_class, im_func and im_self are stored in the PyMethod object */
2130 #define OFF(x) offsetof(PyMethodObject, x)
2132 static PyMemberDef instancemethod_memberlist
[] = {
2133 {"im_class", T_OBJECT
, OFF(im_class
), READONLY
|RESTRICTED
,
2134 "the class associated with a method"},
2135 {"im_func", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2136 "the function (or other callable) implementing a method"},
2137 {"im_self", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2138 "the instance to which a method is bound; None for unbound methods"},
2139 {NULL
} /* Sentinel */
2142 /* The getattr() implementation for PyMethod objects is similar to
2143 PyObject_GenericGetAttr(), but instead of looking in __dict__ it
2144 asks im_self for the attribute. Then the error handling is a bit
2145 different because we want to preserve the exception raised by the
2146 delegate, unless we have an alternative from our class. */
2149 instancemethod_getattro(PyObject
*obj
, PyObject
*name
)
2151 PyMethodObject
*im
= (PyMethodObject
*)obj
;
2152 PyTypeObject
*tp
= obj
->ob_type
;
2153 PyObject
*descr
= NULL
, *res
;
2154 descrgetfunc f
= NULL
;
2156 if (PyType_HasFeature(tp
, Py_TPFLAGS_HAVE_CLASS
)) {
2157 if (tp
->tp_dict
== NULL
) {
2158 if (PyType_Ready(tp
) < 0)
2161 descr
= _PyType_Lookup(tp
, name
);
2165 if (descr
!= NULL
) {
2166 f
= TP_DESCR_GET(descr
->ob_type
);
2167 if (f
!= NULL
&& PyDescr_IsData(descr
))
2168 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2171 res
= PyObject_GetAttr(im
->im_func
, name
);
2172 if (res
!= NULL
|| !PyErr_ExceptionMatches(PyExc_AttributeError
))
2177 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2180 if (descr
!= NULL
) {
2186 assert(PyErr_Occurred());
2190 PyDoc_STRVAR(instancemethod_doc
,
2191 "instancemethod(function, instance, class)\n\
2193 Create an instance method object.");
2196 instancemethod_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
2200 PyObject
*classObj
= NULL
;
2202 if (!PyArg_UnpackTuple(args
, "instancemethod", 2, 3,
2203 &func
, &self
, &classObj
))
2205 if (!PyCallable_Check(func
)) {
2206 PyErr_SetString(PyExc_TypeError
,
2207 "first argument must be callable");
2210 if (self
== Py_None
)
2212 return PyMethod_New(func
, self
, classObj
);
2216 instancemethod_dealloc(register PyMethodObject
*im
)
2218 _PyObject_GC_UNTRACK(im
);
2219 if (im
->im_weakreflist
!= NULL
)
2220 PyObject_ClearWeakRefs((PyObject
*)im
);
2221 Py_DECREF(im
->im_func
);
2222 Py_XDECREF(im
->im_self
);
2223 Py_XDECREF(im
->im_class
);
2224 im
->im_self
= (PyObject
*)free_list
;
2229 instancemethod_compare(PyMethodObject
*a
, PyMethodObject
*b
)
2231 if (a
->im_self
!= b
->im_self
)
2232 return (a
->im_self
< b
->im_self
) ? -1 : 1;
2233 return PyObject_Compare(a
->im_func
, b
->im_func
);
2237 instancemethod_repr(PyMethodObject
*a
)
2239 PyObject
*self
= a
->im_self
;
2240 PyObject
*func
= a
->im_func
;
2241 PyObject
*klass
= a
->im_class
;
2242 PyObject
*funcname
= NULL
, *klassname
= NULL
, *result
= NULL
;
2243 char *sfuncname
= "?", *sklassname
= "?";
2245 funcname
= PyObject_GetAttrString(func
, "__name__");
2246 if (funcname
== NULL
) {
2247 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2251 else if (!PyString_Check(funcname
)) {
2252 Py_DECREF(funcname
);
2256 sfuncname
= PyString_AS_STRING(funcname
);
2260 klassname
= PyObject_GetAttrString(klass
, "__name__");
2261 if (klassname
== NULL
) {
2262 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2266 else if (!PyString_Check(klassname
)) {
2267 Py_DECREF(klassname
);
2271 sklassname
= PyString_AS_STRING(klassname
);
2274 result
= PyString_FromFormat("<unbound method %s.%s>",
2275 sklassname
, sfuncname
);
2277 /* XXX Shouldn't use repr() here! */
2278 PyObject
*selfrepr
= PyObject_Repr(self
);
2279 if (selfrepr
== NULL
)
2281 if (!PyString_Check(selfrepr
)) {
2282 Py_DECREF(selfrepr
);
2285 result
= PyString_FromFormat("<bound method %s.%s of %s>",
2286 sklassname
, sfuncname
,
2287 PyString_AS_STRING(selfrepr
));
2288 Py_DECREF(selfrepr
);
2291 Py_XDECREF(funcname
);
2292 Py_XDECREF(klassname
);
2297 instancemethod_hash(PyMethodObject
*a
)
2300 if (a
->im_self
== NULL
)
2301 x
= PyObject_Hash(Py_None
);
2303 x
= PyObject_Hash(a
->im_self
);
2306 y
= PyObject_Hash(a
->im_func
);
2313 instancemethod_traverse(PyMethodObject
*im
, visitproc visit
, void *arg
)
2317 err
= visit(im
->im_func
, arg
);
2322 err
= visit(im
->im_self
, arg
);
2327 err
= visit(im
->im_class
, arg
);
2335 getclassname(PyObject
*class, char *buf
, int bufsize
)
2339 assert(bufsize
> 1);
2340 strcpy(buf
, "?"); /* Default outcome */
2343 name
= PyObject_GetAttrString(class, "__name__");
2345 /* This function cannot return an exception */
2349 if (PyString_Check(name
)) {
2350 strncpy(buf
, PyString_AS_STRING(name
), bufsize
);
2351 buf
[bufsize
-1] = '\0';
2357 getinstclassname(PyObject
*inst
, char *buf
, int bufsize
)
2362 assert(bufsize
> 0 && (size_t)bufsize
> strlen("nothing"));
2363 strcpy(buf
, "nothing");
2367 class = PyObject_GetAttrString(inst
, "__class__");
2368 if (class == NULL
) {
2369 /* This function cannot return an exception */
2371 class = (PyObject
*)(inst
->ob_type
);
2374 getclassname(class, buf
, bufsize
);
2379 instancemethod_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2381 PyObject
*self
= PyMethod_GET_SELF(func
);
2382 PyObject
*class = PyMethod_GET_CLASS(func
);
2385 func
= PyMethod_GET_FUNCTION(func
);
2387 /* Unbound methods must be called with an instance of
2388 the class (or a derived class) as first argument */
2390 if (PyTuple_Size(arg
) >= 1)
2391 self
= PyTuple_GET_ITEM(arg
, 0);
2395 ok
= PyObject_IsInstance(self
, class);
2402 getclassname(class, clsbuf
, sizeof(clsbuf
));
2403 getinstclassname(self
, instbuf
, sizeof(instbuf
));
2404 PyErr_Format(PyExc_TypeError
,
2405 "unbound method %s%s must be called with "
2406 "%s instance as first argument "
2407 "(got %s%s instead)",
2408 PyEval_GetFuncName(func
),
2409 PyEval_GetFuncDesc(func
),
2412 self
== NULL
? "" : " instance");
2418 int argcount
= PyTuple_Size(arg
);
2419 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2424 PyTuple_SET_ITEM(newarg
, 0, self
);
2425 for (i
= 0; i
< argcount
; i
++) {
2426 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2428 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2432 result
= PyObject_Call((PyObject
*)func
, arg
, kw
);
2438 instancemethod_descr_get(PyObject
*meth
, PyObject
*obj
, PyObject
*cls
)
2440 /* Don't rebind an already bound method, or an unbound method
2441 of a class that's not a base class of cls. */
2443 if (PyMethod_GET_SELF(meth
) != NULL
) {
2448 /* No, it is an unbound method */
2449 if (PyMethod_GET_CLASS(meth
) != NULL
&& cls
!= NULL
) {
2450 /* Do subclass test. If it fails, return meth unchanged. */
2451 int ok
= PyObject_IsSubclass(cls
, PyMethod_GET_CLASS(meth
));
2459 /* Bind it to obj */
2460 return PyMethod_New(PyMethod_GET_FUNCTION(meth
), obj
, cls
);
2463 PyTypeObject PyMethod_Type
= {
2464 PyObject_HEAD_INIT(&PyType_Type
)
2467 sizeof(PyMethodObject
),
2469 (destructor
)instancemethod_dealloc
, /* tp_dealloc */
2473 (cmpfunc
)instancemethod_compare
, /* tp_compare */
2474 (reprfunc
)instancemethod_repr
, /* tp_repr */
2475 0, /* tp_as_number */
2476 0, /* tp_as_sequence */
2477 0, /* tp_as_mapping */
2478 (hashfunc
)instancemethod_hash
, /* tp_hash */
2479 instancemethod_call
, /* tp_call */
2481 (getattrofunc
)instancemethod_getattro
, /* tp_getattro */
2482 PyObject_GenericSetAttr
, /* tp_setattro */
2483 0, /* tp_as_buffer */
2484 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
2485 instancemethod_doc
, /* tp_doc */
2486 (traverseproc
)instancemethod_traverse
, /* tp_traverse */
2488 0, /* tp_richcompare */
2489 offsetof(PyMethodObject
, im_weakreflist
), /* tp_weaklistoffset */
2491 0, /* tp_iternext */
2493 instancemethod_memberlist
, /* tp_members */
2497 instancemethod_descr_get
, /* tp_descr_get */
2498 0, /* tp_descr_set */
2499 0, /* tp_dictoffset */
2502 instancemethod_new
, /* tp_new */
2505 /* Clear out the free list */
2511 PyMethodObject
*im
= free_list
;
2512 free_list
= (PyMethodObject
*)(im
->im_self
);
2513 PyObject_GC_Del(im
);