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 (class == NULL
|| !PyClass_Check(class))
492 cp
= (PyClassObject
*)class;
493 n
= PyTuple_Size(cp
->cl_bases
);
494 for (i
= 0; i
< n
; i
++) {
495 if (PyClass_IsSubclass(PyTuple_GetItem(cp
->cl_bases
, i
), base
))
502 /* Instance objects */
505 PyInstance_NewRaw(PyObject
*klass
, PyObject
*dict
)
507 PyInstanceObject
*inst
;
509 if (!PyClass_Check(klass
)) {
510 PyErr_BadInternalCall();
519 if (!PyDict_Check(dict
)) {
520 PyErr_BadInternalCall();
525 inst
= PyObject_GC_New(PyInstanceObject
, &PyInstance_Type
);
530 inst
->in_weakreflist
= NULL
;
532 inst
->in_class
= (PyClassObject
*)klass
;
533 inst
->in_dict
= dict
;
534 _PyObject_GC_TRACK(inst
);
535 return (PyObject
*)inst
;
539 PyInstance_New(PyObject
*klass
, PyObject
*arg
, PyObject
*kw
)
541 register PyInstanceObject
*inst
;
543 static PyObject
*initstr
;
545 inst
= (PyInstanceObject
*) PyInstance_NewRaw(klass
, NULL
);
549 initstr
= PyString_InternFromString("__init__");
550 init
= instance_getattr2(inst
, initstr
);
552 if ((arg
!= NULL
&& (!PyTuple_Check(arg
) ||
553 PyTuple_Size(arg
) != 0))
554 || (kw
!= NULL
&& (!PyDict_Check(kw
) ||
555 PyDict_Size(kw
) != 0))) {
556 PyErr_SetString(PyExc_TypeError
,
557 "this constructor takes no arguments");
563 PyObject
*res
= PyEval_CallObjectWithKeywords(init
, arg
, kw
);
570 if (res
!= Py_None
) {
571 PyErr_SetString(PyExc_TypeError
,
572 "__init__() should return None");
579 return (PyObject
*)inst
;
582 /* Instance methods */
584 PyDoc_STRVAR(instance_doc
,
585 "instance(class[, dict])\n\
587 Create an instance without calling its __init__() method.\n\
588 The class must be a classic class.\n\
589 If present, dict must be a dictionary or None.");
592 instance_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
595 PyObject
*dict
= Py_None
;
597 if (!PyArg_ParseTuple(args
, "O!|O:instance",
598 &PyClass_Type
, &klass
, &dict
))
603 else if (!PyDict_Check(dict
)) {
604 PyErr_SetString(PyExc_TypeError
,
605 "instance() second arg must be dictionary or None");
608 return PyInstance_NewRaw(klass
, dict
);
613 instance_dealloc(register PyInstanceObject
*inst
)
615 PyObject
*error_type
, *error_value
, *error_traceback
;
617 static PyObject
*delstr
;
619 extern long _Py_RefTotal
;
621 _PyObject_GC_UNTRACK(inst
);
622 if (inst
->in_weakreflist
!= NULL
)
623 PyObject_ClearWeakRefs((PyObject
*) inst
);
625 /* Temporarily resurrect the object. */
628 # error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
630 /* much too complicated if Py_TRACE_REFS defined */
631 inst
->ob_type
= &PyInstance_Type
;
632 _Py_NewReference((PyObject
*)inst
);
634 /* compensate for boost in _Py_NewReference; note that
635 * _Py_RefTotal was also boosted; we'll knock that down later.
637 inst
->ob_type
->tp_allocs
--;
639 #else /* !Py_TRACE_REFS */
640 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
642 #endif /* !Py_TRACE_REFS */
644 /* Save the current exception, if any. */
645 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
646 /* Execute __del__ method, if any. */
648 delstr
= PyString_InternFromString("__del__");
649 if ((del
= instance_getattr2(inst
, delstr
)) != NULL
) {
650 PyObject
*res
= PyEval_CallObject(del
, (PyObject
*)NULL
);
652 PyErr_WriteUnraisable(del
);
657 /* Restore the saved exception. */
658 PyErr_Restore(error_type
, error_value
, error_traceback
);
659 /* Undo the temporary resurrection; can't use DECREF here, it would
660 * cause a recursive call.
663 /* _Py_RefTotal was boosted either by _Py_NewReference or
668 if (--inst
->ob_refcnt
> 0) {
670 inst
->ob_type
->tp_frees
--;
672 _PyObject_GC_TRACK(inst
);
673 return; /* __del__ added a reference; don't delete now */
676 _Py_ForgetReference((PyObject
*)inst
);
678 /* compensate for increment in _Py_ForgetReference */
679 inst
->ob_type
->tp_frees
--;
681 #ifndef WITH_CYCLE_GC
682 inst
->ob_type
= NULL
;
685 Py_DECREF(inst
->in_class
);
686 Py_XDECREF(inst
->in_dict
);
687 PyObject_GC_Del(inst
);
691 instance_getattr1(register PyInstanceObject
*inst
, PyObject
*name
)
693 register PyObject
*v
;
694 register char *sname
= PyString_AsString(name
);
695 if (sname
[0] == '_' && sname
[1] == '_') {
696 if (strcmp(sname
, "__dict__") == 0) {
697 if (PyEval_GetRestricted()) {
698 PyErr_SetString(PyExc_RuntimeError
,
699 "instance.__dict__ not accessible in restricted mode");
702 Py_INCREF(inst
->in_dict
);
703 return inst
->in_dict
;
705 if (strcmp(sname
, "__class__") == 0) {
706 Py_INCREF(inst
->in_class
);
707 return (PyObject
*)inst
->in_class
;
710 v
= instance_getattr2(inst
, name
);
712 PyErr_Format(PyExc_AttributeError
,
713 "%.50s instance has no attribute '%.400s'",
714 PyString_AS_STRING(inst
->in_class
->cl_name
), sname
);
720 instance_getattr2(register PyInstanceObject
*inst
, PyObject
*name
)
722 register PyObject
*v
;
723 PyClassObject
*class;
726 v
= PyDict_GetItem(inst
->in_dict
, name
);
731 v
= class_lookup(inst
->in_class
, name
, &class);
734 f
= TP_DESCR_GET(v
->ob_type
);
736 PyObject
*w
= f(v
, (PyObject
*)inst
,
737 (PyObject
*)(inst
->in_class
));
746 instance_getattr(register PyInstanceObject
*inst
, PyObject
*name
)
748 register PyObject
*func
, *res
;
749 res
= instance_getattr1(inst
, name
);
750 if (res
== NULL
&& (func
= inst
->in_class
->cl_getattr
) != NULL
) {
752 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
755 args
= Py_BuildValue("(OO)", inst
, name
);
758 res
= PyEval_CallObject(func
, args
);
765 instance_setattr1(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
768 int rv
= PyDict_DelItem(inst
->in_dict
, name
);
770 PyErr_Format(PyExc_AttributeError
,
771 "%.50s instance has no attribute '%.400s'",
772 PyString_AS_STRING(inst
->in_class
->cl_name
),
773 PyString_AS_STRING(name
));
777 return PyDict_SetItem(inst
->in_dict
, name
, v
);
781 instance_setattr(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
783 PyObject
*func
, *args
, *res
, *tmp
;
784 char *sname
= PyString_AsString(name
);
785 if (sname
[0] == '_' && sname
[1] == '_') {
786 int n
= PyString_Size(name
);
787 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
788 if (strcmp(sname
, "__dict__") == 0) {
789 if (PyEval_GetRestricted()) {
790 PyErr_SetString(PyExc_RuntimeError
,
791 "__dict__ not accessible in restricted mode");
794 if (v
== NULL
|| !PyDict_Check(v
)) {
795 PyErr_SetString(PyExc_TypeError
,
796 "__dict__ must be set to a dictionary");
805 if (strcmp(sname
, "__class__") == 0) {
806 if (PyEval_GetRestricted()) {
807 PyErr_SetString(PyExc_RuntimeError
,
808 "__class__ not accessible in restricted mode");
811 if (v
== NULL
|| !PyClass_Check(v
)) {
812 PyErr_SetString(PyExc_TypeError
,
813 "__class__ must be set to a class");
816 tmp
= (PyObject
*)(inst
->in_class
);
818 inst
->in_class
= (PyClassObject
*)v
;
825 func
= inst
->in_class
->cl_delattr
;
827 func
= inst
->in_class
->cl_setattr
;
829 return instance_setattr1(inst
, name
, v
);
831 args
= Py_BuildValue("(OO)", inst
, name
);
833 args
= Py_BuildValue("(OOO)", inst
, name
, v
);
836 res
= PyEval_CallObject(func
, args
);
845 instance_repr(PyInstanceObject
*inst
)
849 static PyObject
*reprstr
;
852 reprstr
= PyString_InternFromString("__repr__");
853 func
= instance_getattr(inst
, reprstr
);
855 PyObject
*classname
, *mod
;
857 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
860 classname
= inst
->in_class
->cl_name
;
861 mod
= PyDict_GetItemString(inst
->in_class
->cl_dict
,
863 if (classname
!= NULL
&& PyString_Check(classname
))
864 cname
= PyString_AsString(classname
);
867 if (mod
== NULL
|| !PyString_Check(mod
))
868 return PyString_FromFormat("<?.%s instance at %p>",
871 return PyString_FromFormat("<%s.%s instance at %p>",
872 PyString_AsString(mod
),
875 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
881 instance_str(PyInstanceObject
*inst
)
885 static PyObject
*strstr
;
888 strstr
= PyString_InternFromString("__str__");
889 func
= instance_getattr(inst
, strstr
);
891 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
894 return instance_repr(inst
);
896 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
902 instance_hash(PyInstanceObject
*inst
)
907 static PyObject
*hashstr
, *eqstr
, *cmpstr
;
910 hashstr
= PyString_InternFromString("__hash__");
911 func
= instance_getattr(inst
, hashstr
);
913 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
916 /* If there is no __eq__ and no __cmp__ method, we hash on the
917 address. If an __eq__ or __cmp__ method exists, there must
920 eqstr
= PyString_InternFromString("__eq__");
921 func
= instance_getattr(inst
, eqstr
);
923 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
927 cmpstr
= PyString_InternFromString("__cmp__");
928 func
= instance_getattr(inst
, cmpstr
);
930 if (!PyErr_ExceptionMatches(
931 PyExc_AttributeError
))
934 return _Py_HashPointer(inst
);
937 PyErr_SetString(PyExc_TypeError
, "unhashable instance");
940 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
944 if (PyInt_Check(res
)) {
945 outcome
= PyInt_AsLong(res
);
950 PyErr_SetString(PyExc_TypeError
,
951 "__hash__() should return an int");
959 instance_traverse(PyInstanceObject
*o
, visitproc visit
, void *arg
)
963 err
= visit((PyObject
*)(o
->in_class
), arg
);
968 err
= visit(o
->in_dict
, arg
);
975 static PyObject
*getitemstr
, *setitemstr
, *delitemstr
, *lenstr
;
976 static PyObject
*iterstr
, *nextstr
;
979 instance_length(PyInstanceObject
*inst
)
986 lenstr
= PyString_InternFromString("__len__");
987 func
= instance_getattr(inst
, lenstr
);
990 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
994 if (PyInt_Check(res
)) {
995 outcome
= PyInt_AsLong(res
);
997 PyErr_SetString(PyExc_ValueError
,
998 "__len__() should return >= 0");
1001 PyErr_SetString(PyExc_TypeError
,
1002 "__len__() should return an int");
1010 instance_subscript(PyInstanceObject
*inst
, PyObject
*key
)
1016 if (getitemstr
== NULL
)
1017 getitemstr
= PyString_InternFromString("__getitem__");
1018 func
= instance_getattr(inst
, getitemstr
);
1021 arg
= Py_BuildValue("(O)", key
);
1026 res
= PyEval_CallObject(func
, arg
);
1033 instance_ass_subscript(PyInstanceObject
*inst
, PyObject
*key
, PyObject
*value
)
1039 if (value
== NULL
) {
1040 if (delitemstr
== NULL
)
1041 delitemstr
= PyString_InternFromString("__delitem__");
1042 func
= instance_getattr(inst
, delitemstr
);
1045 if (setitemstr
== NULL
)
1046 setitemstr
= PyString_InternFromString("__setitem__");
1047 func
= instance_getattr(inst
, setitemstr
);
1052 arg
= Py_BuildValue("(O)", key
);
1054 arg
= Py_BuildValue("(OO)", key
, value
);
1059 res
= PyEval_CallObject(func
, arg
);
1068 static PyMappingMethods instance_as_mapping
= {
1069 (inquiry
)instance_length
, /* mp_length */
1070 (binaryfunc
)instance_subscript
, /* mp_subscript */
1071 (objobjargproc
)instance_ass_subscript
, /* mp_ass_subscript */
1075 instance_item(PyInstanceObject
*inst
, int i
)
1077 PyObject
*func
, *arg
, *res
;
1079 if (getitemstr
== NULL
)
1080 getitemstr
= PyString_InternFromString("__getitem__");
1081 func
= instance_getattr(inst
, getitemstr
);
1084 arg
= Py_BuildValue("(i)", i
);
1089 res
= PyEval_CallObject(func
, arg
);
1096 sliceobj_from_intint(int i
, int j
)
1098 PyObject
*start
, *end
, *res
;
1100 start
= PyInt_FromLong((long)i
);
1104 end
= PyInt_FromLong((long)j
);
1109 res
= PySlice_New(start
, end
, NULL
);
1117 instance_slice(PyInstanceObject
*inst
, int i
, int j
)
1119 PyObject
*func
, *arg
, *res
;
1120 static PyObject
*getslicestr
;
1122 if (getslicestr
== NULL
)
1123 getslicestr
= PyString_InternFromString("__getslice__");
1124 func
= instance_getattr(inst
, getslicestr
);
1127 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1131 if (getitemstr
== NULL
)
1132 getitemstr
= PyString_InternFromString("__getitem__");
1133 func
= instance_getattr(inst
, getitemstr
);
1136 arg
= Py_BuildValue("(N)", sliceobj_from_intint(i
, j
));
1138 arg
= Py_BuildValue("(ii)", i
, j
);
1144 res
= PyEval_CallObject(func
, arg
);
1151 instance_ass_item(PyInstanceObject
*inst
, int i
, PyObject
*item
)
1153 PyObject
*func
, *arg
, *res
;
1156 if (delitemstr
== NULL
)
1157 delitemstr
= PyString_InternFromString("__delitem__");
1158 func
= instance_getattr(inst
, delitemstr
);
1161 if (setitemstr
== NULL
)
1162 setitemstr
= PyString_InternFromString("__setitem__");
1163 func
= instance_getattr(inst
, setitemstr
);
1168 arg
= Py_BuildValue("i", i
);
1170 arg
= Py_BuildValue("(iO)", i
, item
);
1175 res
= PyEval_CallObject(func
, arg
);
1185 instance_ass_slice(PyInstanceObject
*inst
, int i
, int j
, PyObject
*value
)
1187 PyObject
*func
, *arg
, *res
;
1188 static PyObject
*setslicestr
, *delslicestr
;
1190 if (value
== NULL
) {
1191 if (delslicestr
== NULL
)
1193 PyString_InternFromString("__delslice__");
1194 func
= instance_getattr(inst
, delslicestr
);
1196 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1199 if (delitemstr
== NULL
)
1201 PyString_InternFromString("__delitem__");
1202 func
= instance_getattr(inst
, delitemstr
);
1206 arg
= Py_BuildValue("(N)",
1207 sliceobj_from_intint(i
, j
));
1209 arg
= Py_BuildValue("(ii)", i
, j
);
1212 if (setslicestr
== NULL
)
1214 PyString_InternFromString("__setslice__");
1215 func
= instance_getattr(inst
, setslicestr
);
1217 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1220 if (setitemstr
== NULL
)
1222 PyString_InternFromString("__setitem__");
1223 func
= instance_getattr(inst
, setitemstr
);
1227 arg
= Py_BuildValue("(NO)",
1228 sliceobj_from_intint(i
, j
), value
);
1230 arg
= Py_BuildValue("(iiO)", i
, j
, value
);
1236 res
= PyEval_CallObject(func
, arg
);
1246 instance_contains(PyInstanceObject
*inst
, PyObject
*member
)
1248 static PyObject
*__contains__
;
1251 /* Try __contains__ first.
1252 * If that can't be done, try iterator-based searching.
1255 if(__contains__
== NULL
) {
1256 __contains__
= PyString_InternFromString("__contains__");
1257 if(__contains__
== NULL
)
1260 func
= instance_getattr(inst
, __contains__
);
1264 PyObject
*arg
= Py_BuildValue("(O)", member
);
1269 res
= PyEval_CallObject(func
, arg
);
1274 ret
= PyObject_IsTrue(res
);
1279 /* Couldn't find __contains__. */
1280 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1281 /* Assume the failure was simply due to that there is no
1282 * __contains__ attribute, and try iterating instead.
1285 return _PySequence_IterSearch((PyObject
*)inst
, member
,
1286 PY_ITERSEARCH_CONTAINS
);
1292 static PySequenceMethods
1293 instance_as_sequence
= {
1294 (inquiry
)instance_length
, /* sq_length */
1297 (intargfunc
)instance_item
, /* sq_item */
1298 (intintargfunc
)instance_slice
, /* sq_slice */
1299 (intobjargproc
)instance_ass_item
, /* sq_ass_item */
1300 (intintobjargproc
)instance_ass_slice
, /* sq_ass_slice */
1301 (objobjproc
)instance_contains
, /* sq_contains */
1305 generic_unary_op(PyInstanceObject
*self
, PyObject
*methodname
)
1307 PyObject
*func
, *res
;
1309 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1311 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1317 generic_binary_op(PyObject
*v
, PyObject
*w
, char *opname
)
1321 PyObject
*func
= PyObject_GetAttrString(v
, opname
);
1323 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1326 Py_INCREF(Py_NotImplemented
);
1327 return Py_NotImplemented
;
1329 args
= Py_BuildValue("(O)", w
);
1334 result
= PyEval_CallObject(func
, args
);
1341 static PyObject
*coerce_obj
;
1343 /* Try one half of a binary operator involving a class instance. */
1345 half_binop(PyObject
*v
, PyObject
*w
, char *opname
, binaryfunc thisfunc
,
1349 PyObject
*coercefunc
;
1350 PyObject
*coerced
= NULL
;
1354 if (!PyInstance_Check(v
)) {
1355 Py_INCREF(Py_NotImplemented
);
1356 return Py_NotImplemented
;
1359 if (coerce_obj
== NULL
) {
1360 coerce_obj
= PyString_InternFromString("__coerce__");
1361 if (coerce_obj
== NULL
)
1364 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1365 if (coercefunc
== NULL
) {
1366 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1369 return generic_binary_op(v
, w
, opname
);
1372 args
= Py_BuildValue("(O)", w
);
1376 coerced
= PyEval_CallObject(coercefunc
, args
);
1378 Py_DECREF(coercefunc
);
1379 if (coerced
== NULL
) {
1382 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1384 return generic_binary_op(v
, w
, opname
);
1386 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1388 PyErr_SetString(PyExc_TypeError
,
1389 "coercion should return None or 2-tuple");
1392 v1
= PyTuple_GetItem(coerced
, 0);
1393 w
= PyTuple_GetItem(coerced
, 1);
1394 if (v1
->ob_type
== v
->ob_type
&& PyInstance_Check(v
)) {
1395 /* prevent recursion if __coerce__ returns self as the first
1397 result
= generic_binary_op(v1
, w
, opname
);
1400 result
= (thisfunc
)(w
, v1
);
1402 result
= (thisfunc
)(v1
, w
);
1408 /* Implement a binary operator involving at least one class instance. */
1410 do_binop(PyObject
*v
, PyObject
*w
, char *opname
, char *ropname
,
1411 binaryfunc thisfunc
)
1413 PyObject
*result
= half_binop(v
, w
, opname
, thisfunc
, 0);
1414 if (result
== Py_NotImplemented
) {
1416 result
= half_binop(w
, v
, ropname
, thisfunc
, 1);
1422 do_binop_inplace(PyObject
*v
, PyObject
*w
, char *iopname
, char *opname
,
1423 char *ropname
, binaryfunc thisfunc
)
1425 PyObject
*result
= half_binop(v
, w
, iopname
, thisfunc
, 0);
1426 if (result
== Py_NotImplemented
) {
1428 result
= do_binop(v
, w
, opname
, ropname
, thisfunc
);
1434 instance_coerce(PyObject
**pv
, PyObject
**pw
)
1438 PyObject
*coercefunc
;
1442 if (coerce_obj
== NULL
) {
1443 coerce_obj
= PyString_InternFromString("__coerce__");
1444 if (coerce_obj
== NULL
)
1447 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1448 if (coercefunc
== NULL
) {
1449 /* No __coerce__ method */
1450 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1455 /* Has __coerce__ method: call it */
1456 args
= Py_BuildValue("(O)", w
);
1460 coerced
= PyEval_CallObject(coercefunc
, args
);
1462 Py_DECREF(coercefunc
);
1463 if (coerced
== NULL
) {
1464 /* __coerce__ call raised an exception */
1467 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1468 /* __coerce__ says "I can't do it" */
1472 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1473 /* __coerce__ return value is malformed */
1475 PyErr_SetString(PyExc_TypeError
,
1476 "coercion should return None or 2-tuple");
1479 /* __coerce__ returned two new values */
1480 *pv
= PyTuple_GetItem(coerced
, 0);
1481 *pw
= PyTuple_GetItem(coerced
, 1);
1488 #define UNARY(funcname, methodname) \
1489 static PyObject *funcname(PyInstanceObject *self) { \
1490 static PyObject *o; \
1491 if (o == NULL) o = PyString_InternFromString(methodname); \
1492 return generic_unary_op(self, o); \
1495 #define BINARY(f, m, n) \
1496 static PyObject *f(PyObject *v, PyObject *w) { \
1497 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1500 #define BINARY_INPLACE(f, m, n) \
1501 static PyObject *f(PyObject *v, PyObject *w) { \
1502 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1506 UNARY(instance_neg
, "__neg__")
1507 UNARY(instance_pos
, "__pos__")
1508 UNARY(instance_abs
, "__abs__")
1510 BINARY(instance_or
, "or", PyNumber_Or
)
1511 BINARY(instance_and
, "and", PyNumber_And
)
1512 BINARY(instance_xor
, "xor", PyNumber_Xor
)
1513 BINARY(instance_lshift
, "lshift", PyNumber_Lshift
)
1514 BINARY(instance_rshift
, "rshift", PyNumber_Rshift
)
1515 BINARY(instance_add
, "add", PyNumber_Add
)
1516 BINARY(instance_sub
, "sub", PyNumber_Subtract
)
1517 BINARY(instance_mul
, "mul", PyNumber_Multiply
)
1518 BINARY(instance_div
, "div", PyNumber_Divide
)
1519 BINARY(instance_mod
, "mod", PyNumber_Remainder
)
1520 BINARY(instance_divmod
, "divmod", PyNumber_Divmod
)
1521 BINARY(instance_floordiv
, "floordiv", PyNumber_FloorDivide
)
1522 BINARY(instance_truediv
, "truediv", PyNumber_TrueDivide
)
1524 BINARY_INPLACE(instance_ior
, "or", PyNumber_InPlaceOr
)
1525 BINARY_INPLACE(instance_ixor
, "xor", PyNumber_InPlaceXor
)
1526 BINARY_INPLACE(instance_iand
, "and", PyNumber_InPlaceAnd
)
1527 BINARY_INPLACE(instance_ilshift
, "lshift", PyNumber_InPlaceLshift
)
1528 BINARY_INPLACE(instance_irshift
, "rshift", PyNumber_InPlaceRshift
)
1529 BINARY_INPLACE(instance_iadd
, "add", PyNumber_InPlaceAdd
)
1530 BINARY_INPLACE(instance_isub
, "sub", PyNumber_InPlaceSubtract
)
1531 BINARY_INPLACE(instance_imul
, "mul", PyNumber_InPlaceMultiply
)
1532 BINARY_INPLACE(instance_idiv
, "div", PyNumber_InPlaceDivide
)
1533 BINARY_INPLACE(instance_imod
, "mod", PyNumber_InPlaceRemainder
)
1534 BINARY_INPLACE(instance_ifloordiv
, "floordiv", PyNumber_InPlaceFloorDivide
)
1535 BINARY_INPLACE(instance_itruediv
, "truediv", PyNumber_InPlaceTrueDivide
)
1537 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1538 -2 for an exception;
1542 2 if this particular 3-way comparison is not implemented or undefined.
1545 half_cmp(PyObject
*v
, PyObject
*w
)
1547 static PyObject
*cmp_obj
;
1553 assert(PyInstance_Check(v
));
1555 if (cmp_obj
== NULL
) {
1556 cmp_obj
= PyString_InternFromString("__cmp__");
1557 if (cmp_obj
== NULL
)
1561 cmp_func
= PyObject_GetAttr(v
, cmp_obj
);
1562 if (cmp_func
== NULL
) {
1563 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1569 args
= Py_BuildValue("(O)", w
);
1573 result
= PyEval_CallObject(cmp_func
, args
);
1575 Py_DECREF(cmp_func
);
1580 if (result
== Py_NotImplemented
) {
1585 l
= PyInt_AsLong(result
);
1587 if (l
== -1 && PyErr_Occurred()) {
1588 PyErr_SetString(PyExc_TypeError
,
1589 "comparison did not return an int");
1593 return l
< 0 ? -1 : l
> 0 ? 1 : 0;
1596 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1597 We first try a coercion. Return:
1598 -2 for an exception;
1602 2 if this particular 3-way comparison is not implemented or undefined.
1603 THIS IS ONLY CALLED FROM object.c!
1606 instance_compare(PyObject
*v
, PyObject
*w
)
1610 c
= PyNumber_CoerceEx(&v
, &w
);
1614 /* If neither is now an instance, use regular comparison */
1615 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1616 c
= PyObject_Compare(v
, w
);
1619 if (PyErr_Occurred())
1621 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
1625 /* The coercion didn't do anything.
1626 Treat this the same as returning v and w unchanged. */
1631 if (PyInstance_Check(v
)) {
1639 if (PyInstance_Check(w
)) {
1655 instance_nonzero(PyInstanceObject
*self
)
1657 PyObject
*func
, *res
;
1659 static PyObject
*nonzerostr
;
1661 if (nonzerostr
== NULL
)
1662 nonzerostr
= PyString_InternFromString("__nonzero__");
1663 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1664 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1668 lenstr
= PyString_InternFromString("__len__");
1669 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1670 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1673 /* Fall back to the default behavior:
1674 all instances are nonzero */
1678 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1682 if (!PyInt_Check(res
)) {
1684 PyErr_SetString(PyExc_TypeError
,
1685 "__nonzero__ should return an int");
1688 outcome
= PyInt_AsLong(res
);
1691 PyErr_SetString(PyExc_ValueError
,
1692 "__nonzero__ should return >= 0");
1698 UNARY(instance_invert
, "__invert__")
1699 UNARY(instance_int
, "__int__")
1700 UNARY(instance_long
, "__long__")
1701 UNARY(instance_float
, "__float__")
1702 UNARY(instance_oct
, "__oct__")
1703 UNARY(instance_hex
, "__hex__")
1706 bin_power(PyObject
*v
, PyObject
*w
)
1708 return PyNumber_Power(v
, w
, Py_None
);
1711 /* This version is for ternary calls only (z != None) */
1713 instance_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1716 return do_binop(v
, w
, "__pow__", "__rpow__", bin_power
);
1723 /* XXX Doesn't do coercions... */
1724 func
= PyObject_GetAttrString(v
, "__pow__");
1727 args
= Py_BuildValue("(OO)", w
, z
);
1732 result
= PyEval_CallObject(func
, args
);
1740 bin_inplace_power(PyObject
*v
, PyObject
*w
)
1742 return PyNumber_InPlacePower(v
, w
, Py_None
);
1747 instance_ipow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1750 return do_binop_inplace(v
, w
, "__ipow__", "__pow__",
1751 "__rpow__", bin_inplace_power
);
1754 /* XXX Doesn't do coercions... */
1759 func
= PyObject_GetAttrString(v
, "__ipow__");
1761 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1764 return instance_pow(v
, w
, z
);
1766 args
= Py_BuildValue("(OO)", w
, z
);
1771 result
= PyEval_CallObject(func
, args
);
1779 /* Map rich comparison operators to their __xx__ namesakes */
1781 static PyObject
**name_op
= NULL
;
1787 char *_name_op
[] = {
1796 name_op
= (PyObject
**)malloc(sizeof(PyObject
*) * NAME_OPS
);
1797 if (name_op
== NULL
)
1799 for (i
= 0; i
< NAME_OPS
; ++i
) {
1800 name_op
[i
] = PyString_InternFromString(_name_op
[i
]);
1801 if (name_op
[i
] == NULL
)
1808 half_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1814 assert(PyInstance_Check(v
));
1816 if (name_op
== NULL
) {
1817 if (init_name_op() < 0)
1820 /* If the instance doesn't define an __getattr__ method, use
1821 instance_getattr2 directly because it will not set an
1822 exception on failure. */
1823 if (((PyInstanceObject
*)v
)->in_class
->cl_getattr
== NULL
) {
1824 method
= instance_getattr2((PyInstanceObject
*)v
,
1826 if (method
== NULL
) {
1827 assert(!PyErr_Occurred());
1828 res
= Py_NotImplemented
;
1833 method
= PyObject_GetAttr(v
, name_op
[op
]);
1834 if (method
== NULL
) {
1835 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1838 res
= Py_NotImplemented
;
1844 args
= Py_BuildValue("(O)", w
);
1850 res
= PyEval_CallObject(method
, args
);
1857 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1858 static int swapped_op
[] = {Py_GT
, Py_GE
, Py_EQ
, Py_NE
, Py_LT
, Py_LE
};
1861 instance_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1865 if (PyInstance_Check(v
)) {
1866 res
= half_richcompare(v
, w
, op
);
1867 if (res
!= Py_NotImplemented
)
1872 if (PyInstance_Check(w
)) {
1873 res
= half_richcompare(w
, v
, swapped_op
[op
]);
1874 if (res
!= Py_NotImplemented
)
1879 Py_INCREF(Py_NotImplemented
);
1880 return Py_NotImplemented
;
1884 /* Get the iterator */
1886 instance_getiter(PyInstanceObject
*self
)
1890 if (iterstr
== NULL
) {
1891 iterstr
= PyString_InternFromString("__iter__");
1892 if (iterstr
== NULL
)
1895 if (getitemstr
== NULL
) {
1896 getitemstr
= PyString_InternFromString("__getitem__");
1897 if (getitemstr
== NULL
)
1901 if ((func
= instance_getattr(self
, iterstr
)) != NULL
) {
1902 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1904 if (res
!= NULL
&& !PyIter_Check(res
)) {
1905 PyErr_Format(PyExc_TypeError
,
1906 "__iter__ returned non-iterator "
1908 res
->ob_type
->tp_name
);
1914 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1917 if ((func
= instance_getattr(self
, getitemstr
)) == NULL
) {
1918 PyErr_SetString(PyExc_TypeError
,
1919 "iteration over non-sequence");
1923 return PySeqIter_New((PyObject
*)self
);
1927 /* Call the iterator's next */
1929 instance_iternext(PyInstanceObject
*self
)
1933 if (nextstr
== NULL
)
1934 nextstr
= PyString_InternFromString("next");
1936 if ((func
= instance_getattr(self
, nextstr
)) != NULL
) {
1937 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1942 if (PyErr_ExceptionMatches(PyExc_StopIteration
)) {
1948 PyErr_SetString(PyExc_TypeError
, "instance has no next() method");
1953 instance_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
1955 PyThreadState
*tstate
= PyThreadState_GET();
1956 PyObject
*res
, *call
= PyObject_GetAttrString(func
, "__call__");
1958 PyInstanceObject
*inst
= (PyInstanceObject
*) func
;
1959 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1962 PyErr_Format(PyExc_AttributeError
,
1963 "%.200s instance has no __call__ method",
1964 PyString_AsString(inst
->in_class
->cl_name
));
1967 /* We must check and increment the recursion depth here. Scenario:
1970 A.__call__ = A() # that's right
1972 a() # infinite recursion
1973 This bounces between instance_call() and PyObject_Call() without
1974 ever hitting eval_frame() (which has the main recursion check). */
1975 if (tstate
->recursion_depth
++ > Py_GetRecursionLimit()) {
1976 PyErr_SetString(PyExc_RuntimeError
,
1977 "maximum __call__ recursion depth exceeded");
1981 res
= PyObject_Call(call
, arg
, kw
);
1982 tstate
->recursion_depth
--;
1988 static PyNumberMethods instance_as_number
= {
1989 (binaryfunc
)instance_add
, /* nb_add */
1990 (binaryfunc
)instance_sub
, /* nb_subtract */
1991 (binaryfunc
)instance_mul
, /* nb_multiply */
1992 (binaryfunc
)instance_div
, /* nb_divide */
1993 (binaryfunc
)instance_mod
, /* nb_remainder */
1994 (binaryfunc
)instance_divmod
, /* nb_divmod */
1995 (ternaryfunc
)instance_pow
, /* nb_power */
1996 (unaryfunc
)instance_neg
, /* nb_negative */
1997 (unaryfunc
)instance_pos
, /* nb_positive */
1998 (unaryfunc
)instance_abs
, /* nb_absolute */
1999 (inquiry
)instance_nonzero
, /* nb_nonzero */
2000 (unaryfunc
)instance_invert
, /* nb_invert */
2001 (binaryfunc
)instance_lshift
, /* nb_lshift */
2002 (binaryfunc
)instance_rshift
, /* nb_rshift */
2003 (binaryfunc
)instance_and
, /* nb_and */
2004 (binaryfunc
)instance_xor
, /* nb_xor */
2005 (binaryfunc
)instance_or
, /* nb_or */
2006 (coercion
)instance_coerce
, /* nb_coerce */
2007 (unaryfunc
)instance_int
, /* nb_int */
2008 (unaryfunc
)instance_long
, /* nb_long */
2009 (unaryfunc
)instance_float
, /* nb_float */
2010 (unaryfunc
)instance_oct
, /* nb_oct */
2011 (unaryfunc
)instance_hex
, /* nb_hex */
2012 (binaryfunc
)instance_iadd
, /* nb_inplace_add */
2013 (binaryfunc
)instance_isub
, /* nb_inplace_subtract */
2014 (binaryfunc
)instance_imul
, /* nb_inplace_multiply */
2015 (binaryfunc
)instance_idiv
, /* nb_inplace_divide */
2016 (binaryfunc
)instance_imod
, /* nb_inplace_remainder */
2017 (ternaryfunc
)instance_ipow
, /* nb_inplace_power */
2018 (binaryfunc
)instance_ilshift
, /* nb_inplace_lshift */
2019 (binaryfunc
)instance_irshift
, /* nb_inplace_rshift */
2020 (binaryfunc
)instance_iand
, /* nb_inplace_and */
2021 (binaryfunc
)instance_ixor
, /* nb_inplace_xor */
2022 (binaryfunc
)instance_ior
, /* nb_inplace_or */
2023 (binaryfunc
)instance_floordiv
, /* nb_floor_divide */
2024 (binaryfunc
)instance_truediv
, /* nb_true_divide */
2025 (binaryfunc
)instance_ifloordiv
, /* nb_inplace_floor_divide */
2026 (binaryfunc
)instance_itruediv
, /* nb_inplace_true_divide */
2029 PyTypeObject PyInstance_Type
= {
2030 PyObject_HEAD_INIT(&PyType_Type
)
2033 sizeof(PyInstanceObject
),
2035 (destructor
)instance_dealloc
, /* tp_dealloc */
2039 instance_compare
, /* tp_compare */
2040 (reprfunc
)instance_repr
, /* tp_repr */
2041 &instance_as_number
, /* tp_as_number */
2042 &instance_as_sequence
, /* tp_as_sequence */
2043 &instance_as_mapping
, /* tp_as_mapping */
2044 (hashfunc
)instance_hash
, /* tp_hash */
2045 instance_call
, /* tp_call */
2046 (reprfunc
)instance_str
, /* tp_str */
2047 (getattrofunc
)instance_getattr
, /* tp_getattro */
2048 (setattrofunc
)instance_setattr
, /* tp_setattro */
2049 0, /* tp_as_buffer */
2050 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
,/*tp_flags*/
2051 instance_doc
, /* tp_doc */
2052 (traverseproc
)instance_traverse
, /* tp_traverse */
2054 instance_richcompare
, /* tp_richcompare */
2055 offsetof(PyInstanceObject
, in_weakreflist
), /* tp_weaklistoffset */
2056 (getiterfunc
)instance_getiter
, /* tp_iter */
2057 (iternextfunc
)instance_iternext
, /* tp_iternext */
2063 0, /* tp_descr_get */
2064 0, /* tp_descr_set */
2065 0, /* tp_dictoffset */
2068 instance_new
, /* tp_new */
2072 /* Instance method objects are used for two purposes:
2073 (a) as bound instance methods (returned by instancename.methodname)
2074 (b) as unbound methods (returned by ClassName.methodname)
2075 In case (b), im_self is NULL
2078 static PyMethodObject
*free_list
;
2081 PyMethod_New(PyObject
*func
, PyObject
*self
, PyObject
*class)
2083 register PyMethodObject
*im
;
2084 if (!PyCallable_Check(func
)) {
2085 PyErr_BadInternalCall();
2090 free_list
= (PyMethodObject
*)(im
->im_self
);
2091 PyObject_INIT(im
, &PyMethod_Type
);
2094 im
= PyObject_GC_New(PyMethodObject
, &PyMethod_Type
);
2098 im
->im_weakreflist
= NULL
;
2104 im
->im_class
= class;
2105 _PyObject_GC_TRACK(im
);
2106 return (PyObject
*)im
;
2109 /* Descriptors for PyMethod attributes */
2111 /* im_class, im_func and im_self are stored in the PyMethod object */
2113 #define OFF(x) offsetof(PyMethodObject, x)
2115 static PyMemberDef instancemethod_memberlist
[] = {
2116 {"im_class", T_OBJECT
, OFF(im_class
), READONLY
|RESTRICTED
,
2117 "the class associated with a method"},
2118 {"im_func", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2119 "the function (or other callable) implementing a method"},
2120 {"im_self", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2121 "the instance to which a method is bound; None for unbound methods"},
2122 {NULL
} /* Sentinel */
2125 /* The getattr() implementation for PyMethod objects is similar to
2126 PyObject_GenericGetAttr(), but instead of looking in __dict__ it
2127 asks im_self for the attribute. Then the error handling is a bit
2128 different because we want to preserve the exception raised by the
2129 delegate, unless we have an alternative from our class. */
2132 instancemethod_getattro(PyObject
*obj
, PyObject
*name
)
2134 PyMethodObject
*im
= (PyMethodObject
*)obj
;
2135 PyTypeObject
*tp
= obj
->ob_type
;
2136 PyObject
*descr
= NULL
, *res
;
2137 descrgetfunc f
= NULL
;
2139 if (PyType_HasFeature(tp
, Py_TPFLAGS_HAVE_CLASS
)) {
2140 if (tp
->tp_dict
== NULL
) {
2141 if (PyType_Ready(tp
) < 0)
2144 descr
= _PyType_Lookup(tp
, name
);
2148 if (descr
!= NULL
) {
2149 f
= TP_DESCR_GET(descr
->ob_type
);
2150 if (f
!= NULL
&& PyDescr_IsData(descr
))
2151 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2154 res
= PyObject_GetAttr(im
->im_func
, name
);
2155 if (res
!= NULL
|| !PyErr_ExceptionMatches(PyExc_AttributeError
))
2160 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2163 if (descr
!= NULL
) {
2169 assert(PyErr_Occurred());
2173 PyDoc_STRVAR(instancemethod_doc
,
2174 "instancemethod(function, instance, class)\n\
2176 Create an instance method object.");
2179 instancemethod_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
2185 if (!PyArg_ParseTuple(args
, "OOO:instancemethod",
2186 &func
, &self
, &classObj
))
2188 if (!PyCallable_Check(func
)) {
2189 PyErr_SetString(PyExc_TypeError
,
2190 "first argument must be callable");
2193 if (self
== Py_None
)
2195 return PyMethod_New(func
, self
, classObj
);
2199 instancemethod_dealloc(register PyMethodObject
*im
)
2201 _PyObject_GC_UNTRACK(im
);
2202 if (im
->im_weakreflist
!= NULL
)
2203 PyObject_ClearWeakRefs((PyObject
*)im
);
2204 Py_DECREF(im
->im_func
);
2205 Py_XDECREF(im
->im_self
);
2206 Py_XDECREF(im
->im_class
);
2207 im
->im_self
= (PyObject
*)free_list
;
2212 instancemethod_compare(PyMethodObject
*a
, PyMethodObject
*b
)
2214 if (a
->im_self
!= b
->im_self
)
2215 return (a
->im_self
< b
->im_self
) ? -1 : 1;
2216 return PyObject_Compare(a
->im_func
, b
->im_func
);
2220 instancemethod_repr(PyMethodObject
*a
)
2222 PyObject
*self
= a
->im_self
;
2223 PyObject
*func
= a
->im_func
;
2224 PyObject
*klass
= a
->im_class
;
2225 PyObject
*funcname
= NULL
, *klassname
= NULL
, *result
= NULL
;
2226 char *sfuncname
= "?", *sklassname
= "?";
2228 funcname
= PyObject_GetAttrString(func
, "__name__");
2229 if (funcname
== NULL
) {
2230 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2234 else if (!PyString_Check(funcname
)) {
2235 Py_DECREF(funcname
);
2239 sfuncname
= PyString_AS_STRING(funcname
);
2243 klassname
= PyObject_GetAttrString(klass
, "__name__");
2244 if (klassname
== NULL
) {
2245 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2249 else if (!PyString_Check(klassname
)) {
2250 Py_DECREF(klassname
);
2254 sklassname
= PyString_AS_STRING(klassname
);
2257 result
= PyString_FromFormat("<unbound method %s.%s>",
2258 sklassname
, sfuncname
);
2260 /* XXX Shouldn't use repr() here! */
2261 PyObject
*selfrepr
= PyObject_Repr(self
);
2262 if (selfrepr
== NULL
)
2264 if (!PyString_Check(selfrepr
)) {
2265 Py_DECREF(selfrepr
);
2268 result
= PyString_FromFormat("<bound method %s.%s of %s>",
2269 sklassname
, sfuncname
,
2270 PyString_AS_STRING(selfrepr
));
2271 Py_DECREF(selfrepr
);
2274 Py_XDECREF(funcname
);
2275 Py_XDECREF(klassname
);
2280 instancemethod_hash(PyMethodObject
*a
)
2283 if (a
->im_self
== NULL
)
2284 x
= PyObject_Hash(Py_None
);
2286 x
= PyObject_Hash(a
->im_self
);
2289 y
= PyObject_Hash(a
->im_func
);
2296 instancemethod_traverse(PyMethodObject
*im
, visitproc visit
, void *arg
)
2300 err
= visit(im
->im_func
, arg
);
2305 err
= visit(im
->im_self
, arg
);
2310 err
= visit(im
->im_class
, arg
);
2318 getclassname(PyObject
*class)
2325 name
= PyObject_GetAttrString(class, "__name__");
2327 /* This function cannot return an exception */
2331 if (!PyString_Check(name
)) {
2335 PyString_InternInPlace(&name
);
2337 return PyString_AS_STRING(name
);
2341 getinstclassname(PyObject
*inst
)
2349 class = PyObject_GetAttrString(inst
, "__class__");
2350 if (class == NULL
) {
2351 /* This function cannot return an exception */
2353 class = (PyObject
*)(inst
->ob_type
);
2356 name
= getclassname(class);
2362 instancemethod_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2364 PyObject
*self
= PyMethod_GET_SELF(func
);
2365 PyObject
*class = PyMethod_GET_CLASS(func
);
2368 func
= PyMethod_GET_FUNCTION(func
);
2370 /* Unbound methods must be called with an instance of
2371 the class (or a derived class) as first argument */
2373 if (PyTuple_Size(arg
) >= 1)
2374 self
= PyTuple_GET_ITEM(arg
, 0);
2378 ok
= PyObject_IsInstance(self
, class);
2383 PyErr_Format(PyExc_TypeError
,
2384 "unbound method %s%s must be called with "
2385 "%s instance as first argument "
2386 "(got %s%s instead)",
2387 PyEval_GetFuncName(func
),
2388 PyEval_GetFuncDesc(func
),
2389 getclassname(class),
2390 getinstclassname(self
),
2391 self
== NULL
? "" : " instance");
2397 int argcount
= PyTuple_Size(arg
);
2398 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2403 PyTuple_SET_ITEM(newarg
, 0, self
);
2404 for (i
= 0; i
< argcount
; i
++) {
2405 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2407 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2411 result
= PyObject_Call((PyObject
*)func
, arg
, kw
);
2417 instancemethod_descr_get(PyObject
*meth
, PyObject
*obj
, PyObject
*class)
2419 /* Don't rebind an already bound method, or an unbound method
2420 of a class that's not a base class of class */
2421 if (PyMethod_GET_SELF(meth
) != NULL
||
2422 (PyMethod_GET_CLASS(meth
) != NULL
&&
2423 !PyObject_IsSubclass(class, PyMethod_GET_CLASS(meth
)))) {
2429 return PyMethod_New(PyMethod_GET_FUNCTION(meth
), obj
, class);
2432 PyTypeObject PyMethod_Type
= {
2433 PyObject_HEAD_INIT(&PyType_Type
)
2436 sizeof(PyMethodObject
),
2438 (destructor
)instancemethod_dealloc
, /* tp_dealloc */
2442 (cmpfunc
)instancemethod_compare
, /* tp_compare */
2443 (reprfunc
)instancemethod_repr
, /* tp_repr */
2444 0, /* tp_as_number */
2445 0, /* tp_as_sequence */
2446 0, /* tp_as_mapping */
2447 (hashfunc
)instancemethod_hash
, /* tp_hash */
2448 instancemethod_call
, /* tp_call */
2450 (getattrofunc
)instancemethod_getattro
, /* tp_getattro */
2451 PyObject_GenericSetAttr
, /* tp_setattro */
2452 0, /* tp_as_buffer */
2453 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
2454 instancemethod_doc
, /* tp_doc */
2455 (traverseproc
)instancemethod_traverse
, /* tp_traverse */
2457 0, /* tp_richcompare */
2458 offsetof(PyMethodObject
, im_weakreflist
), /* tp_weaklistoffset */
2460 0, /* tp_iternext */
2462 instancemethod_memberlist
, /* tp_members */
2466 instancemethod_descr_get
, /* tp_descr_get */
2467 0, /* tp_descr_set */
2468 0, /* tp_dictoffset */
2471 instancemethod_new
, /* tp_new */
2474 /* Clear out the free list */
2480 PyMethodObject
*im
= free_list
;
2481 free_list
= (PyMethodObject
*)(im
->im_self
);
2482 PyObject_GC_Del(im
);