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 _PyObject_GC_UNTRACK(inst
);
620 if (inst
->in_weakreflist
!= NULL
)
621 PyObject_ClearWeakRefs((PyObject
*) inst
);
623 /* Temporarily resurrect the object. */
624 assert(inst
->ob_type
== &PyInstance_Type
);
625 assert(inst
->ob_refcnt
== 0);
628 /* Save the current exception, if any. */
629 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
630 /* Execute __del__ method, if any. */
632 delstr
= PyString_InternFromString("__del__");
633 if ((del
= instance_getattr2(inst
, delstr
)) != NULL
) {
634 PyObject
*res
= PyEval_CallObject(del
, (PyObject
*)NULL
);
636 PyErr_WriteUnraisable(del
);
641 /* Restore the saved exception. */
642 PyErr_Restore(error_type
, error_value
, error_traceback
);
644 /* Undo the temporary resurrection; can't use DECREF here, it would
645 * cause a recursive call.
647 assert(inst
->ob_refcnt
> 0);
648 if (--inst
->ob_refcnt
== 0) {
649 Py_DECREF(inst
->in_class
);
650 Py_XDECREF(inst
->in_dict
);
651 PyObject_GC_Del(inst
);
654 int refcnt
= inst
->ob_refcnt
;
655 /* __del__ resurrected it! Make it look like the original
656 * Py_DECREF never happened.
658 _Py_NewReference((PyObject
*)inst
);
659 inst
->ob_refcnt
= refcnt
;
660 _PyObject_GC_TRACK(inst
);
661 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal,
662 * but _Py_NewReference bumped it again, so that's a wash.
663 * If Py_TRACE_REFS, _Py_NewReference re-added self to the
664 * object chain, so no more to do there either.
665 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
666 * _Py_NewReference bumped tp_allocs: both of those need to
670 --inst
->ob_type
->tp_frees
;
671 --inst
->ob_type
->tp_allocs
;
677 instance_getattr1(register PyInstanceObject
*inst
, PyObject
*name
)
679 register PyObject
*v
;
680 register char *sname
= PyString_AsString(name
);
681 if (sname
[0] == '_' && sname
[1] == '_') {
682 if (strcmp(sname
, "__dict__") == 0) {
683 if (PyEval_GetRestricted()) {
684 PyErr_SetString(PyExc_RuntimeError
,
685 "instance.__dict__ not accessible in restricted mode");
688 Py_INCREF(inst
->in_dict
);
689 return inst
->in_dict
;
691 if (strcmp(sname
, "__class__") == 0) {
692 Py_INCREF(inst
->in_class
);
693 return (PyObject
*)inst
->in_class
;
696 v
= instance_getattr2(inst
, name
);
698 PyErr_Format(PyExc_AttributeError
,
699 "%.50s instance has no attribute '%.400s'",
700 PyString_AS_STRING(inst
->in_class
->cl_name
), sname
);
706 instance_getattr2(register PyInstanceObject
*inst
, PyObject
*name
)
708 register PyObject
*v
;
709 PyClassObject
*class;
712 v
= PyDict_GetItem(inst
->in_dict
, name
);
717 v
= class_lookup(inst
->in_class
, name
, &class);
720 f
= TP_DESCR_GET(v
->ob_type
);
722 PyObject
*w
= f(v
, (PyObject
*)inst
,
723 (PyObject
*)(inst
->in_class
));
732 instance_getattr(register PyInstanceObject
*inst
, PyObject
*name
)
734 register PyObject
*func
, *res
;
735 res
= instance_getattr1(inst
, name
);
736 if (res
== NULL
&& (func
= inst
->in_class
->cl_getattr
) != NULL
) {
738 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
741 args
= Py_BuildValue("(OO)", inst
, name
);
744 res
= PyEval_CallObject(func
, args
);
751 instance_setattr1(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
754 int rv
= PyDict_DelItem(inst
->in_dict
, name
);
756 PyErr_Format(PyExc_AttributeError
,
757 "%.50s instance has no attribute '%.400s'",
758 PyString_AS_STRING(inst
->in_class
->cl_name
),
759 PyString_AS_STRING(name
));
763 return PyDict_SetItem(inst
->in_dict
, name
, v
);
767 instance_setattr(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
769 PyObject
*func
, *args
, *res
, *tmp
;
770 char *sname
= PyString_AsString(name
);
771 if (sname
[0] == '_' && sname
[1] == '_') {
772 int n
= PyString_Size(name
);
773 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
774 if (strcmp(sname
, "__dict__") == 0) {
775 if (PyEval_GetRestricted()) {
776 PyErr_SetString(PyExc_RuntimeError
,
777 "__dict__ not accessible in restricted mode");
780 if (v
== NULL
|| !PyDict_Check(v
)) {
781 PyErr_SetString(PyExc_TypeError
,
782 "__dict__ must be set to a dictionary");
791 if (strcmp(sname
, "__class__") == 0) {
792 if (PyEval_GetRestricted()) {
793 PyErr_SetString(PyExc_RuntimeError
,
794 "__class__ not accessible in restricted mode");
797 if (v
== NULL
|| !PyClass_Check(v
)) {
798 PyErr_SetString(PyExc_TypeError
,
799 "__class__ must be set to a class");
802 tmp
= (PyObject
*)(inst
->in_class
);
804 inst
->in_class
= (PyClassObject
*)v
;
811 func
= inst
->in_class
->cl_delattr
;
813 func
= inst
->in_class
->cl_setattr
;
815 return instance_setattr1(inst
, name
, v
);
817 args
= Py_BuildValue("(OO)", inst
, name
);
819 args
= Py_BuildValue("(OOO)", inst
, name
, v
);
822 res
= PyEval_CallObject(func
, args
);
831 instance_repr(PyInstanceObject
*inst
)
835 static PyObject
*reprstr
;
838 reprstr
= PyString_InternFromString("__repr__");
839 func
= instance_getattr(inst
, reprstr
);
841 PyObject
*classname
, *mod
;
843 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
846 classname
= inst
->in_class
->cl_name
;
847 mod
= PyDict_GetItemString(inst
->in_class
->cl_dict
,
849 if (classname
!= NULL
&& PyString_Check(classname
))
850 cname
= PyString_AsString(classname
);
853 if (mod
== NULL
|| !PyString_Check(mod
))
854 return PyString_FromFormat("<?.%s instance at %p>",
857 return PyString_FromFormat("<%s.%s instance at %p>",
858 PyString_AsString(mod
),
861 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
867 instance_str(PyInstanceObject
*inst
)
871 static PyObject
*strstr
;
874 strstr
= PyString_InternFromString("__str__");
875 func
= instance_getattr(inst
, strstr
);
877 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
880 return instance_repr(inst
);
882 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
888 instance_hash(PyInstanceObject
*inst
)
893 static PyObject
*hashstr
, *eqstr
, *cmpstr
;
896 hashstr
= PyString_InternFromString("__hash__");
897 func
= instance_getattr(inst
, hashstr
);
899 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
902 /* If there is no __eq__ and no __cmp__ method, we hash on the
903 address. If an __eq__ or __cmp__ method exists, there must
906 eqstr
= PyString_InternFromString("__eq__");
907 func
= instance_getattr(inst
, eqstr
);
909 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
913 cmpstr
= PyString_InternFromString("__cmp__");
914 func
= instance_getattr(inst
, cmpstr
);
916 if (!PyErr_ExceptionMatches(
917 PyExc_AttributeError
))
920 return _Py_HashPointer(inst
);
923 PyErr_SetString(PyExc_TypeError
, "unhashable instance");
926 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
930 if (PyInt_Check(res
)) {
931 outcome
= PyInt_AsLong(res
);
936 PyErr_SetString(PyExc_TypeError
,
937 "__hash__() should return an int");
945 instance_traverse(PyInstanceObject
*o
, visitproc visit
, void *arg
)
949 err
= visit((PyObject
*)(o
->in_class
), arg
);
954 err
= visit(o
->in_dict
, arg
);
961 static PyObject
*getitemstr
, *setitemstr
, *delitemstr
, *lenstr
;
962 static PyObject
*iterstr
, *nextstr
;
965 instance_length(PyInstanceObject
*inst
)
972 lenstr
= PyString_InternFromString("__len__");
973 func
= instance_getattr(inst
, lenstr
);
976 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
980 if (PyInt_Check(res
)) {
981 outcome
= PyInt_AsLong(res
);
983 PyErr_SetString(PyExc_ValueError
,
984 "__len__() should return >= 0");
987 PyErr_SetString(PyExc_TypeError
,
988 "__len__() should return an int");
996 instance_subscript(PyInstanceObject
*inst
, PyObject
*key
)
1002 if (getitemstr
== NULL
)
1003 getitemstr
= PyString_InternFromString("__getitem__");
1004 func
= instance_getattr(inst
, getitemstr
);
1007 arg
= Py_BuildValue("(O)", key
);
1012 res
= PyEval_CallObject(func
, arg
);
1019 instance_ass_subscript(PyInstanceObject
*inst
, PyObject
*key
, PyObject
*value
)
1025 if (value
== NULL
) {
1026 if (delitemstr
== NULL
)
1027 delitemstr
= PyString_InternFromString("__delitem__");
1028 func
= instance_getattr(inst
, delitemstr
);
1031 if (setitemstr
== NULL
)
1032 setitemstr
= PyString_InternFromString("__setitem__");
1033 func
= instance_getattr(inst
, setitemstr
);
1038 arg
= Py_BuildValue("(O)", key
);
1040 arg
= Py_BuildValue("(OO)", key
, value
);
1045 res
= PyEval_CallObject(func
, arg
);
1054 static PyMappingMethods instance_as_mapping
= {
1055 (inquiry
)instance_length
, /* mp_length */
1056 (binaryfunc
)instance_subscript
, /* mp_subscript */
1057 (objobjargproc
)instance_ass_subscript
, /* mp_ass_subscript */
1061 instance_item(PyInstanceObject
*inst
, int i
)
1063 PyObject
*func
, *arg
, *res
;
1065 if (getitemstr
== NULL
)
1066 getitemstr
= PyString_InternFromString("__getitem__");
1067 func
= instance_getattr(inst
, getitemstr
);
1070 arg
= Py_BuildValue("(i)", i
);
1075 res
= PyEval_CallObject(func
, arg
);
1082 sliceobj_from_intint(int i
, int j
)
1084 PyObject
*start
, *end
, *res
;
1086 start
= PyInt_FromLong((long)i
);
1090 end
= PyInt_FromLong((long)j
);
1095 res
= PySlice_New(start
, end
, NULL
);
1103 instance_slice(PyInstanceObject
*inst
, int i
, int j
)
1105 PyObject
*func
, *arg
, *res
;
1106 static PyObject
*getslicestr
;
1108 if (getslicestr
== NULL
)
1109 getslicestr
= PyString_InternFromString("__getslice__");
1110 func
= instance_getattr(inst
, getslicestr
);
1113 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1117 if (getitemstr
== NULL
)
1118 getitemstr
= PyString_InternFromString("__getitem__");
1119 func
= instance_getattr(inst
, getitemstr
);
1122 arg
= Py_BuildValue("(N)", sliceobj_from_intint(i
, j
));
1124 arg
= Py_BuildValue("(ii)", i
, j
);
1130 res
= PyEval_CallObject(func
, arg
);
1137 instance_ass_item(PyInstanceObject
*inst
, int i
, PyObject
*item
)
1139 PyObject
*func
, *arg
, *res
;
1142 if (delitemstr
== NULL
)
1143 delitemstr
= PyString_InternFromString("__delitem__");
1144 func
= instance_getattr(inst
, delitemstr
);
1147 if (setitemstr
== NULL
)
1148 setitemstr
= PyString_InternFromString("__setitem__");
1149 func
= instance_getattr(inst
, setitemstr
);
1154 arg
= Py_BuildValue("i", i
);
1156 arg
= Py_BuildValue("(iO)", i
, item
);
1161 res
= PyEval_CallObject(func
, arg
);
1171 instance_ass_slice(PyInstanceObject
*inst
, int i
, int j
, PyObject
*value
)
1173 PyObject
*func
, *arg
, *res
;
1174 static PyObject
*setslicestr
, *delslicestr
;
1176 if (value
== NULL
) {
1177 if (delslicestr
== NULL
)
1179 PyString_InternFromString("__delslice__");
1180 func
= instance_getattr(inst
, delslicestr
);
1182 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1185 if (delitemstr
== NULL
)
1187 PyString_InternFromString("__delitem__");
1188 func
= instance_getattr(inst
, delitemstr
);
1192 arg
= Py_BuildValue("(N)",
1193 sliceobj_from_intint(i
, j
));
1195 arg
= Py_BuildValue("(ii)", i
, j
);
1198 if (setslicestr
== NULL
)
1200 PyString_InternFromString("__setslice__");
1201 func
= instance_getattr(inst
, setslicestr
);
1203 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1206 if (setitemstr
== NULL
)
1208 PyString_InternFromString("__setitem__");
1209 func
= instance_getattr(inst
, setitemstr
);
1213 arg
= Py_BuildValue("(NO)",
1214 sliceobj_from_intint(i
, j
), value
);
1216 arg
= Py_BuildValue("(iiO)", i
, j
, value
);
1222 res
= PyEval_CallObject(func
, arg
);
1232 instance_contains(PyInstanceObject
*inst
, PyObject
*member
)
1234 static PyObject
*__contains__
;
1237 /* Try __contains__ first.
1238 * If that can't be done, try iterator-based searching.
1241 if(__contains__
== NULL
) {
1242 __contains__
= PyString_InternFromString("__contains__");
1243 if(__contains__
== NULL
)
1246 func
= instance_getattr(inst
, __contains__
);
1250 PyObject
*arg
= Py_BuildValue("(O)", member
);
1255 res
= PyEval_CallObject(func
, arg
);
1260 ret
= PyObject_IsTrue(res
);
1265 /* Couldn't find __contains__. */
1266 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1267 /* Assume the failure was simply due to that there is no
1268 * __contains__ attribute, and try iterating instead.
1271 return _PySequence_IterSearch((PyObject
*)inst
, member
,
1272 PY_ITERSEARCH_CONTAINS
);
1278 static PySequenceMethods
1279 instance_as_sequence
= {
1280 (inquiry
)instance_length
, /* sq_length */
1283 (intargfunc
)instance_item
, /* sq_item */
1284 (intintargfunc
)instance_slice
, /* sq_slice */
1285 (intobjargproc
)instance_ass_item
, /* sq_ass_item */
1286 (intintobjargproc
)instance_ass_slice
, /* sq_ass_slice */
1287 (objobjproc
)instance_contains
, /* sq_contains */
1291 generic_unary_op(PyInstanceObject
*self
, PyObject
*methodname
)
1293 PyObject
*func
, *res
;
1295 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1297 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1303 generic_binary_op(PyObject
*v
, PyObject
*w
, char *opname
)
1307 PyObject
*func
= PyObject_GetAttrString(v
, opname
);
1309 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1312 Py_INCREF(Py_NotImplemented
);
1313 return Py_NotImplemented
;
1315 args
= Py_BuildValue("(O)", w
);
1320 result
= PyEval_CallObject(func
, args
);
1327 static PyObject
*coerce_obj
;
1329 /* Try one half of a binary operator involving a class instance. */
1331 half_binop(PyObject
*v
, PyObject
*w
, char *opname
, binaryfunc thisfunc
,
1335 PyObject
*coercefunc
;
1336 PyObject
*coerced
= NULL
;
1340 if (!PyInstance_Check(v
)) {
1341 Py_INCREF(Py_NotImplemented
);
1342 return Py_NotImplemented
;
1345 if (coerce_obj
== NULL
) {
1346 coerce_obj
= PyString_InternFromString("__coerce__");
1347 if (coerce_obj
== NULL
)
1350 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1351 if (coercefunc
== NULL
) {
1352 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1355 return generic_binary_op(v
, w
, opname
);
1358 args
= Py_BuildValue("(O)", w
);
1362 coerced
= PyEval_CallObject(coercefunc
, args
);
1364 Py_DECREF(coercefunc
);
1365 if (coerced
== NULL
) {
1368 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1370 return generic_binary_op(v
, w
, opname
);
1372 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1374 PyErr_SetString(PyExc_TypeError
,
1375 "coercion should return None or 2-tuple");
1378 v1
= PyTuple_GetItem(coerced
, 0);
1379 w
= PyTuple_GetItem(coerced
, 1);
1380 if (v1
->ob_type
== v
->ob_type
&& PyInstance_Check(v
)) {
1381 /* prevent recursion if __coerce__ returns self as the first
1383 result
= generic_binary_op(v1
, w
, opname
);
1386 result
= (thisfunc
)(w
, v1
);
1388 result
= (thisfunc
)(v1
, w
);
1394 /* Implement a binary operator involving at least one class instance. */
1396 do_binop(PyObject
*v
, PyObject
*w
, char *opname
, char *ropname
,
1397 binaryfunc thisfunc
)
1399 PyObject
*result
= half_binop(v
, w
, opname
, thisfunc
, 0);
1400 if (result
== Py_NotImplemented
) {
1402 result
= half_binop(w
, v
, ropname
, thisfunc
, 1);
1408 do_binop_inplace(PyObject
*v
, PyObject
*w
, char *iopname
, char *opname
,
1409 char *ropname
, binaryfunc thisfunc
)
1411 PyObject
*result
= half_binop(v
, w
, iopname
, thisfunc
, 0);
1412 if (result
== Py_NotImplemented
) {
1414 result
= do_binop(v
, w
, opname
, ropname
, thisfunc
);
1420 instance_coerce(PyObject
**pv
, PyObject
**pw
)
1424 PyObject
*coercefunc
;
1428 if (coerce_obj
== NULL
) {
1429 coerce_obj
= PyString_InternFromString("__coerce__");
1430 if (coerce_obj
== NULL
)
1433 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1434 if (coercefunc
== NULL
) {
1435 /* No __coerce__ method */
1436 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1441 /* Has __coerce__ method: call it */
1442 args
= Py_BuildValue("(O)", w
);
1446 coerced
= PyEval_CallObject(coercefunc
, args
);
1448 Py_DECREF(coercefunc
);
1449 if (coerced
== NULL
) {
1450 /* __coerce__ call raised an exception */
1453 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1454 /* __coerce__ says "I can't do it" */
1458 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1459 /* __coerce__ return value is malformed */
1461 PyErr_SetString(PyExc_TypeError
,
1462 "coercion should return None or 2-tuple");
1465 /* __coerce__ returned two new values */
1466 *pv
= PyTuple_GetItem(coerced
, 0);
1467 *pw
= PyTuple_GetItem(coerced
, 1);
1474 #define UNARY(funcname, methodname) \
1475 static PyObject *funcname(PyInstanceObject *self) { \
1476 static PyObject *o; \
1477 if (o == NULL) o = PyString_InternFromString(methodname); \
1478 return generic_unary_op(self, o); \
1481 #define BINARY(f, m, n) \
1482 static PyObject *f(PyObject *v, PyObject *w) { \
1483 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1486 #define BINARY_INPLACE(f, m, n) \
1487 static PyObject *f(PyObject *v, PyObject *w) { \
1488 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1492 UNARY(instance_neg
, "__neg__")
1493 UNARY(instance_pos
, "__pos__")
1494 UNARY(instance_abs
, "__abs__")
1496 BINARY(instance_or
, "or", PyNumber_Or
)
1497 BINARY(instance_and
, "and", PyNumber_And
)
1498 BINARY(instance_xor
, "xor", PyNumber_Xor
)
1499 BINARY(instance_lshift
, "lshift", PyNumber_Lshift
)
1500 BINARY(instance_rshift
, "rshift", PyNumber_Rshift
)
1501 BINARY(instance_add
, "add", PyNumber_Add
)
1502 BINARY(instance_sub
, "sub", PyNumber_Subtract
)
1503 BINARY(instance_mul
, "mul", PyNumber_Multiply
)
1504 BINARY(instance_div
, "div", PyNumber_Divide
)
1505 BINARY(instance_mod
, "mod", PyNumber_Remainder
)
1506 BINARY(instance_divmod
, "divmod", PyNumber_Divmod
)
1507 BINARY(instance_floordiv
, "floordiv", PyNumber_FloorDivide
)
1508 BINARY(instance_truediv
, "truediv", PyNumber_TrueDivide
)
1510 BINARY_INPLACE(instance_ior
, "or", PyNumber_InPlaceOr
)
1511 BINARY_INPLACE(instance_ixor
, "xor", PyNumber_InPlaceXor
)
1512 BINARY_INPLACE(instance_iand
, "and", PyNumber_InPlaceAnd
)
1513 BINARY_INPLACE(instance_ilshift
, "lshift", PyNumber_InPlaceLshift
)
1514 BINARY_INPLACE(instance_irshift
, "rshift", PyNumber_InPlaceRshift
)
1515 BINARY_INPLACE(instance_iadd
, "add", PyNumber_InPlaceAdd
)
1516 BINARY_INPLACE(instance_isub
, "sub", PyNumber_InPlaceSubtract
)
1517 BINARY_INPLACE(instance_imul
, "mul", PyNumber_InPlaceMultiply
)
1518 BINARY_INPLACE(instance_idiv
, "div", PyNumber_InPlaceDivide
)
1519 BINARY_INPLACE(instance_imod
, "mod", PyNumber_InPlaceRemainder
)
1520 BINARY_INPLACE(instance_ifloordiv
, "floordiv", PyNumber_InPlaceFloorDivide
)
1521 BINARY_INPLACE(instance_itruediv
, "truediv", PyNumber_InPlaceTrueDivide
)
1523 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1524 -2 for an exception;
1528 2 if this particular 3-way comparison is not implemented or undefined.
1531 half_cmp(PyObject
*v
, PyObject
*w
)
1533 static PyObject
*cmp_obj
;
1539 assert(PyInstance_Check(v
));
1541 if (cmp_obj
== NULL
) {
1542 cmp_obj
= PyString_InternFromString("__cmp__");
1543 if (cmp_obj
== NULL
)
1547 cmp_func
= PyObject_GetAttr(v
, cmp_obj
);
1548 if (cmp_func
== NULL
) {
1549 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1555 args
= Py_BuildValue("(O)", w
);
1559 result
= PyEval_CallObject(cmp_func
, args
);
1561 Py_DECREF(cmp_func
);
1566 if (result
== Py_NotImplemented
) {
1571 l
= PyInt_AsLong(result
);
1573 if (l
== -1 && PyErr_Occurred()) {
1574 PyErr_SetString(PyExc_TypeError
,
1575 "comparison did not return an int");
1579 return l
< 0 ? -1 : l
> 0 ? 1 : 0;
1582 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1583 We first try a coercion. Return:
1584 -2 for an exception;
1588 2 if this particular 3-way comparison is not implemented or undefined.
1589 THIS IS ONLY CALLED FROM object.c!
1592 instance_compare(PyObject
*v
, PyObject
*w
)
1596 c
= PyNumber_CoerceEx(&v
, &w
);
1600 /* If neither is now an instance, use regular comparison */
1601 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1602 c
= PyObject_Compare(v
, w
);
1605 if (PyErr_Occurred())
1607 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
1611 /* The coercion didn't do anything.
1612 Treat this the same as returning v and w unchanged. */
1617 if (PyInstance_Check(v
)) {
1625 if (PyInstance_Check(w
)) {
1641 instance_nonzero(PyInstanceObject
*self
)
1643 PyObject
*func
, *res
;
1645 static PyObject
*nonzerostr
;
1647 if (nonzerostr
== NULL
)
1648 nonzerostr
= PyString_InternFromString("__nonzero__");
1649 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1650 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1654 lenstr
= PyString_InternFromString("__len__");
1655 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1656 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1659 /* Fall back to the default behavior:
1660 all instances are nonzero */
1664 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1668 if (!PyInt_Check(res
)) {
1670 PyErr_SetString(PyExc_TypeError
,
1671 "__nonzero__ should return an int");
1674 outcome
= PyInt_AsLong(res
);
1677 PyErr_SetString(PyExc_ValueError
,
1678 "__nonzero__ should return >= 0");
1684 UNARY(instance_invert
, "__invert__")
1685 UNARY(instance_int
, "__int__")
1686 UNARY(instance_long
, "__long__")
1687 UNARY(instance_float
, "__float__")
1688 UNARY(instance_oct
, "__oct__")
1689 UNARY(instance_hex
, "__hex__")
1692 bin_power(PyObject
*v
, PyObject
*w
)
1694 return PyNumber_Power(v
, w
, Py_None
);
1697 /* This version is for ternary calls only (z != None) */
1699 instance_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1702 return do_binop(v
, w
, "__pow__", "__rpow__", bin_power
);
1709 /* XXX Doesn't do coercions... */
1710 func
= PyObject_GetAttrString(v
, "__pow__");
1713 args
= Py_BuildValue("(OO)", w
, z
);
1718 result
= PyEval_CallObject(func
, args
);
1726 bin_inplace_power(PyObject
*v
, PyObject
*w
)
1728 return PyNumber_InPlacePower(v
, w
, Py_None
);
1733 instance_ipow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1736 return do_binop_inplace(v
, w
, "__ipow__", "__pow__",
1737 "__rpow__", bin_inplace_power
);
1740 /* XXX Doesn't do coercions... */
1745 func
= PyObject_GetAttrString(v
, "__ipow__");
1747 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1750 return instance_pow(v
, w
, z
);
1752 args
= Py_BuildValue("(OO)", w
, z
);
1757 result
= PyEval_CallObject(func
, args
);
1765 /* Map rich comparison operators to their __xx__ namesakes */
1767 static PyObject
**name_op
= NULL
;
1773 char *_name_op
[] = {
1782 name_op
= (PyObject
**)malloc(sizeof(PyObject
*) * NAME_OPS
);
1783 if (name_op
== NULL
)
1785 for (i
= 0; i
< NAME_OPS
; ++i
) {
1786 name_op
[i
] = PyString_InternFromString(_name_op
[i
]);
1787 if (name_op
[i
] == NULL
)
1794 half_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1800 assert(PyInstance_Check(v
));
1802 if (name_op
== NULL
) {
1803 if (init_name_op() < 0)
1806 /* If the instance doesn't define an __getattr__ method, use
1807 instance_getattr2 directly because it will not set an
1808 exception on failure. */
1809 if (((PyInstanceObject
*)v
)->in_class
->cl_getattr
== NULL
) {
1810 method
= instance_getattr2((PyInstanceObject
*)v
,
1812 if (method
== NULL
) {
1813 assert(!PyErr_Occurred());
1814 res
= Py_NotImplemented
;
1819 method
= PyObject_GetAttr(v
, name_op
[op
]);
1820 if (method
== NULL
) {
1821 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1824 res
= Py_NotImplemented
;
1830 args
= Py_BuildValue("(O)", w
);
1836 res
= PyEval_CallObject(method
, args
);
1843 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1844 static int swapped_op
[] = {Py_GT
, Py_GE
, Py_EQ
, Py_NE
, Py_LT
, Py_LE
};
1847 instance_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1851 if (PyInstance_Check(v
)) {
1852 res
= half_richcompare(v
, w
, op
);
1853 if (res
!= Py_NotImplemented
)
1858 if (PyInstance_Check(w
)) {
1859 res
= half_richcompare(w
, v
, swapped_op
[op
]);
1860 if (res
!= Py_NotImplemented
)
1865 Py_INCREF(Py_NotImplemented
);
1866 return Py_NotImplemented
;
1870 /* Get the iterator */
1872 instance_getiter(PyInstanceObject
*self
)
1876 if (iterstr
== NULL
) {
1877 iterstr
= PyString_InternFromString("__iter__");
1878 if (iterstr
== NULL
)
1881 if (getitemstr
== NULL
) {
1882 getitemstr
= PyString_InternFromString("__getitem__");
1883 if (getitemstr
== NULL
)
1887 if ((func
= instance_getattr(self
, iterstr
)) != NULL
) {
1888 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1890 if (res
!= NULL
&& !PyIter_Check(res
)) {
1891 PyErr_Format(PyExc_TypeError
,
1892 "__iter__ returned non-iterator "
1894 res
->ob_type
->tp_name
);
1900 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1903 if ((func
= instance_getattr(self
, getitemstr
)) == NULL
) {
1904 PyErr_SetString(PyExc_TypeError
,
1905 "iteration over non-sequence");
1909 return PySeqIter_New((PyObject
*)self
);
1913 /* Call the iterator's next */
1915 instance_iternext(PyInstanceObject
*self
)
1919 if (nextstr
== NULL
)
1920 nextstr
= PyString_InternFromString("next");
1922 if ((func
= instance_getattr(self
, nextstr
)) != NULL
) {
1923 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1928 if (PyErr_ExceptionMatches(PyExc_StopIteration
)) {
1934 PyErr_SetString(PyExc_TypeError
, "instance has no next() method");
1939 instance_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
1941 PyThreadState
*tstate
= PyThreadState_GET();
1942 PyObject
*res
, *call
= PyObject_GetAttrString(func
, "__call__");
1944 PyInstanceObject
*inst
= (PyInstanceObject
*) func
;
1945 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1948 PyErr_Format(PyExc_AttributeError
,
1949 "%.200s instance has no __call__ method",
1950 PyString_AsString(inst
->in_class
->cl_name
));
1953 /* We must check and increment the recursion depth here. Scenario:
1956 A.__call__ = A() # that's right
1958 a() # infinite recursion
1959 This bounces between instance_call() and PyObject_Call() without
1960 ever hitting eval_frame() (which has the main recursion check). */
1961 if (tstate
->recursion_depth
++ > Py_GetRecursionLimit()) {
1962 PyErr_SetString(PyExc_RuntimeError
,
1963 "maximum __call__ recursion depth exceeded");
1967 res
= PyObject_Call(call
, arg
, kw
);
1968 tstate
->recursion_depth
--;
1974 static PyNumberMethods instance_as_number
= {
1975 (binaryfunc
)instance_add
, /* nb_add */
1976 (binaryfunc
)instance_sub
, /* nb_subtract */
1977 (binaryfunc
)instance_mul
, /* nb_multiply */
1978 (binaryfunc
)instance_div
, /* nb_divide */
1979 (binaryfunc
)instance_mod
, /* nb_remainder */
1980 (binaryfunc
)instance_divmod
, /* nb_divmod */
1981 (ternaryfunc
)instance_pow
, /* nb_power */
1982 (unaryfunc
)instance_neg
, /* nb_negative */
1983 (unaryfunc
)instance_pos
, /* nb_positive */
1984 (unaryfunc
)instance_abs
, /* nb_absolute */
1985 (inquiry
)instance_nonzero
, /* nb_nonzero */
1986 (unaryfunc
)instance_invert
, /* nb_invert */
1987 (binaryfunc
)instance_lshift
, /* nb_lshift */
1988 (binaryfunc
)instance_rshift
, /* nb_rshift */
1989 (binaryfunc
)instance_and
, /* nb_and */
1990 (binaryfunc
)instance_xor
, /* nb_xor */
1991 (binaryfunc
)instance_or
, /* nb_or */
1992 (coercion
)instance_coerce
, /* nb_coerce */
1993 (unaryfunc
)instance_int
, /* nb_int */
1994 (unaryfunc
)instance_long
, /* nb_long */
1995 (unaryfunc
)instance_float
, /* nb_float */
1996 (unaryfunc
)instance_oct
, /* nb_oct */
1997 (unaryfunc
)instance_hex
, /* nb_hex */
1998 (binaryfunc
)instance_iadd
, /* nb_inplace_add */
1999 (binaryfunc
)instance_isub
, /* nb_inplace_subtract */
2000 (binaryfunc
)instance_imul
, /* nb_inplace_multiply */
2001 (binaryfunc
)instance_idiv
, /* nb_inplace_divide */
2002 (binaryfunc
)instance_imod
, /* nb_inplace_remainder */
2003 (ternaryfunc
)instance_ipow
, /* nb_inplace_power */
2004 (binaryfunc
)instance_ilshift
, /* nb_inplace_lshift */
2005 (binaryfunc
)instance_irshift
, /* nb_inplace_rshift */
2006 (binaryfunc
)instance_iand
, /* nb_inplace_and */
2007 (binaryfunc
)instance_ixor
, /* nb_inplace_xor */
2008 (binaryfunc
)instance_ior
, /* nb_inplace_or */
2009 (binaryfunc
)instance_floordiv
, /* nb_floor_divide */
2010 (binaryfunc
)instance_truediv
, /* nb_true_divide */
2011 (binaryfunc
)instance_ifloordiv
, /* nb_inplace_floor_divide */
2012 (binaryfunc
)instance_itruediv
, /* nb_inplace_true_divide */
2015 PyTypeObject PyInstance_Type
= {
2016 PyObject_HEAD_INIT(&PyType_Type
)
2019 sizeof(PyInstanceObject
),
2021 (destructor
)instance_dealloc
, /* tp_dealloc */
2025 instance_compare
, /* tp_compare */
2026 (reprfunc
)instance_repr
, /* tp_repr */
2027 &instance_as_number
, /* tp_as_number */
2028 &instance_as_sequence
, /* tp_as_sequence */
2029 &instance_as_mapping
, /* tp_as_mapping */
2030 (hashfunc
)instance_hash
, /* tp_hash */
2031 instance_call
, /* tp_call */
2032 (reprfunc
)instance_str
, /* tp_str */
2033 (getattrofunc
)instance_getattr
, /* tp_getattro */
2034 (setattrofunc
)instance_setattr
, /* tp_setattro */
2035 0, /* tp_as_buffer */
2036 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
,/*tp_flags*/
2037 instance_doc
, /* tp_doc */
2038 (traverseproc
)instance_traverse
, /* tp_traverse */
2040 instance_richcompare
, /* tp_richcompare */
2041 offsetof(PyInstanceObject
, in_weakreflist
), /* tp_weaklistoffset */
2042 (getiterfunc
)instance_getiter
, /* tp_iter */
2043 (iternextfunc
)instance_iternext
, /* tp_iternext */
2049 0, /* tp_descr_get */
2050 0, /* tp_descr_set */
2051 0, /* tp_dictoffset */
2054 instance_new
, /* tp_new */
2058 /* Instance method objects are used for two purposes:
2059 (a) as bound instance methods (returned by instancename.methodname)
2060 (b) as unbound methods (returned by ClassName.methodname)
2061 In case (b), im_self is NULL
2064 static PyMethodObject
*free_list
;
2067 PyMethod_New(PyObject
*func
, PyObject
*self
, PyObject
*class)
2069 register PyMethodObject
*im
;
2070 if (!PyCallable_Check(func
)) {
2071 PyErr_BadInternalCall();
2076 free_list
= (PyMethodObject
*)(im
->im_self
);
2077 PyObject_INIT(im
, &PyMethod_Type
);
2080 im
= PyObject_GC_New(PyMethodObject
, &PyMethod_Type
);
2084 im
->im_weakreflist
= NULL
;
2090 im
->im_class
= class;
2091 _PyObject_GC_TRACK(im
);
2092 return (PyObject
*)im
;
2095 /* Descriptors for PyMethod attributes */
2097 /* im_class, im_func and im_self are stored in the PyMethod object */
2099 #define OFF(x) offsetof(PyMethodObject, x)
2101 static PyMemberDef instancemethod_memberlist
[] = {
2102 {"im_class", T_OBJECT
, OFF(im_class
), READONLY
|RESTRICTED
,
2103 "the class associated with a method"},
2104 {"im_func", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2105 "the function (or other callable) implementing a method"},
2106 {"im_self", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2107 "the instance to which a method is bound; None for unbound methods"},
2108 {NULL
} /* Sentinel */
2111 /* The getattr() implementation for PyMethod objects is similar to
2112 PyObject_GenericGetAttr(), but instead of looking in __dict__ it
2113 asks im_self for the attribute. Then the error handling is a bit
2114 different because we want to preserve the exception raised by the
2115 delegate, unless we have an alternative from our class. */
2118 instancemethod_getattro(PyObject
*obj
, PyObject
*name
)
2120 PyMethodObject
*im
= (PyMethodObject
*)obj
;
2121 PyTypeObject
*tp
= obj
->ob_type
;
2122 PyObject
*descr
= NULL
, *res
;
2123 descrgetfunc f
= NULL
;
2125 if (PyType_HasFeature(tp
, Py_TPFLAGS_HAVE_CLASS
)) {
2126 if (tp
->tp_dict
== NULL
) {
2127 if (PyType_Ready(tp
) < 0)
2130 descr
= _PyType_Lookup(tp
, name
);
2134 if (descr
!= NULL
) {
2135 f
= TP_DESCR_GET(descr
->ob_type
);
2136 if (f
!= NULL
&& PyDescr_IsData(descr
))
2137 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2140 res
= PyObject_GetAttr(im
->im_func
, name
);
2141 if (res
!= NULL
|| !PyErr_ExceptionMatches(PyExc_AttributeError
))
2146 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2149 if (descr
!= NULL
) {
2155 assert(PyErr_Occurred());
2159 PyDoc_STRVAR(instancemethod_doc
,
2160 "instancemethod(function, instance, class)\n\
2162 Create an instance method object.");
2165 instancemethod_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
2171 if (!PyArg_ParseTuple(args
, "OOO:instancemethod",
2172 &func
, &self
, &classObj
))
2174 if (!PyCallable_Check(func
)) {
2175 PyErr_SetString(PyExc_TypeError
,
2176 "first argument must be callable");
2179 if (self
== Py_None
)
2181 return PyMethod_New(func
, self
, classObj
);
2185 instancemethod_dealloc(register PyMethodObject
*im
)
2187 _PyObject_GC_UNTRACK(im
);
2188 if (im
->im_weakreflist
!= NULL
)
2189 PyObject_ClearWeakRefs((PyObject
*)im
);
2190 Py_DECREF(im
->im_func
);
2191 Py_XDECREF(im
->im_self
);
2192 Py_XDECREF(im
->im_class
);
2193 im
->im_self
= (PyObject
*)free_list
;
2198 instancemethod_compare(PyMethodObject
*a
, PyMethodObject
*b
)
2200 if (a
->im_self
!= b
->im_self
)
2201 return (a
->im_self
< b
->im_self
) ? -1 : 1;
2202 return PyObject_Compare(a
->im_func
, b
->im_func
);
2206 instancemethod_repr(PyMethodObject
*a
)
2208 PyObject
*self
= a
->im_self
;
2209 PyObject
*func
= a
->im_func
;
2210 PyObject
*klass
= a
->im_class
;
2211 PyObject
*funcname
= NULL
, *klassname
= NULL
, *result
= NULL
;
2212 char *sfuncname
= "?", *sklassname
= "?";
2214 funcname
= PyObject_GetAttrString(func
, "__name__");
2215 if (funcname
== NULL
) {
2216 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2220 else if (!PyString_Check(funcname
)) {
2221 Py_DECREF(funcname
);
2225 sfuncname
= PyString_AS_STRING(funcname
);
2229 klassname
= PyObject_GetAttrString(klass
, "__name__");
2230 if (klassname
== NULL
) {
2231 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2235 else if (!PyString_Check(klassname
)) {
2236 Py_DECREF(klassname
);
2240 sklassname
= PyString_AS_STRING(klassname
);
2243 result
= PyString_FromFormat("<unbound method %s.%s>",
2244 sklassname
, sfuncname
);
2246 /* XXX Shouldn't use repr() here! */
2247 PyObject
*selfrepr
= PyObject_Repr(self
);
2248 if (selfrepr
== NULL
)
2250 if (!PyString_Check(selfrepr
)) {
2251 Py_DECREF(selfrepr
);
2254 result
= PyString_FromFormat("<bound method %s.%s of %s>",
2255 sklassname
, sfuncname
,
2256 PyString_AS_STRING(selfrepr
));
2257 Py_DECREF(selfrepr
);
2260 Py_XDECREF(funcname
);
2261 Py_XDECREF(klassname
);
2266 instancemethod_hash(PyMethodObject
*a
)
2269 if (a
->im_self
== NULL
)
2270 x
= PyObject_Hash(Py_None
);
2272 x
= PyObject_Hash(a
->im_self
);
2275 y
= PyObject_Hash(a
->im_func
);
2282 instancemethod_traverse(PyMethodObject
*im
, visitproc visit
, void *arg
)
2286 err
= visit(im
->im_func
, arg
);
2291 err
= visit(im
->im_self
, arg
);
2296 err
= visit(im
->im_class
, arg
);
2304 getclassname(PyObject
*class, char *buf
, int bufsize
)
2308 assert(bufsize
> 1);
2309 strcpy(buf
, "?"); /* Default outcome */
2312 name
= PyObject_GetAttrString(class, "__name__");
2314 /* This function cannot return an exception */
2318 if (PyString_Check(name
)) {
2319 strncpy(buf
, PyString_AS_STRING(name
), bufsize
);
2320 buf
[bufsize
-1] = '\0';
2326 getinstclassname(PyObject
*inst
, char *buf
, int bufsize
)
2331 assert(bufsize
> 0 && (size_t)bufsize
> strlen("nothing"));
2332 strcpy(buf
, "nothing");
2336 class = PyObject_GetAttrString(inst
, "__class__");
2337 if (class == NULL
) {
2338 /* This function cannot return an exception */
2340 class = (PyObject
*)(inst
->ob_type
);
2343 getclassname(class, buf
, bufsize
);
2348 instancemethod_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2350 PyObject
*self
= PyMethod_GET_SELF(func
);
2351 PyObject
*class = PyMethod_GET_CLASS(func
);
2354 func
= PyMethod_GET_FUNCTION(func
);
2356 /* Unbound methods must be called with an instance of
2357 the class (or a derived class) as first argument */
2359 if (PyTuple_Size(arg
) >= 1)
2360 self
= PyTuple_GET_ITEM(arg
, 0);
2364 ok
= PyObject_IsInstance(self
, class);
2371 getclassname(class, clsbuf
, sizeof(clsbuf
));
2372 getinstclassname(self
, instbuf
, sizeof(instbuf
));
2373 PyErr_Format(PyExc_TypeError
,
2374 "unbound method %s%s must be called with "
2375 "%s instance as first argument "
2376 "(got %s%s instead)",
2377 PyEval_GetFuncName(func
),
2378 PyEval_GetFuncDesc(func
),
2381 self
== NULL
? "" : " instance");
2387 int argcount
= PyTuple_Size(arg
);
2388 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2393 PyTuple_SET_ITEM(newarg
, 0, self
);
2394 for (i
= 0; i
< argcount
; i
++) {
2395 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2397 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2401 result
= PyObject_Call((PyObject
*)func
, arg
, kw
);
2407 instancemethod_descr_get(PyObject
*meth
, PyObject
*obj
, PyObject
*class)
2409 /* Don't rebind an already bound method, or an unbound method
2410 of a class that's not a base class of class */
2411 if (PyMethod_GET_SELF(meth
) != NULL
||
2412 (PyMethod_GET_CLASS(meth
) != NULL
&&
2413 !PyObject_IsSubclass(class, PyMethod_GET_CLASS(meth
)))) {
2419 return PyMethod_New(PyMethod_GET_FUNCTION(meth
), obj
, class);
2422 PyTypeObject PyMethod_Type
= {
2423 PyObject_HEAD_INIT(&PyType_Type
)
2426 sizeof(PyMethodObject
),
2428 (destructor
)instancemethod_dealloc
, /* tp_dealloc */
2432 (cmpfunc
)instancemethod_compare
, /* tp_compare */
2433 (reprfunc
)instancemethod_repr
, /* tp_repr */
2434 0, /* tp_as_number */
2435 0, /* tp_as_sequence */
2436 0, /* tp_as_mapping */
2437 (hashfunc
)instancemethod_hash
, /* tp_hash */
2438 instancemethod_call
, /* tp_call */
2440 (getattrofunc
)instancemethod_getattro
, /* tp_getattro */
2441 PyObject_GenericSetAttr
, /* tp_setattro */
2442 0, /* tp_as_buffer */
2443 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
2444 instancemethod_doc
, /* tp_doc */
2445 (traverseproc
)instancemethod_traverse
, /* tp_traverse */
2447 0, /* tp_richcompare */
2448 offsetof(PyMethodObject
, im_weakreflist
), /* tp_weaklistoffset */
2450 0, /* tp_iternext */
2452 instancemethod_memberlist
, /* tp_members */
2456 instancemethod_descr_get
, /* tp_descr_get */
2457 0, /* tp_descr_set */
2458 0, /* tp_dictoffset */
2461 instancemethod_new
, /* tp_new */
2464 /* Clear out the free list */
2470 PyMethodObject
*im
= free_list
;
2471 free_list
= (PyMethodObject
*)(im
->im_self
);
2472 PyObject_GC_Del(im
);