2 /* Class object implementation */
5 #include "structmember.h"
9 static PyObject
*class_lookup(PyClassObject
*, PyObject
*,
11 static PyObject
*instance_getattr1(PyInstanceObject
*, PyObject
*);
12 static PyObject
*instance_getattr2(PyInstanceObject
*, PyObject
*);
14 static PyObject
*getattrstr
, *setattrstr
, *delattrstr
;
18 PyClass_New(PyObject
*bases
, PyObject
*dict
, PyObject
*name
)
19 /* bases is NULL or tuple of classobjects! */
21 PyClassObject
*op
, *dummy
;
22 static PyObject
*docstr
, *modstr
, *namestr
;
24 docstr
= PyString_InternFromString("__doc__");
29 modstr
= PyString_InternFromString("__module__");
33 if (namestr
== NULL
) {
34 namestr
= PyString_InternFromString("__name__");
38 if (name
== NULL
|| !PyString_Check(name
)) {
39 PyErr_SetString(PyExc_TypeError
,
40 "PyClass_New: name must be a string");
43 if (dict
== NULL
|| !PyDict_Check(dict
)) {
44 PyErr_SetString(PyExc_TypeError
,
45 "PyClass_New: dict must be a dictionary");
48 if (PyDict_GetItem(dict
, docstr
) == NULL
) {
49 if (PyDict_SetItem(dict
, docstr
, Py_None
) < 0)
52 if (PyDict_GetItem(dict
, modstr
) == NULL
) {
53 PyObject
*globals
= PyEval_GetGlobals();
54 if (globals
!= NULL
) {
55 PyObject
*modname
= PyDict_GetItem(globals
, namestr
);
56 if (modname
!= NULL
) {
57 if (PyDict_SetItem(dict
, modstr
, modname
) < 0)
63 bases
= PyTuple_New(0);
70 if (!PyTuple_Check(bases
)) {
71 PyErr_SetString(PyExc_TypeError
,
72 "PyClass_New: bases must be a tuple");
75 n
= PyTuple_Size(bases
);
76 for (i
= 0; i
< n
; i
++) {
77 base
= PyTuple_GET_ITEM(bases
, i
);
78 if (!PyClass_Check(base
)) {
80 (PyObject
*) base
->ob_type
))
81 return PyObject_CallFunction(
82 (PyObject
*) base
->ob_type
,
87 PyErr_SetString(PyExc_TypeError
,
88 "PyClass_New: base must be a class");
94 op
= PyObject_GC_New(PyClassObject
, &PyClass_Type
);
104 if (getattrstr
== NULL
) {
105 getattrstr
= PyString_InternFromString("__getattr__");
106 setattrstr
= PyString_InternFromString("__setattr__");
107 delattrstr
= PyString_InternFromString("__delattr__");
109 op
->cl_getattr
= class_lookup(op
, getattrstr
, &dummy
);
110 op
->cl_setattr
= class_lookup(op
, setattrstr
, &dummy
);
111 op
->cl_delattr
= class_lookup(op
, delattrstr
, &dummy
);
112 Py_XINCREF(op
->cl_getattr
);
113 Py_XINCREF(op
->cl_setattr
);
114 Py_XINCREF(op
->cl_delattr
);
115 _PyObject_GC_TRACK(op
);
116 return (PyObject
*) op
;
120 PyMethod_Function(PyObject
*im
)
122 if (!PyMethod_Check(im
)) {
123 PyErr_BadInternalCall();
126 return ((PyMethodObject
*)im
)->im_func
;
130 PyMethod_Self(PyObject
*im
)
132 if (!PyMethod_Check(im
)) {
133 PyErr_BadInternalCall();
136 return ((PyMethodObject
*)im
)->im_self
;
140 PyMethod_Class(PyObject
*im
)
142 if (!PyMethod_Check(im
)) {
143 PyErr_BadInternalCall();
146 return ((PyMethodObject
*)im
)->im_class
;
150 class_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
152 PyObject
*name
, *bases
, *dict
;
153 static char *kwlist
[] = {"name", "bases", "dict", 0};
155 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "SOO", kwlist
,
156 &name
, &bases
, &dict
))
158 return PyClass_New(bases
, dict
, name
);
164 class_dealloc(PyClassObject
*op
)
166 _PyObject_GC_UNTRACK(op
);
167 Py_DECREF(op
->cl_bases
);
168 Py_DECREF(op
->cl_dict
);
169 Py_XDECREF(op
->cl_name
);
170 Py_XDECREF(op
->cl_getattr
);
171 Py_XDECREF(op
->cl_setattr
);
172 Py_XDECREF(op
->cl_delattr
);
177 class_lookup(PyClassObject
*cp
, PyObject
*name
, PyClassObject
**pclass
)
180 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
185 n
= PyTuple_Size(cp
->cl_bases
);
186 for (i
= 0; i
< n
; i
++) {
187 /* XXX What if one of the bases is not a class? */
188 PyObject
*v
= class_lookup(
190 PyTuple_GetItem(cp
->cl_bases
, i
), name
, pclass
);
198 class_getattr(register PyClassObject
*op
, PyObject
*name
)
200 register PyObject
*v
;
201 register char *sname
= PyString_AsString(name
);
202 PyClassObject
*class;
205 if (sname
[0] == '_' && sname
[1] == '_') {
206 if (strcmp(sname
, "__dict__") == 0) {
207 if (PyEval_GetRestricted()) {
208 PyErr_SetString(PyExc_RuntimeError
,
209 "class.__dict__ not accessible in restricted mode");
212 Py_INCREF(op
->cl_dict
);
215 if (strcmp(sname
, "__bases__") == 0) {
216 Py_INCREF(op
->cl_bases
);
219 if (strcmp(sname
, "__name__") == 0) {
220 if (op
->cl_name
== NULL
)
228 v
= class_lookup(op
, name
, &class);
230 PyErr_Format(PyExc_AttributeError
,
231 "class %.50s has no attribute '%.400s'",
232 PyString_AS_STRING(op
->cl_name
), sname
);
235 f
= v
->ob_type
->tp_descr_get
;
239 v
= f(v
, (PyObject
*)NULL
, (PyObject
*)op
);
244 set_slot(PyObject
**slot
, PyObject
*v
)
246 PyObject
*temp
= *slot
;
253 set_attr_slots(PyClassObject
*c
)
255 PyClassObject
*dummy
;
257 set_slot(&c
->cl_getattr
, class_lookup(c
, getattrstr
, &dummy
));
258 set_slot(&c
->cl_setattr
, class_lookup(c
, setattrstr
, &dummy
));
259 set_slot(&c
->cl_delattr
, class_lookup(c
, delattrstr
, &dummy
));
263 set_dict(PyClassObject
*c
, PyObject
*v
)
265 if (v
== NULL
|| !PyDict_Check(v
))
266 return "__dict__ must be a dictionary object";
267 set_slot(&c
->cl_dict
, v
);
273 set_bases(PyClassObject
*c
, PyObject
*v
)
277 if (v
== NULL
|| !PyTuple_Check(v
))
278 return "__bases__ must be a tuple object";
280 for (i
= 0; i
< n
; i
++) {
281 PyObject
*x
= PyTuple_GET_ITEM(v
, i
);
282 if (!PyClass_Check(x
))
283 return "__bases__ items must be classes";
284 if (PyClass_IsSubclass(x
, (PyObject
*)c
))
285 return "a __bases__ item causes an inheritance cycle";
287 set_slot(&c
->cl_bases
, v
);
293 set_name(PyClassObject
*c
, PyObject
*v
)
295 if (v
== NULL
|| !PyString_Check(v
))
296 return "__name__ must be a string object";
297 if (strlen(PyString_AS_STRING(v
)) != (size_t)PyString_GET_SIZE(v
))
298 return "__name__ must not contain null bytes";
299 set_slot(&c
->cl_name
, v
);
304 class_setattr(PyClassObject
*op
, PyObject
*name
, PyObject
*v
)
307 if (PyEval_GetRestricted()) {
308 PyErr_SetString(PyExc_RuntimeError
,
309 "classes are read-only in restricted mode");
312 sname
= PyString_AsString(name
);
313 if (sname
[0] == '_' && sname
[1] == '_') {
314 int n
= PyString_Size(name
);
315 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
317 if (strcmp(sname
, "__dict__") == 0)
318 err
= set_dict(op
, v
);
319 else if (strcmp(sname
, "__bases__") == 0)
320 err
= set_bases(op
, v
);
321 else if (strcmp(sname
, "__name__") == 0)
322 err
= set_name(op
, v
);
323 else if (strcmp(sname
, "__getattr__") == 0)
324 set_slot(&op
->cl_getattr
, v
);
325 else if (strcmp(sname
, "__setattr__") == 0)
326 set_slot(&op
->cl_setattr
, v
);
327 else if (strcmp(sname
, "__delattr__") == 0)
328 set_slot(&op
->cl_delattr
, v
);
329 /* For the last three, we fall through to update the
330 dictionary as well. */
334 PyErr_SetString(PyExc_TypeError
, err
);
340 int rv
= PyDict_DelItem(op
->cl_dict
, name
);
342 PyErr_Format(PyExc_AttributeError
,
343 "class %.50s has no attribute '%.400s'",
344 PyString_AS_STRING(op
->cl_name
), sname
);
348 return PyDict_SetItem(op
->cl_dict
, name
, v
);
352 class_repr(PyClassObject
*op
)
354 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
356 if (op
->cl_name
== NULL
|| !PyString_Check(op
->cl_name
))
359 name
= PyString_AsString(op
->cl_name
);
360 if (mod
== NULL
|| !PyString_Check(mod
))
361 return PyString_FromFormat("<class ?.%s at %p>", name
, op
);
363 return PyString_FromFormat("<class %s.%s at %p>",
364 PyString_AsString(mod
),
369 class_str(PyClassObject
*op
)
371 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
372 PyObject
*name
= op
->cl_name
;
376 if (name
== NULL
|| !PyString_Check(name
))
377 return class_repr(op
);
378 if (mod
== NULL
|| !PyString_Check(mod
)) {
382 m
= PyString_Size(mod
);
383 n
= PyString_Size(name
);
384 res
= PyString_FromStringAndSize((char *)NULL
, m
+1+n
);
386 char *s
= PyString_AsString(res
);
387 memcpy(s
, PyString_AsString(mod
), m
);
390 memcpy(s
, PyString_AsString(name
), n
);
396 class_traverse(PyClassObject
*o
, visitproc visit
, void *arg
)
400 err
= visit(o
->cl_bases
, arg
);
405 err
= visit(o
->cl_dict
, arg
);
410 err
= visit(o
->cl_name
, arg
);
415 err
= visit(o
->cl_getattr
, arg
);
420 err
= visit(o
->cl_setattr
, arg
);
425 err
= visit(o
->cl_delattr
, arg
);
432 PyTypeObject PyClass_Type
= {
433 PyObject_HEAD_INIT(&PyType_Type
)
436 sizeof(PyClassObject
),
438 (destructor
)class_dealloc
, /* tp_dealloc */
443 (reprfunc
)class_repr
, /* tp_repr */
444 0, /* tp_as_number */
445 0, /* tp_as_sequence */
446 0, /* tp_as_mapping */
448 PyInstance_New
, /* tp_call */
449 (reprfunc
)class_str
, /* tp_str */
450 (getattrofunc
)class_getattr
, /* tp_getattro */
451 (setattrofunc
)class_setattr
, /* tp_setattro */
452 0, /* tp_as_buffer */
453 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
455 (traverseproc
)class_traverse
, /* tp_traverse */
457 0, /* tp_richcompare */
458 0, /* tp_weaklistoffset */
466 0, /* tp_descr_get */
467 0, /* tp_descr_set */
468 0, /* tp_dictoffset */
471 class_new
, /* tp_new */
475 PyClass_IsSubclass(PyObject
*class, PyObject
*base
)
481 if (class == NULL
|| !PyClass_Check(class))
483 cp
= (PyClassObject
*)class;
484 n
= PyTuple_Size(cp
->cl_bases
);
485 for (i
= 0; i
< n
; i
++) {
486 if (PyClass_IsSubclass(PyTuple_GetItem(cp
->cl_bases
, i
), base
))
493 /* Instance objects */
496 PyInstance_NewRaw(PyObject
*klass
, PyObject
*dict
)
498 PyInstanceObject
*inst
;
500 if (!PyClass_Check(klass
)) {
501 PyErr_BadInternalCall();
510 if (!PyDict_Check(dict
)) {
511 PyErr_BadInternalCall();
516 inst
= PyObject_GC_New(PyInstanceObject
, &PyInstance_Type
);
521 inst
->in_weakreflist
= NULL
;
523 inst
->in_class
= (PyClassObject
*)klass
;
524 inst
->in_dict
= dict
;
525 _PyObject_GC_TRACK(inst
);
526 return (PyObject
*)inst
;
530 PyInstance_New(PyObject
*klass
, PyObject
*arg
, PyObject
*kw
)
532 register PyInstanceObject
*inst
;
534 static PyObject
*initstr
;
536 inst
= (PyInstanceObject
*) PyInstance_NewRaw(klass
, NULL
);
540 initstr
= PyString_InternFromString("__init__");
541 init
= instance_getattr2(inst
, initstr
);
543 if ((arg
!= NULL
&& (!PyTuple_Check(arg
) ||
544 PyTuple_Size(arg
) != 0))
545 || (kw
!= NULL
&& (!PyDict_Check(kw
) ||
546 PyDict_Size(kw
) != 0))) {
547 PyErr_SetString(PyExc_TypeError
,
548 "this constructor takes no arguments");
554 PyObject
*res
= PyEval_CallObjectWithKeywords(init
, arg
, kw
);
561 if (res
!= Py_None
) {
562 PyErr_SetString(PyExc_TypeError
,
563 "__init__() should return None");
570 return (PyObject
*)inst
;
573 /* Instance methods */
576 instance_dealloc(register PyInstanceObject
*inst
)
578 PyObject
*error_type
, *error_value
, *error_traceback
;
580 static PyObject
*delstr
;
582 extern long _Py_RefTotal
;
584 _PyObject_GC_UNTRACK(inst
);
585 PyObject_ClearWeakRefs((PyObject
*) inst
);
587 /* Temporarily resurrect the object. */
590 # error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
592 /* much too complicated if Py_TRACE_REFS defined */
593 inst
->ob_type
= &PyInstance_Type
;
594 _Py_NewReference((PyObject
*)inst
);
596 /* compensate for boost in _Py_NewReference; note that
597 * _Py_RefTotal was also boosted; we'll knock that down later.
599 inst
->ob_type
->tp_allocs
--;
601 #else /* !Py_TRACE_REFS */
602 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
604 #endif /* !Py_TRACE_REFS */
606 /* Save the current exception, if any. */
607 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
608 /* Execute __del__ method, if any. */
610 delstr
= PyString_InternFromString("__del__");
611 if ((del
= instance_getattr2(inst
, delstr
)) != NULL
) {
612 PyObject
*res
= PyEval_CallObject(del
, (PyObject
*)NULL
);
614 PyErr_WriteUnraisable(del
);
619 /* Restore the saved exception. */
620 PyErr_Restore(error_type
, error_value
, error_traceback
);
621 /* Undo the temporary resurrection; can't use DECREF here, it would
622 * cause a recursive call.
625 /* _Py_RefTotal was boosted either by _Py_NewReference or
630 if (--inst
->ob_refcnt
> 0) {
632 inst
->ob_type
->tp_frees
--;
634 _PyObject_GC_TRACK(inst
);
635 return; /* __del__ added a reference; don't delete now */
638 _Py_ForgetReference((PyObject
*)inst
);
640 /* compensate for increment in _Py_ForgetReference */
641 inst
->ob_type
->tp_frees
--;
643 #ifndef WITH_CYCLE_GC
644 inst
->ob_type
= NULL
;
647 Py_DECREF(inst
->in_class
);
648 Py_XDECREF(inst
->in_dict
);
649 PyObject_GC_Del(inst
);
653 instance_getattr1(register PyInstanceObject
*inst
, PyObject
*name
)
655 register PyObject
*v
;
656 register char *sname
= PyString_AsString(name
);
657 if (sname
[0] == '_' && sname
[1] == '_') {
658 if (strcmp(sname
, "__dict__") == 0) {
659 if (PyEval_GetRestricted()) {
660 PyErr_SetString(PyExc_RuntimeError
,
661 "instance.__dict__ not accessible in restricted mode");
664 Py_INCREF(inst
->in_dict
);
665 return inst
->in_dict
;
667 if (strcmp(sname
, "__class__") == 0) {
668 Py_INCREF(inst
->in_class
);
669 return (PyObject
*)inst
->in_class
;
672 v
= instance_getattr2(inst
, name
);
674 PyErr_Format(PyExc_AttributeError
,
675 "%.50s instance has no attribute '%.400s'",
676 PyString_AS_STRING(inst
->in_class
->cl_name
), sname
);
682 instance_getattr2(register PyInstanceObject
*inst
, PyObject
*name
)
684 register PyObject
*v
;
685 PyClassObject
*class;
688 v
= PyDict_GetItem(inst
->in_dict
, name
);
693 v
= class_lookup(inst
->in_class
, name
, &class);
696 f
= v
->ob_type
->tp_descr_get
;
698 PyObject
*w
= f(v
, (PyObject
*)inst
,
699 (PyObject
*)(inst
->in_class
));
708 instance_getattr(register PyInstanceObject
*inst
, PyObject
*name
)
710 register PyObject
*func
, *res
;
711 res
= instance_getattr1(inst
, name
);
712 if (res
== NULL
&& (func
= inst
->in_class
->cl_getattr
) != NULL
) {
715 args
= Py_BuildValue("(OO)", inst
, name
);
718 res
= PyEval_CallObject(func
, args
);
725 instance_setattr1(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
728 int rv
= PyDict_DelItem(inst
->in_dict
, name
);
730 PyErr_Format(PyExc_AttributeError
,
731 "%.50s instance has no attribute '%.400s'",
732 PyString_AS_STRING(inst
->in_class
->cl_name
),
733 PyString_AS_STRING(name
));
737 return PyDict_SetItem(inst
->in_dict
, name
, v
);
741 instance_setattr(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
743 PyObject
*func
, *args
, *res
, *tmp
;
744 char *sname
= PyString_AsString(name
);
745 if (sname
[0] == '_' && sname
[1] == '_') {
746 int n
= PyString_Size(name
);
747 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
748 if (strcmp(sname
, "__dict__") == 0) {
749 if (PyEval_GetRestricted()) {
750 PyErr_SetString(PyExc_RuntimeError
,
751 "__dict__ not accessible in restricted mode");
754 if (v
== NULL
|| !PyDict_Check(v
)) {
755 PyErr_SetString(PyExc_TypeError
,
756 "__dict__ must be set to a dictionary");
765 if (strcmp(sname
, "__class__") == 0) {
766 if (PyEval_GetRestricted()) {
767 PyErr_SetString(PyExc_RuntimeError
,
768 "__class__ not accessible in restricted mode");
771 if (v
== NULL
|| !PyClass_Check(v
)) {
772 PyErr_SetString(PyExc_TypeError
,
773 "__class__ must be set to a class");
776 tmp
= (PyObject
*)(inst
->in_class
);
778 inst
->in_class
= (PyClassObject
*)v
;
785 func
= inst
->in_class
->cl_delattr
;
787 func
= inst
->in_class
->cl_setattr
;
789 return instance_setattr1(inst
, name
, v
);
791 args
= Py_BuildValue("(OO)", inst
, name
);
793 args
= Py_BuildValue("(OOO)", inst
, name
, v
);
796 res
= PyEval_CallObject(func
, args
);
805 instance_repr(PyInstanceObject
*inst
)
809 static PyObject
*reprstr
;
812 reprstr
= PyString_InternFromString("__repr__");
813 func
= instance_getattr(inst
, reprstr
);
815 PyObject
*classname
= inst
->in_class
->cl_name
;
816 PyObject
*mod
= PyDict_GetItemString(
817 inst
->in_class
->cl_dict
, "__module__");
819 if (classname
!= NULL
&& PyString_Check(classname
))
820 cname
= PyString_AsString(classname
);
824 if (mod
== NULL
|| !PyString_Check(mod
))
825 return PyString_FromFormat("<?.%s instance at %p>",
828 return PyString_FromFormat("<%s.%s instance at %p>",
829 PyString_AsString(mod
),
832 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
838 instance_str(PyInstanceObject
*inst
)
842 static PyObject
*strstr
;
845 strstr
= PyString_InternFromString("__str__");
846 func
= instance_getattr(inst
, strstr
);
849 return instance_repr(inst
);
851 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
857 instance_hash(PyInstanceObject
*inst
)
862 static PyObject
*hashstr
, *eqstr
, *cmpstr
;
865 hashstr
= PyString_InternFromString("__hash__");
866 func
= instance_getattr(inst
, hashstr
);
868 /* If there is no __eq__ and no __cmp__ method, we hash on the
869 address. If an __eq__ or __cmp__ method exists, there must
873 eqstr
= PyString_InternFromString("__eq__");
874 func
= instance_getattr(inst
, eqstr
);
878 cmpstr
= PyString_InternFromString("__cmp__");
879 func
= instance_getattr(inst
, cmpstr
);
882 return _Py_HashPointer(inst
);
885 PyErr_SetString(PyExc_TypeError
, "unhashable instance");
888 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
892 if (PyInt_Check(res
)) {
893 outcome
= PyInt_AsLong(res
);
898 PyErr_SetString(PyExc_TypeError
,
899 "__hash__() should return an int");
907 instance_traverse(PyInstanceObject
*o
, visitproc visit
, void *arg
)
911 err
= visit((PyObject
*)(o
->in_class
), arg
);
916 err
= visit(o
->in_dict
, arg
);
923 static PyObject
*getitemstr
, *setitemstr
, *delitemstr
, *lenstr
;
924 static PyObject
*iterstr
, *nextstr
;
927 instance_length(PyInstanceObject
*inst
)
934 lenstr
= PyString_InternFromString("__len__");
935 func
= instance_getattr(inst
, lenstr
);
938 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
942 if (PyInt_Check(res
)) {
943 outcome
= PyInt_AsLong(res
);
945 PyErr_SetString(PyExc_ValueError
,
946 "__len__() should return >= 0");
949 PyErr_SetString(PyExc_TypeError
,
950 "__len__() should return an int");
958 instance_subscript(PyInstanceObject
*inst
, PyObject
*key
)
964 if (getitemstr
== NULL
)
965 getitemstr
= PyString_InternFromString("__getitem__");
966 func
= instance_getattr(inst
, getitemstr
);
969 arg
= Py_BuildValue("(O)", key
);
974 res
= PyEval_CallObject(func
, arg
);
981 instance_ass_subscript(PyInstanceObject
*inst
, PyObject
*key
, PyObject
*value
)
988 if (delitemstr
== NULL
)
989 delitemstr
= PyString_InternFromString("__delitem__");
990 func
= instance_getattr(inst
, delitemstr
);
993 if (setitemstr
== NULL
)
994 setitemstr
= PyString_InternFromString("__setitem__");
995 func
= instance_getattr(inst
, setitemstr
);
1000 arg
= Py_BuildValue("(O)", key
);
1002 arg
= Py_BuildValue("(OO)", key
, value
);
1007 res
= PyEval_CallObject(func
, arg
);
1016 static PyMappingMethods instance_as_mapping
= {
1017 (inquiry
)instance_length
, /* mp_length */
1018 (binaryfunc
)instance_subscript
, /* mp_subscript */
1019 (objobjargproc
)instance_ass_subscript
, /* mp_ass_subscript */
1023 instance_item(PyInstanceObject
*inst
, int i
)
1025 PyObject
*func
, *arg
, *res
;
1027 if (getitemstr
== NULL
)
1028 getitemstr
= PyString_InternFromString("__getitem__");
1029 func
= instance_getattr(inst
, getitemstr
);
1032 arg
= Py_BuildValue("(i)", i
);
1037 res
= PyEval_CallObject(func
, arg
);
1044 sliceobj_from_intint(int i
, int j
)
1046 PyObject
*start
, *end
, *res
;
1048 start
= PyInt_FromLong((long)i
);
1052 end
= PyInt_FromLong((long)j
);
1057 res
= PySlice_New(start
, end
, NULL
);
1065 instance_slice(PyInstanceObject
*inst
, int i
, int j
)
1067 PyObject
*func
, *arg
, *res
;
1068 static PyObject
*getslicestr
;
1070 if (getslicestr
== NULL
)
1071 getslicestr
= PyString_InternFromString("__getslice__");
1072 func
= instance_getattr(inst
, getslicestr
);
1077 if (getitemstr
== NULL
)
1078 getitemstr
= PyString_InternFromString("__getitem__");
1079 func
= instance_getattr(inst
, getitemstr
);
1082 arg
= Py_BuildValue("(N)", sliceobj_from_intint(i
, j
));
1084 arg
= Py_BuildValue("(ii)", i
, j
);
1090 res
= PyEval_CallObject(func
, arg
);
1097 instance_ass_item(PyInstanceObject
*inst
, int i
, PyObject
*item
)
1099 PyObject
*func
, *arg
, *res
;
1102 if (delitemstr
== NULL
)
1103 delitemstr
= PyString_InternFromString("__delitem__");
1104 func
= instance_getattr(inst
, delitemstr
);
1107 if (setitemstr
== NULL
)
1108 setitemstr
= PyString_InternFromString("__setitem__");
1109 func
= instance_getattr(inst
, setitemstr
);
1114 arg
= Py_BuildValue("i", i
);
1116 arg
= Py_BuildValue("(iO)", i
, item
);
1121 res
= PyEval_CallObject(func
, arg
);
1131 instance_ass_slice(PyInstanceObject
*inst
, int i
, int j
, PyObject
*value
)
1133 PyObject
*func
, *arg
, *res
;
1134 static PyObject
*setslicestr
, *delslicestr
;
1136 if (value
== NULL
) {
1137 if (delslicestr
== NULL
)
1139 PyString_InternFromString("__delslice__");
1140 func
= instance_getattr(inst
, delslicestr
);
1143 if (delitemstr
== NULL
)
1145 PyString_InternFromString("__delitem__");
1146 func
= instance_getattr(inst
, delitemstr
);
1150 arg
= Py_BuildValue("(N)",
1151 sliceobj_from_intint(i
, j
));
1153 arg
= Py_BuildValue("(ii)", i
, j
);
1156 if (setslicestr
== NULL
)
1158 PyString_InternFromString("__setslice__");
1159 func
= instance_getattr(inst
, setslicestr
);
1162 if (setitemstr
== NULL
)
1164 PyString_InternFromString("__setitem__");
1165 func
= instance_getattr(inst
, setitemstr
);
1169 arg
= Py_BuildValue("(NO)",
1170 sliceobj_from_intint(i
, j
), value
);
1172 arg
= Py_BuildValue("(iiO)", i
, j
, value
);
1178 res
= PyEval_CallObject(func
, arg
);
1188 instance_contains(PyInstanceObject
*inst
, PyObject
*member
)
1190 static PyObject
*__contains__
;
1193 /* Try __contains__ first.
1194 * If that can't be done, try iterator-based searching.
1197 if(__contains__
== NULL
) {
1198 __contains__
= PyString_InternFromString("__contains__");
1199 if(__contains__
== NULL
)
1202 func
= instance_getattr(inst
, __contains__
);
1206 PyObject
*arg
= Py_BuildValue("(O)", member
);
1211 res
= PyEval_CallObject(func
, arg
);
1216 ret
= PyObject_IsTrue(res
);
1221 /* Couldn't find __contains__. */
1222 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1223 /* Assume the failure was simply due to that there is no
1224 * __contains__ attribute, and try iterating instead.
1227 return _PySequence_IterSearch((PyObject
*)inst
, member
,
1228 PY_ITERSEARCH_CONTAINS
);
1234 static PySequenceMethods
1235 instance_as_sequence
= {
1236 (inquiry
)instance_length
, /* sq_length */
1239 (intargfunc
)instance_item
, /* sq_item */
1240 (intintargfunc
)instance_slice
, /* sq_slice */
1241 (intobjargproc
)instance_ass_item
, /* sq_ass_item */
1242 (intintobjargproc
)instance_ass_slice
, /* sq_ass_slice */
1243 (objobjproc
)instance_contains
, /* sq_contains */
1247 generic_unary_op(PyInstanceObject
*self
, PyObject
*methodname
)
1249 PyObject
*func
, *res
;
1251 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1253 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1259 generic_binary_op(PyObject
*v
, PyObject
*w
, char *opname
)
1263 PyObject
*func
= PyObject_GetAttrString(v
, opname
);
1265 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1268 Py_INCREF(Py_NotImplemented
);
1269 return Py_NotImplemented
;
1271 args
= Py_BuildValue("(O)", w
);
1276 result
= PyEval_CallObject(func
, args
);
1283 static PyObject
*coerce_obj
;
1285 /* Try one half of a binary operator involving a class instance. */
1287 half_binop(PyObject
*v
, PyObject
*w
, char *opname
, binaryfunc thisfunc
,
1291 PyObject
*coercefunc
;
1292 PyObject
*coerced
= NULL
;
1296 if (!PyInstance_Check(v
)) {
1297 Py_INCREF(Py_NotImplemented
);
1298 return Py_NotImplemented
;
1301 if (coerce_obj
== NULL
) {
1302 coerce_obj
= PyString_InternFromString("__coerce__");
1303 if (coerce_obj
== NULL
)
1306 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1307 if (coercefunc
== NULL
) {
1309 return generic_binary_op(v
, w
, opname
);
1312 args
= Py_BuildValue("(O)", w
);
1316 coerced
= PyEval_CallObject(coercefunc
, args
);
1318 Py_DECREF(coercefunc
);
1319 if (coerced
== NULL
) {
1322 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1324 return generic_binary_op(v
, w
, opname
);
1326 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1328 PyErr_SetString(PyExc_TypeError
,
1329 "coercion should return None or 2-tuple");
1332 v1
= PyTuple_GetItem(coerced
, 0);
1333 w
= PyTuple_GetItem(coerced
, 1);
1334 if (v1
->ob_type
== v
->ob_type
&& PyInstance_Check(v
)) {
1335 /* prevent recursion if __coerce__ returns self as the first
1337 result
= generic_binary_op(v1
, w
, opname
);
1340 result
= (thisfunc
)(w
, v1
);
1342 result
= (thisfunc
)(v1
, w
);
1348 /* Implement a binary operator involving at least one class instance. */
1350 do_binop(PyObject
*v
, PyObject
*w
, char *opname
, char *ropname
,
1351 binaryfunc thisfunc
)
1353 PyObject
*result
= half_binop(v
, w
, opname
, thisfunc
, 0);
1354 if (result
== Py_NotImplemented
) {
1356 result
= half_binop(w
, v
, ropname
, thisfunc
, 1);
1362 do_binop_inplace(PyObject
*v
, PyObject
*w
, char *iopname
, char *opname
,
1363 char *ropname
, binaryfunc thisfunc
)
1365 PyObject
*result
= half_binop(v
, w
, iopname
, thisfunc
, 0);
1366 if (result
== Py_NotImplemented
) {
1368 result
= do_binop(v
, w
, opname
, ropname
, thisfunc
);
1374 instance_coerce(PyObject
**pv
, PyObject
**pw
)
1378 PyObject
*coercefunc
;
1382 if (coerce_obj
== NULL
) {
1383 coerce_obj
= PyString_InternFromString("__coerce__");
1384 if (coerce_obj
== NULL
)
1387 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1388 if (coercefunc
== NULL
) {
1389 /* No __coerce__ method */
1393 /* Has __coerce__ method: call it */
1394 args
= Py_BuildValue("(O)", w
);
1398 coerced
= PyEval_CallObject(coercefunc
, args
);
1400 Py_DECREF(coercefunc
);
1401 if (coerced
== NULL
) {
1402 /* __coerce__ call raised an exception */
1405 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1406 /* __coerce__ says "I can't do it" */
1410 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1411 /* __coerce__ return value is malformed */
1413 PyErr_SetString(PyExc_TypeError
,
1414 "coercion should return None or 2-tuple");
1417 /* __coerce__ returned two new values */
1418 *pv
= PyTuple_GetItem(coerced
, 0);
1419 *pw
= PyTuple_GetItem(coerced
, 1);
1426 #define UNARY(funcname, methodname) \
1427 static PyObject *funcname(PyInstanceObject *self) { \
1428 static PyObject *o; \
1429 if (o == NULL) o = PyString_InternFromString(methodname); \
1430 return generic_unary_op(self, o); \
1433 #define BINARY(f, m, n) \
1434 static PyObject *f(PyObject *v, PyObject *w) { \
1435 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1438 #define BINARY_INPLACE(f, m, n) \
1439 static PyObject *f(PyObject *v, PyObject *w) { \
1440 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1444 UNARY(instance_neg
, "__neg__")
1445 UNARY(instance_pos
, "__pos__")
1446 UNARY(instance_abs
, "__abs__")
1448 BINARY(instance_or
, "or", PyNumber_Or
)
1449 BINARY(instance_and
, "and", PyNumber_And
)
1450 BINARY(instance_xor
, "xor", PyNumber_Xor
)
1451 BINARY(instance_lshift
, "lshift", PyNumber_Lshift
)
1452 BINARY(instance_rshift
, "rshift", PyNumber_Rshift
)
1453 BINARY(instance_add
, "add", PyNumber_Add
)
1454 BINARY(instance_sub
, "sub", PyNumber_Subtract
)
1455 BINARY(instance_mul
, "mul", PyNumber_Multiply
)
1456 BINARY(instance_div
, "div", PyNumber_Divide
)
1457 BINARY(instance_mod
, "mod", PyNumber_Remainder
)
1458 BINARY(instance_divmod
, "divmod", PyNumber_Divmod
)
1459 BINARY(instance_floordiv
, "floordiv", PyNumber_FloorDivide
)
1460 BINARY(instance_truediv
, "truediv", PyNumber_TrueDivide
)
1462 BINARY_INPLACE(instance_ior
, "or", PyNumber_InPlaceOr
)
1463 BINARY_INPLACE(instance_ixor
, "xor", PyNumber_InPlaceXor
)
1464 BINARY_INPLACE(instance_iand
, "and", PyNumber_InPlaceAnd
)
1465 BINARY_INPLACE(instance_ilshift
, "lshift", PyNumber_InPlaceLshift
)
1466 BINARY_INPLACE(instance_irshift
, "rshift", PyNumber_InPlaceRshift
)
1467 BINARY_INPLACE(instance_iadd
, "add", PyNumber_InPlaceAdd
)
1468 BINARY_INPLACE(instance_isub
, "sub", PyNumber_InPlaceSubtract
)
1469 BINARY_INPLACE(instance_imul
, "mul", PyNumber_InPlaceMultiply
)
1470 BINARY_INPLACE(instance_idiv
, "div", PyNumber_InPlaceDivide
)
1471 BINARY_INPLACE(instance_imod
, "mod", PyNumber_InPlaceRemainder
)
1472 BINARY_INPLACE(instance_ifloordiv
, "floordiv", PyNumber_InPlaceFloorDivide
)
1473 BINARY_INPLACE(instance_itruediv
, "truediv", PyNumber_InPlaceTrueDivide
)
1475 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1476 -2 for an exception;
1480 2 if this particular 3-way comparison is not implemented or undefined.
1483 half_cmp(PyObject
*v
, PyObject
*w
)
1485 static PyObject
*cmp_obj
;
1491 assert(PyInstance_Check(v
));
1493 if (cmp_obj
== NULL
) {
1494 cmp_obj
= PyString_InternFromString("__cmp__");
1495 if (cmp_obj
== NULL
)
1499 cmp_func
= PyObject_GetAttr(v
, cmp_obj
);
1500 if (cmp_func
== NULL
) {
1505 args
= Py_BuildValue("(O)", w
);
1509 result
= PyEval_CallObject(cmp_func
, args
);
1511 Py_DECREF(cmp_func
);
1516 if (result
== Py_NotImplemented
) {
1521 l
= PyInt_AsLong(result
);
1523 if (l
== -1 && PyErr_Occurred()) {
1524 PyErr_SetString(PyExc_TypeError
,
1525 "comparison did not return an int");
1529 return l
< 0 ? -1 : l
> 0 ? 1 : 0;
1532 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1533 We first try a coercion. Return:
1534 -2 for an exception;
1538 2 if this particular 3-way comparison is not implemented or undefined.
1539 THIS IS ONLY CALLED FROM object.c!
1542 instance_compare(PyObject
*v
, PyObject
*w
)
1546 c
= PyNumber_CoerceEx(&v
, &w
);
1550 /* If neither is now an instance, use regular comparison */
1551 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1552 c
= PyObject_Compare(v
, w
);
1555 if (PyErr_Occurred())
1557 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
1561 /* The coercion didn't do anything.
1562 Treat this the same as returning v and w unchanged. */
1567 if (PyInstance_Check(v
)) {
1575 if (PyInstance_Check(w
)) {
1591 instance_nonzero(PyInstanceObject
*self
)
1593 PyObject
*func
, *res
;
1595 static PyObject
*nonzerostr
;
1597 if (nonzerostr
== NULL
)
1598 nonzerostr
= PyString_InternFromString("__nonzero__");
1599 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1602 lenstr
= PyString_InternFromString("__len__");
1603 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1605 /* Fall back to the default behavior:
1606 all instances are nonzero */
1610 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1614 if (!PyInt_Check(res
)) {
1616 PyErr_SetString(PyExc_TypeError
,
1617 "__nonzero__ should return an int");
1620 outcome
= PyInt_AsLong(res
);
1623 PyErr_SetString(PyExc_ValueError
,
1624 "__nonzero__ should return >= 0");
1630 UNARY(instance_invert
, "__invert__")
1631 UNARY(instance_int
, "__int__")
1632 UNARY(instance_long
, "__long__")
1633 UNARY(instance_float
, "__float__")
1634 UNARY(instance_oct
, "__oct__")
1635 UNARY(instance_hex
, "__hex__")
1638 bin_power(PyObject
*v
, PyObject
*w
)
1640 return PyNumber_Power(v
, w
, Py_None
);
1643 /* This version is for ternary calls only (z != None) */
1645 instance_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1648 return do_binop(v
, w
, "__pow__", "__rpow__", bin_power
);
1655 /* XXX Doesn't do coercions... */
1656 func
= PyObject_GetAttrString(v
, "__pow__");
1659 args
= Py_BuildValue("(OO)", w
, z
);
1664 result
= PyEval_CallObject(func
, args
);
1672 bin_inplace_power(PyObject
*v
, PyObject
*w
)
1674 return PyNumber_InPlacePower(v
, w
, Py_None
);
1679 instance_ipow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1682 return do_binop_inplace(v
, w
, "__ipow__", "__pow__",
1683 "__rpow__", bin_inplace_power
);
1686 /* XXX Doesn't do coercions... */
1691 func
= PyObject_GetAttrString(v
, "__ipow__");
1693 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1696 return instance_pow(v
, w
, z
);
1698 args
= Py_BuildValue("(OO)", w
, z
);
1703 result
= PyEval_CallObject(func
, args
);
1711 /* Map rich comparison operators to their __xx__ namesakes */
1713 static PyObject
**name_op
= NULL
;
1719 char *_name_op
[] = {
1728 name_op
= (PyObject
**)malloc(sizeof(PyObject
*) * NAME_OPS
);
1729 if (name_op
== NULL
)
1731 for (i
= 0; i
< NAME_OPS
; ++i
) {
1732 name_op
[i
] = PyString_InternFromString(_name_op
[i
]);
1733 if (name_op
[i
] == NULL
)
1740 half_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1746 assert(PyInstance_Check(v
));
1748 if (name_op
== NULL
) {
1749 if (init_name_op() < 0)
1752 /* If the instance doesn't define an __getattr__ method, use
1753 instance_getattr2 directly because it will not set an
1754 exception on failure. */
1755 if (((PyInstanceObject
*)v
)->in_class
->cl_getattr
== NULL
) {
1756 method
= instance_getattr2((PyInstanceObject
*)v
,
1758 if (method
== NULL
) {
1759 assert(!PyErr_Occurred());
1760 res
= Py_NotImplemented
;
1765 method
= PyObject_GetAttr(v
, name_op
[op
]);
1766 if (method
== NULL
) {
1767 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1770 res
= Py_NotImplemented
;
1776 args
= Py_BuildValue("(O)", w
);
1782 res
= PyEval_CallObject(method
, args
);
1789 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
1790 static int swapped_op
[] = {Py_GT
, Py_GE
, Py_EQ
, Py_NE
, Py_LT
, Py_LE
};
1793 instance_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1797 if (PyInstance_Check(v
)) {
1798 res
= half_richcompare(v
, w
, op
);
1799 if (res
!= Py_NotImplemented
)
1804 if (PyInstance_Check(w
)) {
1805 res
= half_richcompare(w
, v
, swapped_op
[op
]);
1806 if (res
!= Py_NotImplemented
)
1811 Py_INCREF(Py_NotImplemented
);
1812 return Py_NotImplemented
;
1816 /* Get the iterator */
1818 instance_getiter(PyInstanceObject
*self
)
1822 if (iterstr
== NULL
)
1823 iterstr
= PyString_InternFromString("__iter__");
1824 if (getitemstr
== NULL
)
1825 getitemstr
= PyString_InternFromString("__getitem__");
1827 if ((func
= instance_getattr(self
, iterstr
)) != NULL
) {
1828 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1830 if (res
!= NULL
&& !PyIter_Check(res
)) {
1831 PyErr_Format(PyExc_TypeError
,
1832 "__iter__ returned non-iterator "
1834 res
->ob_type
->tp_name
);
1841 if ((func
= instance_getattr(self
, getitemstr
)) == NULL
) {
1842 PyErr_SetString(PyExc_TypeError
, "iter() of non-sequence");
1846 return PySeqIter_New((PyObject
*)self
);
1850 /* Call the iterator's next */
1852 instance_iternext(PyInstanceObject
*self
)
1856 if (nextstr
== NULL
)
1857 nextstr
= PyString_InternFromString("next");
1859 if ((func
= instance_getattr(self
, nextstr
)) != NULL
) {
1860 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1865 if (PyErr_ExceptionMatches(PyExc_StopIteration
)) {
1871 PyErr_SetString(PyExc_TypeError
, "instance has no next() method");
1876 instance_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
1878 PyObject
*res
, *call
= PyObject_GetAttrString(func
, "__call__");
1880 PyInstanceObject
*inst
= (PyInstanceObject
*) func
;
1882 PyErr_Format(PyExc_AttributeError
,
1883 "%.200s instance has no __call__ method",
1884 PyString_AsString(inst
->in_class
->cl_name
));
1887 res
= PyObject_Call(call
, arg
, kw
);
1893 static PyNumberMethods instance_as_number
= {
1894 (binaryfunc
)instance_add
, /* nb_add */
1895 (binaryfunc
)instance_sub
, /* nb_subtract */
1896 (binaryfunc
)instance_mul
, /* nb_multiply */
1897 (binaryfunc
)instance_div
, /* nb_divide */
1898 (binaryfunc
)instance_mod
, /* nb_remainder */
1899 (binaryfunc
)instance_divmod
, /* nb_divmod */
1900 (ternaryfunc
)instance_pow
, /* nb_power */
1901 (unaryfunc
)instance_neg
, /* nb_negative */
1902 (unaryfunc
)instance_pos
, /* nb_positive */
1903 (unaryfunc
)instance_abs
, /* nb_absolute */
1904 (inquiry
)instance_nonzero
, /* nb_nonzero */
1905 (unaryfunc
)instance_invert
, /* nb_invert */
1906 (binaryfunc
)instance_lshift
, /* nb_lshift */
1907 (binaryfunc
)instance_rshift
, /* nb_rshift */
1908 (binaryfunc
)instance_and
, /* nb_and */
1909 (binaryfunc
)instance_xor
, /* nb_xor */
1910 (binaryfunc
)instance_or
, /* nb_or */
1911 (coercion
)instance_coerce
, /* nb_coerce */
1912 (unaryfunc
)instance_int
, /* nb_int */
1913 (unaryfunc
)instance_long
, /* nb_long */
1914 (unaryfunc
)instance_float
, /* nb_float */
1915 (unaryfunc
)instance_oct
, /* nb_oct */
1916 (unaryfunc
)instance_hex
, /* nb_hex */
1917 (binaryfunc
)instance_iadd
, /* nb_inplace_add */
1918 (binaryfunc
)instance_isub
, /* nb_inplace_subtract */
1919 (binaryfunc
)instance_imul
, /* nb_inplace_multiply */
1920 (binaryfunc
)instance_idiv
, /* nb_inplace_divide */
1921 (binaryfunc
)instance_imod
, /* nb_inplace_remainder */
1922 (ternaryfunc
)instance_ipow
, /* nb_inplace_power */
1923 (binaryfunc
)instance_ilshift
, /* nb_inplace_lshift */
1924 (binaryfunc
)instance_irshift
, /* nb_inplace_rshift */
1925 (binaryfunc
)instance_iand
, /* nb_inplace_and */
1926 (binaryfunc
)instance_ixor
, /* nb_inplace_xor */
1927 (binaryfunc
)instance_ior
, /* nb_inplace_or */
1928 (binaryfunc
)instance_floordiv
, /* nb_floor_divide */
1929 (binaryfunc
)instance_truediv
, /* nb_true_divide */
1930 (binaryfunc
)instance_ifloordiv
, /* nb_inplace_floor_divide */
1931 (binaryfunc
)instance_itruediv
, /* nb_inplace_true_divide */
1934 PyTypeObject PyInstance_Type
= {
1935 PyObject_HEAD_INIT(&PyType_Type
)
1938 sizeof(PyInstanceObject
),
1940 (destructor
)instance_dealloc
, /* tp_dealloc */
1944 instance_compare
, /* tp_compare */
1945 (reprfunc
)instance_repr
, /* tp_repr */
1946 &instance_as_number
, /* tp_as_number */
1947 &instance_as_sequence
, /* tp_as_sequence */
1948 &instance_as_mapping
, /* tp_as_mapping */
1949 (hashfunc
)instance_hash
, /* tp_hash */
1950 instance_call
, /* tp_call */
1951 (reprfunc
)instance_str
, /* tp_str */
1952 (getattrofunc
)instance_getattr
, /* tp_getattro */
1953 (setattrofunc
)instance_setattr
, /* tp_setattro */
1954 0, /* tp_as_buffer */
1955 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
,/*tp_flags*/
1957 (traverseproc
)instance_traverse
, /* tp_traverse */
1959 instance_richcompare
, /* tp_richcompare */
1960 offsetof(PyInstanceObject
, in_weakreflist
), /* tp_weaklistoffset */
1961 (getiterfunc
)instance_getiter
, /* tp_iter */
1962 (iternextfunc
)instance_iternext
, /* tp_iternext */
1966 /* Instance method objects are used for two purposes:
1967 (a) as bound instance methods (returned by instancename.methodname)
1968 (b) as unbound methods (returned by ClassName.methodname)
1969 In case (b), im_self is NULL
1972 static PyMethodObject
*free_list
;
1975 PyMethod_New(PyObject
*func
, PyObject
*self
, PyObject
*class)
1977 register PyMethodObject
*im
;
1978 if (!PyCallable_Check(func
)) {
1979 PyErr_BadInternalCall();
1984 free_list
= (PyMethodObject
*)(im
->im_self
);
1985 PyObject_INIT(im
, &PyMethod_Type
);
1988 im
= PyObject_GC_New(PyMethodObject
, &PyMethod_Type
);
1992 im
->im_weakreflist
= NULL
;
1998 im
->im_class
= class;
1999 _PyObject_GC_TRACK(im
);
2000 return (PyObject
*)im
;
2003 /* Descriptors for PyMethod attributes */
2005 /* im_class, im_func and im_self are stored in the PyMethod object */
2007 #define OFF(x) offsetof(PyMethodObject, x)
2009 static PyMemberDef instancemethod_memberlist
[] = {
2010 {"im_class", T_OBJECT
, OFF(im_class
), READONLY
|RESTRICTED
,
2011 "the class associated with a method"},
2012 {"im_func", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2013 "the function (or other callable) implementing a method"},
2014 {"im_self", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2015 "the instance to which a method is bound; None for unbound methods"},
2016 {NULL
} /* Sentinel */
2019 /* __dict__, __doc__ and __name__ are retrieved from im_func */
2022 im_get_dict(PyMethodObject
*im
)
2024 return PyObject_GetAttrString(im
->im_func
, "__dict__");
2028 im_get_doc(PyMethodObject
*im
)
2030 return PyObject_GetAttrString(im
->im_func
, "__doc__");
2034 im_get_name(PyMethodObject
*im
)
2036 return PyObject_GetAttrString(im
->im_func
, "__name__");
2039 static PyGetSetDef instancemethod_getsetlist
[] = {
2040 {"__dict__", (getter
)im_get_dict
, NULL
, "same as im_func.__dict__"},
2041 {"__doc__", (getter
)im_get_doc
, NULL
, "same as im_func.__doc__"},
2042 {"__name__", (getter
)im_get_name
, NULL
, "same as im_func.__name__"},
2043 {NULL
} /* Sentinel */
2046 /* The getattr() implementation for PyMethod objects is similar to
2047 PyObject_GenericGetAttr(), but instead of looking in __dict__ it
2048 asks im_self for the attribute. Then the error handling is a bit
2049 different because we want to preserve the exception raised by the
2050 delegate, unless we have an alternative from our class. */
2053 instancemethod_getattro(PyObject
*obj
, PyObject
*name
)
2055 PyMethodObject
*im
= (PyMethodObject
*)obj
;
2056 PyTypeObject
*tp
= obj
->ob_type
;
2057 PyObject
*descr
, *res
;
2060 if (tp
->tp_dict
== NULL
) {
2061 if (PyType_Ready(tp
) < 0)
2065 descr
= _PyType_Lookup(tp
, name
);
2067 if (descr
!= NULL
) {
2068 f
= descr
->ob_type
->tp_descr_get
;
2069 if (f
!= NULL
&& PyDescr_IsData(descr
))
2070 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2073 res
= PyObject_GetAttr(im
->im_func
, name
);
2074 if (res
!= NULL
|| !PyErr_ExceptionMatches(PyExc_AttributeError
))
2079 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2082 if (descr
!= NULL
) {
2088 assert(PyErr_Occurred());
2093 instancemethod_dealloc(register PyMethodObject
*im
)
2095 _PyObject_GC_UNTRACK(im
);
2096 PyObject_ClearWeakRefs((PyObject
*)im
);
2097 Py_DECREF(im
->im_func
);
2098 Py_XDECREF(im
->im_self
);
2099 Py_XDECREF(im
->im_class
);
2100 im
->im_self
= (PyObject
*)free_list
;
2105 instancemethod_compare(PyMethodObject
*a
, PyMethodObject
*b
)
2107 if (a
->im_self
!= b
->im_self
)
2108 return (a
->im_self
< b
->im_self
) ? -1 : 1;
2109 return PyObject_Compare(a
->im_func
, b
->im_func
);
2113 instancemethod_repr(PyMethodObject
*a
)
2115 PyObject
*self
= a
->im_self
;
2116 PyObject
*func
= a
->im_func
;
2117 PyObject
*klass
= a
->im_class
;
2118 PyObject
*funcname
= NULL
, *klassname
= NULL
, *result
= NULL
;
2119 char *sfuncname
= "?", *sklassname
= "?";
2121 funcname
= PyObject_GetAttrString(func
, "__name__");
2122 if (funcname
== NULL
)
2124 else if (!PyString_Check(funcname
)) {
2125 Py_DECREF(funcname
);
2129 sfuncname
= PyString_AS_STRING(funcname
);
2133 klassname
= PyObject_GetAttrString(klass
, "__name__");
2134 if (klassname
== NULL
)
2136 else if (!PyString_Check(klassname
)) {
2137 Py_DECREF(klassname
);
2141 sklassname
= PyString_AS_STRING(klassname
);
2144 result
= PyString_FromFormat("<unbound method %s.%s>",
2145 sklassname
, sfuncname
);
2147 /* XXX Shouldn't use repr() here! */
2148 PyObject
*selfrepr
= PyObject_Repr(self
);
2149 if (selfrepr
== NULL
)
2151 if (!PyString_Check(selfrepr
)) {
2152 Py_DECREF(selfrepr
);
2155 result
= PyString_FromFormat("<bound method %s.%s of %s>",
2156 sklassname
, sfuncname
,
2157 PyString_AS_STRING(selfrepr
));
2158 Py_DECREF(selfrepr
);
2161 Py_XDECREF(funcname
);
2162 Py_XDECREF(klassname
);
2167 instancemethod_hash(PyMethodObject
*a
)
2170 if (a
->im_self
== NULL
)
2171 x
= PyObject_Hash(Py_None
);
2173 x
= PyObject_Hash(a
->im_self
);
2176 y
= PyObject_Hash(a
->im_func
);
2183 instancemethod_traverse(PyMethodObject
*im
, visitproc visit
, void *arg
)
2187 err
= visit(im
->im_func
, arg
);
2192 err
= visit(im
->im_self
, arg
);
2197 err
= visit(im
->im_class
, arg
);
2205 getclassname(PyObject
*class)
2212 name
= PyObject_GetAttrString(class, "__name__");
2217 if (!PyString_Check(name
)) {
2221 PyString_InternInPlace(&name
);
2223 return PyString_AS_STRING(name
);
2227 getinstclassname(PyObject
*inst
)
2235 class = PyObject_GetAttrString(inst
, "__class__");
2236 if (class == NULL
) {
2238 class = (PyObject
*)(inst
->ob_type
);
2241 name
= getclassname(class);
2247 instancemethod_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2249 PyObject
*self
= PyMethod_GET_SELF(func
);
2250 PyObject
*class = PyMethod_GET_CLASS(func
);
2253 func
= PyMethod_GET_FUNCTION(func
);
2255 /* Unbound methods must be called with an instance of
2256 the class (or a derived class) as first argument */
2258 if (PyTuple_Size(arg
) >= 1)
2259 self
= PyTuple_GET_ITEM(arg
, 0);
2263 ok
= PyObject_IsInstance(self
, class);
2268 PyErr_Format(PyExc_TypeError
,
2269 "unbound method %s%s must be called with "
2270 "%s instance as first argument "
2271 "(got %s%s instead)",
2272 PyEval_GetFuncName(func
),
2273 PyEval_GetFuncDesc(func
),
2274 getclassname(class),
2275 getinstclassname(self
),
2276 self
== NULL
? "" : " instance");
2282 int argcount
= PyTuple_Size(arg
);
2283 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2288 PyTuple_SET_ITEM(newarg
, 0, self
);
2289 for (i
= 0; i
< argcount
; i
++) {
2290 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2292 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2296 result
= PyObject_Call((PyObject
*)func
, arg
, kw
);
2302 instancemethod_descr_get(PyObject
*meth
, PyObject
*obj
, PyObject
*class)
2304 /* Don't rebind an already bound method, or an unbound method
2305 of a class that's not a base class of class */
2306 if (PyMethod_GET_SELF(meth
) != NULL
||
2307 (PyMethod_GET_CLASS(meth
) != NULL
&&
2308 !PyObject_IsSubclass(class, PyMethod_GET_CLASS(meth
)))) {
2314 return PyMethod_New(PyMethod_GET_FUNCTION(meth
), obj
, class);
2317 PyTypeObject PyMethod_Type
= {
2318 PyObject_HEAD_INIT(&PyType_Type
)
2321 sizeof(PyMethodObject
),
2323 (destructor
)instancemethod_dealloc
, /* tp_dealloc */
2327 (cmpfunc
)instancemethod_compare
, /* tp_compare */
2328 (reprfunc
)instancemethod_repr
, /* tp_repr */
2329 0, /* tp_as_number */
2330 0, /* tp_as_sequence */
2331 0, /* tp_as_mapping */
2332 (hashfunc
)instancemethod_hash
, /* tp_hash */
2333 instancemethod_call
, /* tp_call */
2335 (getattrofunc
)instancemethod_getattro
, /* tp_getattro */
2336 PyObject_GenericSetAttr
, /* tp_setattro */
2337 0, /* tp_as_buffer */
2338 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
2340 (traverseproc
)instancemethod_traverse
, /* tp_traverse */
2342 0, /* tp_richcompare */
2343 offsetof(PyMethodObject
, im_weakreflist
), /* tp_weaklistoffset */
2345 0, /* tp_iternext */
2347 instancemethod_memberlist
, /* tp_members */
2348 instancemethod_getsetlist
, /* tp_getset */
2351 instancemethod_descr_get
, /* tp_descr_get */
2352 0, /* tp_descr_set */
2353 0, /* tp_dictoffset */
2356 /* Clear out the free list */
2362 PyMethodObject
*im
= free_list
;
2363 free_list
= (PyMethodObject
*)(im
->im_self
);
2364 PyObject_GC_Del(im
);