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_CallFunctionObjArgs(
85 (PyObject
*) base
->ob_type
,
86 name
, bases
, dict
, NULL
);
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
;
149 PyDoc_STRVAR(class_doc
,
150 "classobj(name, bases, dict)\n\
152 Create a class object. The name must be a string; the second argument\n\
153 a tuple of classes, and the third a dictionary.");
156 class_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
158 PyObject
*name
, *bases
, *dict
;
159 static char *kwlist
[] = {"name", "bases", "dict", 0};
161 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "SOO", kwlist
,
162 &name
, &bases
, &dict
))
164 return PyClass_New(bases
, dict
, name
);
170 class_dealloc(PyClassObject
*op
)
172 _PyObject_GC_UNTRACK(op
);
173 Py_DECREF(op
->cl_bases
);
174 Py_DECREF(op
->cl_dict
);
175 Py_XDECREF(op
->cl_name
);
176 Py_XDECREF(op
->cl_getattr
);
177 Py_XDECREF(op
->cl_setattr
);
178 Py_XDECREF(op
->cl_delattr
);
183 class_lookup(PyClassObject
*cp
, PyObject
*name
, PyClassObject
**pclass
)
186 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
191 n
= PyTuple_Size(cp
->cl_bases
);
192 for (i
= 0; i
< n
; i
++) {
193 /* XXX What if one of the bases is not a class? */
194 PyObject
*v
= class_lookup(
196 PyTuple_GetItem(cp
->cl_bases
, i
), name
, pclass
);
204 class_getattr(register PyClassObject
*op
, PyObject
*name
)
206 register PyObject
*v
;
207 register char *sname
= PyString_AsString(name
);
208 PyClassObject
*klass
;
211 if (sname
[0] == '_' && sname
[1] == '_') {
212 if (strcmp(sname
, "__dict__") == 0) {
213 if (PyEval_GetRestricted()) {
214 PyErr_SetString(PyExc_RuntimeError
,
215 "class.__dict__ not accessible in restricted mode");
218 Py_INCREF(op
->cl_dict
);
221 if (strcmp(sname
, "__bases__") == 0) {
222 Py_INCREF(op
->cl_bases
);
225 if (strcmp(sname
, "__name__") == 0) {
226 if (op
->cl_name
== NULL
)
234 v
= class_lookup(op
, name
, &klass
);
236 PyErr_Format(PyExc_AttributeError
,
237 "class %.50s has no attribute '%.400s'",
238 PyString_AS_STRING(op
->cl_name
), sname
);
241 f
= TP_DESCR_GET(v
->ob_type
);
245 v
= f(v
, (PyObject
*)NULL
, (PyObject
*)op
);
250 set_slot(PyObject
**slot
, PyObject
*v
)
252 PyObject
*temp
= *slot
;
259 set_attr_slots(PyClassObject
*c
)
261 PyClassObject
*dummy
;
263 set_slot(&c
->cl_getattr
, class_lookup(c
, getattrstr
, &dummy
));
264 set_slot(&c
->cl_setattr
, class_lookup(c
, setattrstr
, &dummy
));
265 set_slot(&c
->cl_delattr
, class_lookup(c
, delattrstr
, &dummy
));
269 set_dict(PyClassObject
*c
, PyObject
*v
)
271 if (v
== NULL
|| !PyDict_Check(v
))
272 return "__dict__ must be a dictionary object";
273 set_slot(&c
->cl_dict
, v
);
279 set_bases(PyClassObject
*c
, PyObject
*v
)
283 if (v
== NULL
|| !PyTuple_Check(v
))
284 return "__bases__ must be a tuple object";
286 for (i
= 0; i
< n
; i
++) {
287 PyObject
*x
= PyTuple_GET_ITEM(v
, i
);
288 if (!PyClass_Check(x
))
289 return "__bases__ items must be classes";
290 if (PyClass_IsSubclass(x
, (PyObject
*)c
))
291 return "a __bases__ item causes an inheritance cycle";
293 set_slot(&c
->cl_bases
, v
);
299 set_name(PyClassObject
*c
, PyObject
*v
)
301 if (v
== NULL
|| !PyString_Check(v
))
302 return "__name__ must be a string object";
303 if (strlen(PyString_AS_STRING(v
)) != (size_t)PyString_GET_SIZE(v
))
304 return "__name__ must not contain null bytes";
305 set_slot(&c
->cl_name
, v
);
310 class_setattr(PyClassObject
*op
, PyObject
*name
, PyObject
*v
)
313 if (PyEval_GetRestricted()) {
314 PyErr_SetString(PyExc_RuntimeError
,
315 "classes are read-only in restricted mode");
318 sname
= PyString_AsString(name
);
319 if (sname
[0] == '_' && sname
[1] == '_') {
320 Py_ssize_t n
= PyString_Size(name
);
321 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
323 if (strcmp(sname
, "__dict__") == 0)
324 err
= set_dict(op
, v
);
325 else if (strcmp(sname
, "__bases__") == 0)
326 err
= set_bases(op
, v
);
327 else if (strcmp(sname
, "__name__") == 0)
328 err
= set_name(op
, v
);
329 else if (strcmp(sname
, "__getattr__") == 0)
330 set_slot(&op
->cl_getattr
, v
);
331 else if (strcmp(sname
, "__setattr__") == 0)
332 set_slot(&op
->cl_setattr
, v
);
333 else if (strcmp(sname
, "__delattr__") == 0)
334 set_slot(&op
->cl_delattr
, v
);
335 /* For the last three, we fall through to update the
336 dictionary as well. */
340 PyErr_SetString(PyExc_TypeError
, err
);
346 int rv
= PyDict_DelItem(op
->cl_dict
, name
);
348 PyErr_Format(PyExc_AttributeError
,
349 "class %.50s has no attribute '%.400s'",
350 PyString_AS_STRING(op
->cl_name
), sname
);
354 return PyDict_SetItem(op
->cl_dict
, name
, v
);
358 class_repr(PyClassObject
*op
)
360 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
362 if (op
->cl_name
== NULL
|| !PyString_Check(op
->cl_name
))
365 name
= PyString_AsString(op
->cl_name
);
366 if (mod
== NULL
|| !PyString_Check(mod
))
367 return PyString_FromFormat("<class ?.%s at %p>", name
, op
);
369 return PyString_FromFormat("<class %s.%s at %p>",
370 PyString_AsString(mod
),
375 class_str(PyClassObject
*op
)
377 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
378 PyObject
*name
= op
->cl_name
;
382 if (name
== NULL
|| !PyString_Check(name
))
383 return class_repr(op
);
384 if (mod
== NULL
|| !PyString_Check(mod
)) {
388 m
= PyString_GET_SIZE(mod
);
389 n
= PyString_GET_SIZE(name
);
390 res
= PyString_FromStringAndSize((char *)NULL
, m
+1+n
);
392 char *s
= PyString_AS_STRING(res
);
393 memcpy(s
, PyString_AS_STRING(mod
), m
);
396 memcpy(s
, PyString_AS_STRING(name
), n
);
402 class_traverse(PyClassObject
*o
, visitproc visit
, void *arg
)
404 Py_VISIT(o
->cl_bases
);
405 Py_VISIT(o
->cl_dict
);
406 Py_VISIT(o
->cl_name
);
407 Py_VISIT(o
->cl_getattr
);
408 Py_VISIT(o
->cl_setattr
);
409 Py_VISIT(o
->cl_delattr
);
413 PyTypeObject PyClass_Type
= {
414 PyObject_HEAD_INIT(&PyType_Type
)
417 sizeof(PyClassObject
),
419 (destructor
)class_dealloc
, /* tp_dealloc */
424 (reprfunc
)class_repr
, /* tp_repr */
425 0, /* tp_as_number */
426 0, /* tp_as_sequence */
427 0, /* tp_as_mapping */
429 PyInstance_New
, /* tp_call */
430 (reprfunc
)class_str
, /* tp_str */
431 (getattrofunc
)class_getattr
, /* tp_getattro */
432 (setattrofunc
)class_setattr
, /* tp_setattro */
433 0, /* tp_as_buffer */
434 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
435 class_doc
, /* tp_doc */
436 (traverseproc
)class_traverse
, /* tp_traverse */
438 0, /* tp_richcompare */
439 0, /* tp_weaklistoffset */
447 0, /* tp_descr_get */
448 0, /* tp_descr_set */
449 0, /* tp_dictoffset */
452 class_new
, /* tp_new */
456 PyClass_IsSubclass(PyObject
*klass
, PyObject
*base
)
462 if (PyTuple_Check(base
)) {
463 n
= PyTuple_GET_SIZE(base
);
464 for (i
= 0; i
< n
; i
++) {
465 if (PyClass_IsSubclass(klass
, PyTuple_GET_ITEM(base
, i
)))
470 if (klass
== NULL
|| !PyClass_Check(klass
))
472 cp
= (PyClassObject
*)klass
;
473 n
= PyTuple_Size(cp
->cl_bases
);
474 for (i
= 0; i
< n
; i
++) {
475 if (PyClass_IsSubclass(PyTuple_GetItem(cp
->cl_bases
, i
), base
))
482 /* Instance objects */
485 PyInstance_NewRaw(PyObject
*klass
, PyObject
*dict
)
487 PyInstanceObject
*inst
;
489 if (!PyClass_Check(klass
)) {
490 PyErr_BadInternalCall();
499 if (!PyDict_Check(dict
)) {
500 PyErr_BadInternalCall();
505 inst
= PyObject_GC_New(PyInstanceObject
, &PyInstance_Type
);
510 inst
->in_weakreflist
= NULL
;
512 inst
->in_class
= (PyClassObject
*)klass
;
513 inst
->in_dict
= dict
;
514 _PyObject_GC_TRACK(inst
);
515 return (PyObject
*)inst
;
519 PyInstance_New(PyObject
*klass
, PyObject
*arg
, PyObject
*kw
)
521 register PyInstanceObject
*inst
;
523 static PyObject
*initstr
;
525 inst
= (PyInstanceObject
*) PyInstance_NewRaw(klass
, NULL
);
529 initstr
= PyString_InternFromString("__init__");
530 init
= instance_getattr2(inst
, initstr
);
532 if (PyErr_Occurred()) {
536 if ((arg
!= NULL
&& (!PyTuple_Check(arg
) ||
537 PyTuple_Size(arg
) != 0))
538 || (kw
!= NULL
&& (!PyDict_Check(kw
) ||
539 PyDict_Size(kw
) != 0))) {
540 PyErr_SetString(PyExc_TypeError
,
541 "this constructor takes no arguments");
547 PyObject
*res
= PyEval_CallObjectWithKeywords(init
, arg
, kw
);
554 if (res
!= Py_None
) {
555 PyErr_SetString(PyExc_TypeError
,
556 "__init__() should return None");
563 return (PyObject
*)inst
;
566 /* Instance methods */
568 PyDoc_STRVAR(instance_doc
,
569 "instance(class[, dict])\n\
571 Create an instance without calling its __init__() method.\n\
572 The class must be a classic class.\n\
573 If present, dict must be a dictionary or None.");
576 instance_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
579 PyObject
*dict
= Py_None
;
581 if (!PyArg_ParseTuple(args
, "O!|O:instance",
582 &PyClass_Type
, &klass
, &dict
))
587 else if (!PyDict_Check(dict
)) {
588 PyErr_SetString(PyExc_TypeError
,
589 "instance() second arg must be dictionary or None");
592 return PyInstance_NewRaw(klass
, dict
);
597 instance_dealloc(register PyInstanceObject
*inst
)
599 PyObject
*error_type
, *error_value
, *error_traceback
;
601 static PyObject
*delstr
;
603 _PyObject_GC_UNTRACK(inst
);
604 if (inst
->in_weakreflist
!= NULL
)
605 PyObject_ClearWeakRefs((PyObject
*) inst
);
607 /* Temporarily resurrect the object. */
608 assert(inst
->ob_type
== &PyInstance_Type
);
609 assert(inst
->ob_refcnt
== 0);
612 /* Save the current exception, if any. */
613 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
614 /* Execute __del__ method, if any. */
616 delstr
= PyString_InternFromString("__del__");
617 if ((del
= instance_getattr2(inst
, delstr
)) != NULL
) {
618 PyObject
*res
= PyEval_CallObject(del
, (PyObject
*)NULL
);
620 PyErr_WriteUnraisable(del
);
625 /* Restore the saved exception. */
626 PyErr_Restore(error_type
, error_value
, error_traceback
);
628 /* Undo the temporary resurrection; can't use DECREF here, it would
629 * cause a recursive call.
631 assert(inst
->ob_refcnt
> 0);
632 if (--inst
->ob_refcnt
== 0) {
633 Py_DECREF(inst
->in_class
);
634 Py_XDECREF(inst
->in_dict
);
635 PyObject_GC_Del(inst
);
638 Py_ssize_t refcnt
= inst
->ob_refcnt
;
639 /* __del__ resurrected it! Make it look like the original
640 * Py_DECREF never happened.
642 _Py_NewReference((PyObject
*)inst
);
643 inst
->ob_refcnt
= refcnt
;
644 _PyObject_GC_TRACK(inst
);
645 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
646 * we need to undo that. */
648 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
649 * object chain, so no more to do there.
650 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
651 * _Py_NewReference bumped tp_allocs: both of those need to be
655 --inst
->ob_type
->tp_frees
;
656 --inst
->ob_type
->tp_allocs
;
662 instance_getattr1(register PyInstanceObject
*inst
, PyObject
*name
)
664 register PyObject
*v
;
665 register char *sname
= PyString_AsString(name
);
666 if (sname
[0] == '_' && sname
[1] == '_') {
667 if (strcmp(sname
, "__dict__") == 0) {
668 if (PyEval_GetRestricted()) {
669 PyErr_SetString(PyExc_RuntimeError
,
670 "instance.__dict__ not accessible in restricted mode");
673 Py_INCREF(inst
->in_dict
);
674 return inst
->in_dict
;
676 if (strcmp(sname
, "__class__") == 0) {
677 Py_INCREF(inst
->in_class
);
678 return (PyObject
*)inst
->in_class
;
681 v
= instance_getattr2(inst
, name
);
682 if (v
== NULL
&& !PyErr_Occurred()) {
683 PyErr_Format(PyExc_AttributeError
,
684 "%.50s instance has no attribute '%.400s'",
685 PyString_AS_STRING(inst
->in_class
->cl_name
), sname
);
691 instance_getattr2(register PyInstanceObject
*inst
, PyObject
*name
)
693 register PyObject
*v
;
694 PyClassObject
*klass
;
697 v
= PyDict_GetItem(inst
->in_dict
, name
);
702 v
= class_lookup(inst
->in_class
, name
, &klass
);
705 f
= TP_DESCR_GET(v
->ob_type
);
707 PyObject
*w
= f(v
, (PyObject
*)inst
,
708 (PyObject
*)(inst
->in_class
));
717 instance_getattr(register PyInstanceObject
*inst
, PyObject
*name
)
719 register PyObject
*func
, *res
;
720 res
= instance_getattr1(inst
, name
);
721 if (res
== NULL
&& (func
= inst
->in_class
->cl_getattr
) != NULL
) {
723 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
726 args
= PyTuple_Pack(2, inst
, name
);
729 res
= PyEval_CallObject(func
, args
);
735 /* See classobject.h comments: this only does dict lookups, and is always
739 _PyInstance_Lookup(PyObject
*pinst
, PyObject
*name
)
742 PyClassObject
*klass
;
743 PyInstanceObject
*inst
; /* pinst cast to the right type */
745 assert(PyInstance_Check(pinst
));
746 inst
= (PyInstanceObject
*)pinst
;
748 assert(PyString_Check(name
));
750 v
= PyDict_GetItem(inst
->in_dict
, name
);
752 v
= class_lookup(inst
->in_class
, name
, &klass
);
757 instance_setattr1(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
760 int rv
= PyDict_DelItem(inst
->in_dict
, name
);
762 PyErr_Format(PyExc_AttributeError
,
763 "%.50s instance has no attribute '%.400s'",
764 PyString_AS_STRING(inst
->in_class
->cl_name
),
765 PyString_AS_STRING(name
));
769 return PyDict_SetItem(inst
->in_dict
, name
, v
);
773 instance_setattr(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
775 PyObject
*func
, *args
, *res
, *tmp
;
776 char *sname
= PyString_AsString(name
);
777 if (sname
[0] == '_' && sname
[1] == '_') {
778 Py_ssize_t n
= PyString_Size(name
);
779 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
780 if (strcmp(sname
, "__dict__") == 0) {
781 if (PyEval_GetRestricted()) {
782 PyErr_SetString(PyExc_RuntimeError
,
783 "__dict__ not accessible in restricted mode");
786 if (v
== NULL
|| !PyDict_Check(v
)) {
787 PyErr_SetString(PyExc_TypeError
,
788 "__dict__ must be set to a dictionary");
797 if (strcmp(sname
, "__class__") == 0) {
798 if (PyEval_GetRestricted()) {
799 PyErr_SetString(PyExc_RuntimeError
,
800 "__class__ not accessible in restricted mode");
803 if (v
== NULL
|| !PyClass_Check(v
)) {
804 PyErr_SetString(PyExc_TypeError
,
805 "__class__ must be set to a class");
808 tmp
= (PyObject
*)(inst
->in_class
);
810 inst
->in_class
= (PyClassObject
*)v
;
817 func
= inst
->in_class
->cl_delattr
;
819 func
= inst
->in_class
->cl_setattr
;
821 return instance_setattr1(inst
, name
, v
);
823 args
= PyTuple_Pack(2, inst
, name
);
825 args
= PyTuple_Pack(3, inst
, name
, v
);
828 res
= PyEval_CallObject(func
, args
);
837 instance_repr(PyInstanceObject
*inst
)
841 static PyObject
*reprstr
;
844 reprstr
= PyString_InternFromString("__repr__");
845 func
= instance_getattr(inst
, reprstr
);
847 PyObject
*classname
, *mod
;
849 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
852 classname
= inst
->in_class
->cl_name
;
853 mod
= PyDict_GetItemString(inst
->in_class
->cl_dict
,
855 if (classname
!= NULL
&& PyString_Check(classname
))
856 cname
= PyString_AsString(classname
);
859 if (mod
== NULL
|| !PyString_Check(mod
))
860 return PyString_FromFormat("<?.%s instance at %p>",
863 return PyString_FromFormat("<%s.%s instance at %p>",
864 PyString_AsString(mod
),
867 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
873 instance_str(PyInstanceObject
*inst
)
877 static PyObject
*strstr
;
880 strstr
= PyString_InternFromString("__str__");
881 func
= instance_getattr(inst
, strstr
);
883 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
886 return instance_repr(inst
);
888 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
894 instance_hash(PyInstanceObject
*inst
)
899 static PyObject
*hashstr
, *eqstr
, *cmpstr
;
902 hashstr
= PyString_InternFromString("__hash__");
903 func
= instance_getattr(inst
, hashstr
);
905 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
908 /* If there is no __eq__ and no __cmp__ method, we hash on the
909 address. If an __eq__ or __cmp__ method exists, there must
912 eqstr
= PyString_InternFromString("__eq__");
913 func
= instance_getattr(inst
, eqstr
);
915 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
919 cmpstr
= PyString_InternFromString("__cmp__");
920 func
= instance_getattr(inst
, cmpstr
);
922 if (!PyErr_ExceptionMatches(
923 PyExc_AttributeError
))
926 return _Py_HashPointer(inst
);
930 PyErr_SetString(PyExc_TypeError
, "unhashable instance");
933 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
937 if (PyInt_Check(res
)) {
938 outcome
= PyInt_AsLong(res
);
943 PyErr_SetString(PyExc_TypeError
,
944 "__hash__() should return an int");
952 instance_traverse(PyInstanceObject
*o
, visitproc visit
, void *arg
)
954 Py_VISIT(o
->in_class
);
955 Py_VISIT(o
->in_dict
);
959 static PyObject
*getitemstr
, *setitemstr
, *delitemstr
, *lenstr
;
960 static PyObject
*iterstr
, *nextstr
;
963 instance_length(PyInstanceObject
*inst
)
970 lenstr
= PyString_InternFromString("__len__");
971 func
= instance_getattr(inst
, lenstr
);
974 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
978 if (PyInt_Check(res
)) {
979 Py_ssize_t temp
= PyInt_AsSsize_t(res
);
980 if (temp
== -1 && PyErr_Occurred()) {
984 outcome
= (Py_ssize_t
)temp
;
985 #if SIZEOF_SIZE_T < SIZEOF_LONG
986 /* Overflow check -- range of PyInt is more than C int */
987 if (outcome
!= temp
) {
988 PyErr_SetString(PyExc_OverflowError
,
989 "__len__() should return 0 <= outcome < 2**31");
995 PyErr_SetString(PyExc_ValueError
,
996 "__len__() should return >= 0");
999 PyErr_SetString(PyExc_TypeError
,
1000 "__len__() should return an int");
1008 instance_subscript(PyInstanceObject
*inst
, PyObject
*key
)
1014 if (getitemstr
== NULL
)
1015 getitemstr
= PyString_InternFromString("__getitem__");
1016 func
= instance_getattr(inst
, getitemstr
);
1019 arg
= PyTuple_Pack(1, key
);
1024 res
= PyEval_CallObject(func
, arg
);
1031 instance_ass_subscript(PyInstanceObject
*inst
, PyObject
*key
, PyObject
*value
)
1037 if (value
== NULL
) {
1038 if (delitemstr
== NULL
)
1039 delitemstr
= PyString_InternFromString("__delitem__");
1040 func
= instance_getattr(inst
, delitemstr
);
1043 if (setitemstr
== NULL
)
1044 setitemstr
= PyString_InternFromString("__setitem__");
1045 func
= instance_getattr(inst
, setitemstr
);
1050 arg
= PyTuple_Pack(1, key
);
1052 arg
= PyTuple_Pack(2, key
, value
);
1057 res
= PyEval_CallObject(func
, arg
);
1066 static PyMappingMethods instance_as_mapping
= {
1067 (lenfunc
)instance_length
, /* mp_length */
1068 (binaryfunc
)instance_subscript
, /* mp_subscript */
1069 (objobjargproc
)instance_ass_subscript
, /* mp_ass_subscript */
1073 instance_item(PyInstanceObject
*inst
, Py_ssize_t i
)
1075 PyObject
*func
, *res
;
1077 if (getitemstr
== NULL
)
1078 getitemstr
= PyString_InternFromString("__getitem__");
1079 func
= instance_getattr(inst
, getitemstr
);
1082 res
= PyObject_CallFunction(func
, "n", i
);
1088 instance_slice(PyInstanceObject
*inst
, Py_ssize_t i
, Py_ssize_t j
)
1090 PyObject
*func
, *arg
, *res
;
1091 static PyObject
*getslicestr
;
1093 if (getslicestr
== NULL
)
1094 getslicestr
= PyString_InternFromString("__getslice__");
1095 func
= instance_getattr(inst
, getslicestr
);
1098 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1102 if (getitemstr
== NULL
)
1103 getitemstr
= PyString_InternFromString("__getitem__");
1104 func
= instance_getattr(inst
, getitemstr
);
1107 arg
= Py_BuildValue("(N)", _PySlice_FromIndices(i
, j
));
1109 arg
= Py_BuildValue("(nn)", i
, j
);
1115 res
= PyEval_CallObject(func
, arg
);
1122 instance_ass_item(PyInstanceObject
*inst
, Py_ssize_t i
, PyObject
*item
)
1124 PyObject
*func
, *arg
, *res
;
1127 if (delitemstr
== NULL
)
1128 delitemstr
= PyString_InternFromString("__delitem__");
1129 func
= instance_getattr(inst
, delitemstr
);
1132 if (setitemstr
== NULL
)
1133 setitemstr
= PyString_InternFromString("__setitem__");
1134 func
= instance_getattr(inst
, setitemstr
);
1139 arg
= PyInt_FromSsize_t(i
);
1141 arg
= Py_BuildValue("(nO)", i
, item
);
1146 res
= PyEval_CallObject(func
, arg
);
1156 instance_ass_slice(PyInstanceObject
*inst
, Py_ssize_t i
, Py_ssize_t j
, PyObject
*value
)
1158 PyObject
*func
, *arg
, *res
;
1159 static PyObject
*setslicestr
, *delslicestr
;
1161 if (value
== NULL
) {
1162 if (delslicestr
== NULL
)
1164 PyString_InternFromString("__delslice__");
1165 func
= instance_getattr(inst
, delslicestr
);
1167 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1170 if (delitemstr
== NULL
)
1172 PyString_InternFromString("__delitem__");
1173 func
= instance_getattr(inst
, delitemstr
);
1177 arg
= Py_BuildValue("(N)",
1178 _PySlice_FromIndices(i
, j
));
1180 arg
= Py_BuildValue("(nn)", i
, j
);
1183 if (setslicestr
== NULL
)
1185 PyString_InternFromString("__setslice__");
1186 func
= instance_getattr(inst
, setslicestr
);
1188 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1191 if (setitemstr
== NULL
)
1193 PyString_InternFromString("__setitem__");
1194 func
= instance_getattr(inst
, setitemstr
);
1198 arg
= Py_BuildValue("(NO)",
1199 _PySlice_FromIndices(i
, j
), value
);
1201 arg
= Py_BuildValue("(nnO)", i
, j
, value
);
1207 res
= PyEval_CallObject(func
, arg
);
1217 instance_contains(PyInstanceObject
*inst
, PyObject
*member
)
1219 static PyObject
*__contains__
;
1222 /* Try __contains__ first.
1223 * If that can't be done, try iterator-based searching.
1226 if(__contains__
== NULL
) {
1227 __contains__
= PyString_InternFromString("__contains__");
1228 if(__contains__
== NULL
)
1231 func
= instance_getattr(inst
, __contains__
);
1235 PyObject
*arg
= PyTuple_Pack(1, member
);
1240 res
= PyEval_CallObject(func
, arg
);
1245 ret
= PyObject_IsTrue(res
);
1250 /* Couldn't find __contains__. */
1251 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1252 /* Assume the failure was simply due to that there is no
1253 * __contains__ attribute, and try iterating instead.
1256 return _PySequence_IterSearch((PyObject
*)inst
, member
,
1257 PY_ITERSEARCH_CONTAINS
) > 0;
1263 static PySequenceMethods
1264 instance_as_sequence
= {
1265 (lenfunc
)instance_length
, /* sq_length */
1268 (ssizeargfunc
)instance_item
, /* sq_item */
1269 (ssizessizeargfunc
)instance_slice
, /* sq_slice */
1270 (ssizeobjargproc
)instance_ass_item
, /* sq_ass_item */
1271 (ssizessizeobjargproc
)instance_ass_slice
,/* sq_ass_slice */
1272 (objobjproc
)instance_contains
, /* sq_contains */
1276 generic_unary_op(PyInstanceObject
*self
, PyObject
*methodname
)
1278 PyObject
*func
, *res
;
1280 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1282 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1288 generic_binary_op(PyObject
*v
, PyObject
*w
, char *opname
)
1292 PyObject
*func
= PyObject_GetAttrString(v
, opname
);
1294 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1297 Py_INCREF(Py_NotImplemented
);
1298 return Py_NotImplemented
;
1300 args
= PyTuple_Pack(1, w
);
1305 result
= PyEval_CallObject(func
, args
);
1312 static PyObject
*coerce_obj
;
1314 /* Try one half of a binary operator involving a class instance. */
1316 half_binop(PyObject
*v
, PyObject
*w
, char *opname
, binaryfunc thisfunc
,
1320 PyObject
*coercefunc
;
1321 PyObject
*coerced
= NULL
;
1325 if (!PyInstance_Check(v
)) {
1326 Py_INCREF(Py_NotImplemented
);
1327 return Py_NotImplemented
;
1330 if (coerce_obj
== NULL
) {
1331 coerce_obj
= PyString_InternFromString("__coerce__");
1332 if (coerce_obj
== NULL
)
1335 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1336 if (coercefunc
== NULL
) {
1337 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1340 return generic_binary_op(v
, w
, opname
);
1343 args
= PyTuple_Pack(1, w
);
1345 Py_DECREF(coercefunc
);
1348 coerced
= PyEval_CallObject(coercefunc
, args
);
1350 Py_DECREF(coercefunc
);
1351 if (coerced
== NULL
) {
1354 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1356 return generic_binary_op(v
, w
, opname
);
1358 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1360 PyErr_SetString(PyExc_TypeError
,
1361 "coercion should return None or 2-tuple");
1364 v1
= PyTuple_GetItem(coerced
, 0);
1365 w
= PyTuple_GetItem(coerced
, 1);
1366 if (v1
->ob_type
== v
->ob_type
&& PyInstance_Check(v
)) {
1367 /* prevent recursion if __coerce__ returns self as the first
1369 result
= generic_binary_op(v1
, w
, opname
);
1371 if (Py_EnterRecursiveCall(" after coercion"))
1374 result
= (thisfunc
)(w
, v1
);
1376 result
= (thisfunc
)(v1
, w
);
1377 Py_LeaveRecursiveCall();
1383 /* Implement a binary operator involving at least one class instance. */
1385 do_binop(PyObject
*v
, PyObject
*w
, char *opname
, char *ropname
,
1386 binaryfunc thisfunc
)
1388 PyObject
*result
= half_binop(v
, w
, opname
, thisfunc
, 0);
1389 if (result
== Py_NotImplemented
) {
1391 result
= half_binop(w
, v
, ropname
, thisfunc
, 1);
1397 do_binop_inplace(PyObject
*v
, PyObject
*w
, char *iopname
, char *opname
,
1398 char *ropname
, binaryfunc thisfunc
)
1400 PyObject
*result
= half_binop(v
, w
, iopname
, thisfunc
, 0);
1401 if (result
== Py_NotImplemented
) {
1403 result
= do_binop(v
, w
, opname
, ropname
, thisfunc
);
1409 instance_coerce(PyObject
**pv
, PyObject
**pw
)
1413 PyObject
*coercefunc
;
1417 if (coerce_obj
== NULL
) {
1418 coerce_obj
= PyString_InternFromString("__coerce__");
1419 if (coerce_obj
== NULL
)
1422 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1423 if (coercefunc
== NULL
) {
1424 /* No __coerce__ method */
1425 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1430 /* Has __coerce__ method: call it */
1431 args
= PyTuple_Pack(1, w
);
1435 coerced
= PyEval_CallObject(coercefunc
, args
);
1437 Py_DECREF(coercefunc
);
1438 if (coerced
== NULL
) {
1439 /* __coerce__ call raised an exception */
1442 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1443 /* __coerce__ says "I can't do it" */
1447 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1448 /* __coerce__ return value is malformed */
1450 PyErr_SetString(PyExc_TypeError
,
1451 "coercion should return None or 2-tuple");
1454 /* __coerce__ returned two new values */
1455 *pv
= PyTuple_GetItem(coerced
, 0);
1456 *pw
= PyTuple_GetItem(coerced
, 1);
1463 #define UNARY(funcname, methodname) \
1464 static PyObject *funcname(PyInstanceObject *self) { \
1465 static PyObject *o; \
1466 if (o == NULL) o = PyString_InternFromString(methodname); \
1467 return generic_unary_op(self, o); \
1470 #define BINARY(f, m, n) \
1471 static PyObject *f(PyObject *v, PyObject *w) { \
1472 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1475 #define BINARY_INPLACE(f, m, n) \
1476 static PyObject *f(PyObject *v, PyObject *w) { \
1477 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1481 UNARY(instance_neg
, "__neg__")
1482 UNARY(instance_pos
, "__pos__")
1483 UNARY(instance_abs
, "__abs__")
1485 BINARY(instance_or
, "or", PyNumber_Or
)
1486 BINARY(instance_and
, "and", PyNumber_And
)
1487 BINARY(instance_xor
, "xor", PyNumber_Xor
)
1488 BINARY(instance_lshift
, "lshift", PyNumber_Lshift
)
1489 BINARY(instance_rshift
, "rshift", PyNumber_Rshift
)
1490 BINARY(instance_add
, "add", PyNumber_Add
)
1491 BINARY(instance_sub
, "sub", PyNumber_Subtract
)
1492 BINARY(instance_mul
, "mul", PyNumber_Multiply
)
1493 BINARY(instance_div
, "div", PyNumber_Divide
)
1494 BINARY(instance_mod
, "mod", PyNumber_Remainder
)
1495 BINARY(instance_divmod
, "divmod", PyNumber_Divmod
)
1496 BINARY(instance_floordiv
, "floordiv", PyNumber_FloorDivide
)
1497 BINARY(instance_truediv
, "truediv", PyNumber_TrueDivide
)
1499 BINARY_INPLACE(instance_ior
, "or", PyNumber_InPlaceOr
)
1500 BINARY_INPLACE(instance_ixor
, "xor", PyNumber_InPlaceXor
)
1501 BINARY_INPLACE(instance_iand
, "and", PyNumber_InPlaceAnd
)
1502 BINARY_INPLACE(instance_ilshift
, "lshift", PyNumber_InPlaceLshift
)
1503 BINARY_INPLACE(instance_irshift
, "rshift", PyNumber_InPlaceRshift
)
1504 BINARY_INPLACE(instance_iadd
, "add", PyNumber_InPlaceAdd
)
1505 BINARY_INPLACE(instance_isub
, "sub", PyNumber_InPlaceSubtract
)
1506 BINARY_INPLACE(instance_imul
, "mul", PyNumber_InPlaceMultiply
)
1507 BINARY_INPLACE(instance_idiv
, "div", PyNumber_InPlaceDivide
)
1508 BINARY_INPLACE(instance_imod
, "mod", PyNumber_InPlaceRemainder
)
1509 BINARY_INPLACE(instance_ifloordiv
, "floordiv", PyNumber_InPlaceFloorDivide
)
1510 BINARY_INPLACE(instance_itruediv
, "truediv", PyNumber_InPlaceTrueDivide
)
1512 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1513 -2 for an exception;
1517 2 if this particular 3-way comparison is not implemented or undefined.
1520 half_cmp(PyObject
*v
, PyObject
*w
)
1522 static PyObject
*cmp_obj
;
1528 assert(PyInstance_Check(v
));
1530 if (cmp_obj
== NULL
) {
1531 cmp_obj
= PyString_InternFromString("__cmp__");
1532 if (cmp_obj
== NULL
)
1536 cmp_func
= PyObject_GetAttr(v
, cmp_obj
);
1537 if (cmp_func
== NULL
) {
1538 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1544 args
= PyTuple_Pack(1, w
);
1546 Py_DECREF(cmp_func
);
1550 result
= PyEval_CallObject(cmp_func
, args
);
1552 Py_DECREF(cmp_func
);
1557 if (result
== Py_NotImplemented
) {
1562 l
= PyInt_AsLong(result
);
1564 if (l
== -1 && PyErr_Occurred()) {
1565 PyErr_SetString(PyExc_TypeError
,
1566 "comparison did not return an int");
1570 return l
< 0 ? -1 : l
> 0 ? 1 : 0;
1573 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1574 We first try a coercion. Return:
1575 -2 for an exception;
1579 2 if this particular 3-way comparison is not implemented or undefined.
1580 THIS IS ONLY CALLED FROM object.c!
1583 instance_compare(PyObject
*v
, PyObject
*w
)
1587 c
= PyNumber_CoerceEx(&v
, &w
);
1591 /* If neither is now an instance, use regular comparison */
1592 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1593 c
= PyObject_Compare(v
, w
);
1596 if (PyErr_Occurred())
1598 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
1602 /* The coercion didn't do anything.
1603 Treat this the same as returning v and w unchanged. */
1608 if (PyInstance_Check(v
)) {
1616 if (PyInstance_Check(w
)) {
1632 instance_nonzero(PyInstanceObject
*self
)
1634 PyObject
*func
, *res
;
1636 static PyObject
*nonzerostr
;
1638 if (nonzerostr
== NULL
)
1639 nonzerostr
= PyString_InternFromString("__nonzero__");
1640 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1641 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1645 lenstr
= PyString_InternFromString("__len__");
1646 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1647 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1650 /* Fall back to the default behavior:
1651 all instances are nonzero */
1655 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1659 if (!PyInt_Check(res
)) {
1661 PyErr_SetString(PyExc_TypeError
,
1662 "__nonzero__ should return an int");
1665 outcome
= PyInt_AsLong(res
);
1668 PyErr_SetString(PyExc_ValueError
,
1669 "__nonzero__ should return >= 0");
1676 instance_index(PyInstanceObject
*self
)
1678 PyObject
*func
, *res
;
1680 static PyObject
*indexstr
= NULL
;
1682 if (indexstr
== NULL
) {
1683 indexstr
= PyString_InternFromString("__index__");
1684 if (indexstr
== NULL
)
1687 if ((func
= instance_getattr(self
, indexstr
)) == NULL
) {
1688 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1691 PyErr_SetString(PyExc_TypeError
,
1692 "object cannot be interpreted as an index");
1695 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1699 if (PyInt_Check(res
) || PyLong_Check(res
)) {
1700 outcome
= res
->ob_type
->tp_as_number
->nb_index(res
);
1703 PyErr_SetString(PyExc_TypeError
,
1704 "__index__ must return an int or a long");
1712 UNARY(instance_invert
, "__invert__")
1713 UNARY(instance_int
, "__int__")
1714 UNARY(instance_long
, "__long__")
1715 UNARY(instance_float
, "__float__")
1716 UNARY(instance_oct
, "__oct__")
1717 UNARY(instance_hex
, "__hex__")
1720 bin_power(PyObject
*v
, PyObject
*w
)
1722 return PyNumber_Power(v
, w
, Py_None
);
1725 /* This version is for ternary calls only (z != None) */
1727 instance_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1730 return do_binop(v
, w
, "__pow__", "__rpow__", bin_power
);
1737 /* XXX Doesn't do coercions... */
1738 func
= PyObject_GetAttrString(v
, "__pow__");
1741 args
= PyTuple_Pack(2, w
, z
);
1746 result
= PyEval_CallObject(func
, args
);
1754 bin_inplace_power(PyObject
*v
, PyObject
*w
)
1756 return PyNumber_InPlacePower(v
, w
, Py_None
);
1761 instance_ipow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1764 return do_binop_inplace(v
, w
, "__ipow__", "__pow__",
1765 "__rpow__", bin_inplace_power
);
1768 /* XXX Doesn't do coercions... */
1773 func
= PyObject_GetAttrString(v
, "__ipow__");
1775 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1778 return instance_pow(v
, w
, z
);
1780 args
= PyTuple_Pack(2, w
, z
);
1785 result
= PyEval_CallObject(func
, args
);
1793 /* Map rich comparison operators to their __xx__ namesakes */
1795 static PyObject
**name_op
= NULL
;
1801 char *_name_op
[] = {
1810 name_op
= (PyObject
**)malloc(sizeof(PyObject
*) * NAME_OPS
);
1811 if (name_op
== NULL
)
1813 for (i
= 0; i
< NAME_OPS
; ++i
) {
1814 name_op
[i
] = PyString_InternFromString(_name_op
[i
]);
1815 if (name_op
[i
] == NULL
)
1822 half_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1828 assert(PyInstance_Check(v
));
1830 if (name_op
== NULL
) {
1831 if (init_name_op() < 0)
1834 /* If the instance doesn't define an __getattr__ method, use
1835 instance_getattr2 directly because it will not set an
1836 exception on failure. */
1837 if (((PyInstanceObject
*)v
)->in_class
->cl_getattr
== NULL
)
1838 method
= instance_getattr2((PyInstanceObject
*)v
,
1841 method
= PyObject_GetAttr(v
, name_op
[op
]);
1842 if (method
== NULL
) {
1843 if (PyErr_Occurred()) {
1844 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1848 res
= Py_NotImplemented
;
1853 args
= PyTuple_Pack(1, w
);
1859 res
= PyEval_CallObject(method
, args
);
1867 instance_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1871 if (PyInstance_Check(v
)) {
1872 res
= half_richcompare(v
, w
, op
);
1873 if (res
!= Py_NotImplemented
)
1878 if (PyInstance_Check(w
)) {
1879 res
= half_richcompare(w
, v
, _Py_SwappedOp
[op
]);
1880 if (res
!= Py_NotImplemented
)
1885 Py_INCREF(Py_NotImplemented
);
1886 return Py_NotImplemented
;
1890 /* Get the iterator */
1892 instance_getiter(PyInstanceObject
*self
)
1896 if (iterstr
== NULL
) {
1897 iterstr
= PyString_InternFromString("__iter__");
1898 if (iterstr
== NULL
)
1901 if (getitemstr
== NULL
) {
1902 getitemstr
= PyString_InternFromString("__getitem__");
1903 if (getitemstr
== NULL
)
1907 if ((func
= instance_getattr(self
, iterstr
)) != NULL
) {
1908 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1910 if (res
!= NULL
&& !PyIter_Check(res
)) {
1911 PyErr_Format(PyExc_TypeError
,
1912 "__iter__ returned non-iterator "
1914 res
->ob_type
->tp_name
);
1920 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1923 if ((func
= instance_getattr(self
, getitemstr
)) == NULL
) {
1924 PyErr_SetString(PyExc_TypeError
,
1925 "iteration over non-sequence");
1929 return PySeqIter_New((PyObject
*)self
);
1933 /* Call the iterator's next */
1935 instance_iternext(PyInstanceObject
*self
)
1939 if (nextstr
== NULL
)
1940 nextstr
= PyString_InternFromString("next");
1942 if ((func
= instance_getattr(self
, nextstr
)) != NULL
) {
1943 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1948 if (PyErr_ExceptionMatches(PyExc_StopIteration
)) {
1954 PyErr_SetString(PyExc_TypeError
, "instance has no next() method");
1959 instance_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
1961 PyObject
*res
, *call
= PyObject_GetAttrString(func
, "__call__");
1963 PyInstanceObject
*inst
= (PyInstanceObject
*) func
;
1964 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1967 PyErr_Format(PyExc_AttributeError
,
1968 "%.200s instance has no __call__ method",
1969 PyString_AsString(inst
->in_class
->cl_name
));
1972 /* We must check and increment the recursion depth here. Scenario:
1975 A.__call__ = A() # that's right
1977 a() # infinite recursion
1978 This bounces between instance_call() and PyObject_Call() without
1979 ever hitting eval_frame() (which has the main recursion check). */
1980 if (Py_EnterRecursiveCall(" in __call__")) {
1984 res
= PyObject_Call(call
, arg
, kw
);
1985 Py_LeaveRecursiveCall();
1992 static PyNumberMethods instance_as_number
= {
1993 instance_add
, /* nb_add */
1994 instance_sub
, /* nb_subtract */
1995 instance_mul
, /* nb_multiply */
1996 instance_div
, /* nb_divide */
1997 instance_mod
, /* nb_remainder */
1998 instance_divmod
, /* nb_divmod */
1999 instance_pow
, /* nb_power */
2000 (unaryfunc
)instance_neg
, /* nb_negative */
2001 (unaryfunc
)instance_pos
, /* nb_positive */
2002 (unaryfunc
)instance_abs
, /* nb_absolute */
2003 (inquiry
)instance_nonzero
, /* nb_nonzero */
2004 (unaryfunc
)instance_invert
, /* nb_invert */
2005 instance_lshift
, /* nb_lshift */
2006 instance_rshift
, /* nb_rshift */
2007 instance_and
, /* nb_and */
2008 instance_xor
, /* nb_xor */
2009 instance_or
, /* nb_or */
2010 instance_coerce
, /* nb_coerce */
2011 (unaryfunc
)instance_int
, /* nb_int */
2012 (unaryfunc
)instance_long
, /* nb_long */
2013 (unaryfunc
)instance_float
, /* nb_float */
2014 (unaryfunc
)instance_oct
, /* nb_oct */
2015 (unaryfunc
)instance_hex
, /* nb_hex */
2016 instance_iadd
, /* nb_inplace_add */
2017 instance_isub
, /* nb_inplace_subtract */
2018 instance_imul
, /* nb_inplace_multiply */
2019 instance_idiv
, /* nb_inplace_divide */
2020 instance_imod
, /* nb_inplace_remainder */
2021 instance_ipow
, /* nb_inplace_power */
2022 instance_ilshift
, /* nb_inplace_lshift */
2023 instance_irshift
, /* nb_inplace_rshift */
2024 instance_iand
, /* nb_inplace_and */
2025 instance_ixor
, /* nb_inplace_xor */
2026 instance_ior
, /* nb_inplace_or */
2027 instance_floordiv
, /* nb_floor_divide */
2028 instance_truediv
, /* nb_true_divide */
2029 instance_ifloordiv
, /* nb_inplace_floor_divide */
2030 instance_itruediv
, /* nb_inplace_true_divide */
2031 (lenfunc
)instance_index
, /* nb_index */
2034 PyTypeObject PyInstance_Type
= {
2035 PyObject_HEAD_INIT(&PyType_Type
)
2038 sizeof(PyInstanceObject
),
2040 (destructor
)instance_dealloc
, /* tp_dealloc */
2044 instance_compare
, /* tp_compare */
2045 (reprfunc
)instance_repr
, /* tp_repr */
2046 &instance_as_number
, /* tp_as_number */
2047 &instance_as_sequence
, /* tp_as_sequence */
2048 &instance_as_mapping
, /* tp_as_mapping */
2049 (hashfunc
)instance_hash
, /* tp_hash */
2050 instance_call
, /* tp_call */
2051 (reprfunc
)instance_str
, /* tp_str */
2052 (getattrofunc
)instance_getattr
, /* tp_getattro */
2053 (setattrofunc
)instance_setattr
, /* tp_setattro */
2054 0, /* tp_as_buffer */
2055 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
,/*tp_flags*/
2056 instance_doc
, /* tp_doc */
2057 (traverseproc
)instance_traverse
, /* tp_traverse */
2059 instance_richcompare
, /* tp_richcompare */
2060 offsetof(PyInstanceObject
, in_weakreflist
), /* tp_weaklistoffset */
2061 (getiterfunc
)instance_getiter
, /* tp_iter */
2062 (iternextfunc
)instance_iternext
, /* tp_iternext */
2068 0, /* tp_descr_get */
2069 0, /* tp_descr_set */
2070 0, /* tp_dictoffset */
2073 instance_new
, /* tp_new */
2077 /* Instance method objects are used for two purposes:
2078 (a) as bound instance methods (returned by instancename.methodname)
2079 (b) as unbound methods (returned by ClassName.methodname)
2080 In case (b), im_self is NULL
2083 static PyMethodObject
*free_list
;
2086 PyMethod_New(PyObject
*func
, PyObject
*self
, PyObject
*klass
)
2088 register PyMethodObject
*im
;
2089 if (!PyCallable_Check(func
)) {
2090 PyErr_BadInternalCall();
2095 free_list
= (PyMethodObject
*)(im
->im_self
);
2096 PyObject_INIT(im
, &PyMethod_Type
);
2099 im
= PyObject_GC_New(PyMethodObject
, &PyMethod_Type
);
2103 im
->im_weakreflist
= NULL
;
2109 im
->im_class
= klass
;
2110 _PyObject_GC_TRACK(im
);
2111 return (PyObject
*)im
;
2114 /* Descriptors for PyMethod attributes */
2116 /* im_class, im_func and im_self are stored in the PyMethod object */
2118 #define OFF(x) offsetof(PyMethodObject, x)
2120 static PyMemberDef instancemethod_memberlist
[] = {
2121 {"im_class", T_OBJECT
, OFF(im_class
), READONLY
|RESTRICTED
,
2122 "the class associated with a method"},
2123 {"im_func", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2124 "the function (or other callable) implementing a method"},
2125 {"im_self", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2126 "the instance to which a method is bound; None for unbound methods"},
2127 {NULL
} /* Sentinel */
2130 /* Christian Tismer argued convincingly that method attributes should
2131 (nearly) always override function attributes.
2132 The one exception is __doc__; there's a default __doc__ which
2133 should only be used for the class, not for instances */
2136 instancemethod_get_doc(PyMethodObject
*im
, void *context
)
2138 static PyObject
*docstr
;
2139 if (docstr
== NULL
) {
2140 docstr
= PyString_InternFromString("__doc__");
2144 return PyObject_GetAttr(im
->im_func
, docstr
);
2147 static PyGetSetDef instancemethod_getset
[] = {
2148 {"__doc__", (getter
)instancemethod_get_doc
, NULL
, NULL
},
2153 instancemethod_getattro(PyObject
*obj
, PyObject
*name
)
2155 PyMethodObject
*im
= (PyMethodObject
*)obj
;
2156 PyTypeObject
*tp
= obj
->ob_type
;
2157 PyObject
*descr
= NULL
;
2159 if (PyType_HasFeature(tp
, Py_TPFLAGS_HAVE_CLASS
)) {
2160 if (tp
->tp_dict
== NULL
) {
2161 if (PyType_Ready(tp
) < 0)
2164 descr
= _PyType_Lookup(tp
, name
);
2167 if (descr
!= NULL
) {
2168 descrgetfunc f
= TP_DESCR_GET(descr
->ob_type
);
2170 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2177 return PyObject_GetAttr(im
->im_func
, name
);
2180 PyDoc_STRVAR(instancemethod_doc
,
2181 "instancemethod(function, instance, class)\n\
2183 Create an instance method object.");
2186 instancemethod_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
2190 PyObject
*classObj
= NULL
;
2192 if (!PyArg_UnpackTuple(args
, "instancemethod", 2, 3,
2193 &func
, &self
, &classObj
))
2195 if (!PyCallable_Check(func
)) {
2196 PyErr_SetString(PyExc_TypeError
,
2197 "first argument must be callable");
2200 if (self
== Py_None
)
2202 if (self
== NULL
&& classObj
== NULL
) {
2203 PyErr_SetString(PyExc_TypeError
,
2204 "unbound methods must have non-NULL im_class");
2208 return PyMethod_New(func
, self
, classObj
);
2212 instancemethod_dealloc(register PyMethodObject
*im
)
2214 _PyObject_GC_UNTRACK(im
);
2215 if (im
->im_weakreflist
!= NULL
)
2216 PyObject_ClearWeakRefs((PyObject
*)im
);
2217 Py_DECREF(im
->im_func
);
2218 Py_XDECREF(im
->im_self
);
2219 Py_XDECREF(im
->im_class
);
2220 im
->im_self
= (PyObject
*)free_list
;
2225 instancemethod_compare(PyMethodObject
*a
, PyMethodObject
*b
)
2228 cmp
= PyObject_Compare(a
->im_func
, b
->im_func
);
2232 if (a
->im_self
== b
->im_self
)
2234 if (a
->im_self
== NULL
|| b
->im_self
== NULL
)
2235 return (a
->im_self
< b
->im_self
) ? -1 : 1;
2237 return PyObject_Compare(a
->im_self
, b
->im_self
);
2241 instancemethod_repr(PyMethodObject
*a
)
2243 PyObject
*self
= a
->im_self
;
2244 PyObject
*func
= a
->im_func
;
2245 PyObject
*klass
= a
->im_class
;
2246 PyObject
*funcname
= NULL
, *klassname
= NULL
, *result
= NULL
;
2247 char *sfuncname
= "?", *sklassname
= "?";
2249 funcname
= PyObject_GetAttrString(func
, "__name__");
2250 if (funcname
== NULL
) {
2251 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2255 else if (!PyString_Check(funcname
)) {
2256 Py_DECREF(funcname
);
2260 sfuncname
= PyString_AS_STRING(funcname
);
2264 klassname
= PyObject_GetAttrString(klass
, "__name__");
2265 if (klassname
== NULL
) {
2266 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2270 else if (!PyString_Check(klassname
)) {
2271 Py_DECREF(klassname
);
2275 sklassname
= PyString_AS_STRING(klassname
);
2278 result
= PyString_FromFormat("<unbound method %s.%s>",
2279 sklassname
, sfuncname
);
2281 /* XXX Shouldn't use repr() here! */
2282 PyObject
*selfrepr
= PyObject_Repr(self
);
2283 if (selfrepr
== NULL
)
2285 if (!PyString_Check(selfrepr
)) {
2286 Py_DECREF(selfrepr
);
2289 result
= PyString_FromFormat("<bound method %s.%s of %s>",
2290 sklassname
, sfuncname
,
2291 PyString_AS_STRING(selfrepr
));
2292 Py_DECREF(selfrepr
);
2295 Py_XDECREF(funcname
);
2296 Py_XDECREF(klassname
);
2301 instancemethod_hash(PyMethodObject
*a
)
2304 if (a
->im_self
== NULL
)
2305 x
= PyObject_Hash(Py_None
);
2307 x
= PyObject_Hash(a
->im_self
);
2310 y
= PyObject_Hash(a
->im_func
);
2320 instancemethod_traverse(PyMethodObject
*im
, visitproc visit
, void *arg
)
2322 Py_VISIT(im
->im_func
);
2323 Py_VISIT(im
->im_self
);
2324 Py_VISIT(im
->im_class
);
2329 getclassname(PyObject
*klass
, char *buf
, int bufsize
)
2333 assert(bufsize
> 1);
2334 strcpy(buf
, "?"); /* Default outcome */
2337 name
= PyObject_GetAttrString(klass
, "__name__");
2339 /* This function cannot return an exception */
2343 if (PyString_Check(name
)) {
2344 strncpy(buf
, PyString_AS_STRING(name
), bufsize
);
2345 buf
[bufsize
-1] = '\0';
2351 getinstclassname(PyObject
*inst
, char *buf
, int bufsize
)
2356 assert(bufsize
> 0 && (size_t)bufsize
> strlen("nothing"));
2357 strcpy(buf
, "nothing");
2361 klass
= PyObject_GetAttrString(inst
, "__class__");
2362 if (klass
== NULL
) {
2363 /* This function cannot return an exception */
2365 klass
= (PyObject
*)(inst
->ob_type
);
2368 getclassname(klass
, buf
, bufsize
);
2373 instancemethod_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2375 PyObject
*self
= PyMethod_GET_SELF(func
);
2376 PyObject
*klass
= PyMethod_GET_CLASS(func
);
2379 func
= PyMethod_GET_FUNCTION(func
);
2381 /* Unbound methods must be called with an instance of
2382 the class (or a derived class) as first argument */
2384 if (PyTuple_Size(arg
) >= 1)
2385 self
= PyTuple_GET_ITEM(arg
, 0);
2389 ok
= PyObject_IsInstance(self
, klass
);
2396 getclassname(klass
, clsbuf
, sizeof(clsbuf
));
2397 getinstclassname(self
, instbuf
, sizeof(instbuf
));
2398 PyErr_Format(PyExc_TypeError
,
2399 "unbound method %s%s must be called with "
2400 "%s instance as first argument "
2401 "(got %s%s instead)",
2402 PyEval_GetFuncName(func
),
2403 PyEval_GetFuncDesc(func
),
2406 self
== NULL
? "" : " instance");
2412 Py_ssize_t argcount
= PyTuple_Size(arg
);
2413 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2418 PyTuple_SET_ITEM(newarg
, 0, self
);
2419 for (i
= 0; i
< argcount
; i
++) {
2420 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2422 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2426 result
= PyObject_Call((PyObject
*)func
, arg
, kw
);
2432 instancemethod_descr_get(PyObject
*meth
, PyObject
*obj
, PyObject
*cls
)
2434 /* Don't rebind an already bound method, or an unbound method
2435 of a class that's not a base class of cls. */
2437 if (PyMethod_GET_SELF(meth
) != NULL
) {
2442 /* No, it is an unbound method */
2443 if (PyMethod_GET_CLASS(meth
) != NULL
&& cls
!= NULL
) {
2444 /* Do subclass test. If it fails, return meth unchanged. */
2445 int ok
= PyObject_IsSubclass(cls
, PyMethod_GET_CLASS(meth
));
2453 /* Bind it to obj */
2454 return PyMethod_New(PyMethod_GET_FUNCTION(meth
), obj
, cls
);
2457 PyTypeObject PyMethod_Type
= {
2458 PyObject_HEAD_INIT(&PyType_Type
)
2461 sizeof(PyMethodObject
),
2463 (destructor
)instancemethod_dealloc
, /* tp_dealloc */
2467 (cmpfunc
)instancemethod_compare
, /* tp_compare */
2468 (reprfunc
)instancemethod_repr
, /* tp_repr */
2469 0, /* tp_as_number */
2470 0, /* tp_as_sequence */
2471 0, /* tp_as_mapping */
2472 (hashfunc
)instancemethod_hash
, /* tp_hash */
2473 instancemethod_call
, /* tp_call */
2475 instancemethod_getattro
, /* tp_getattro */
2476 PyObject_GenericSetAttr
, /* tp_setattro */
2477 0, /* tp_as_buffer */
2478 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
2479 instancemethod_doc
, /* tp_doc */
2480 (traverseproc
)instancemethod_traverse
, /* tp_traverse */
2482 0, /* tp_richcompare */
2483 offsetof(PyMethodObject
, im_weakreflist
), /* tp_weaklistoffset */
2485 0, /* tp_iternext */
2487 instancemethod_memberlist
, /* tp_members */
2488 instancemethod_getset
, /* tp_getset */
2491 instancemethod_descr_get
, /* tp_descr_get */
2492 0, /* tp_descr_set */
2493 0, /* tp_dictoffset */
2496 instancemethod_new
, /* tp_new */
2499 /* Clear out the free list */
2505 PyMethodObject
*im
= free_list
;
2506 free_list
= (PyMethodObject
*)(im
->im_self
);
2507 PyObject_GC_Del(im
);