2 /* Class object implementation */
5 #include "structmember.h"
7 /* Free list for method objects to safe malloc/free overhead
8 * The im_self element is used to chain the elements.
10 static PyMethodObject
*free_list
;
11 static int numfree
= 0;
12 #ifndef PyMethod_MAXFREELIST
13 #define PyMethod_MAXFREELIST 256
16 #define TP_DESCR_GET(t) \
17 (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
20 static PyObject
*class_lookup(PyClassObject
*, PyObject
*,
22 static PyObject
*instance_getattr1(PyInstanceObject
*, PyObject
*);
23 static PyObject
*instance_getattr2(PyInstanceObject
*, PyObject
*);
25 static PyObject
*getattrstr
, *setattrstr
, *delattrstr
;
29 PyClass_New(PyObject
*bases
, PyObject
*dict
, PyObject
*name
)
30 /* bases is NULL or tuple of classobjects! */
32 PyClassObject
*op
, *dummy
;
33 static PyObject
*docstr
, *modstr
, *namestr
;
35 docstr
= PyString_InternFromString("__doc__");
40 modstr
= PyString_InternFromString("__module__");
44 if (namestr
== NULL
) {
45 namestr
= PyString_InternFromString("__name__");
49 if (name
== NULL
|| !PyString_Check(name
)) {
50 PyErr_SetString(PyExc_TypeError
,
51 "PyClass_New: name must be a string");
54 if (dict
== NULL
|| !PyDict_Check(dict
)) {
55 PyErr_SetString(PyExc_TypeError
,
56 "PyClass_New: dict must be a dictionary");
59 if (PyDict_GetItem(dict
, docstr
) == NULL
) {
60 if (PyDict_SetItem(dict
, docstr
, Py_None
) < 0)
63 if (PyDict_GetItem(dict
, modstr
) == NULL
) {
64 PyObject
*globals
= PyEval_GetGlobals();
65 if (globals
!= NULL
) {
66 PyObject
*modname
= PyDict_GetItem(globals
, namestr
);
67 if (modname
!= NULL
) {
68 if (PyDict_SetItem(dict
, modstr
, modname
) < 0)
74 bases
= PyTuple_New(0);
81 if (!PyTuple_Check(bases
)) {
82 PyErr_SetString(PyExc_TypeError
,
83 "PyClass_New: bases must be a tuple");
86 n
= PyTuple_Size(bases
);
87 for (i
= 0; i
< n
; i
++) {
88 base
= PyTuple_GET_ITEM(bases
, i
);
89 if (!PyClass_Check(base
)) {
91 (PyObject
*) base
->ob_type
))
92 return PyObject_CallFunctionObjArgs(
93 (PyObject
*) base
->ob_type
,
94 name
, bases
, dict
, NULL
);
95 PyErr_SetString(PyExc_TypeError
,
96 "PyClass_New: base must be a class");
103 if (getattrstr
== NULL
) {
104 getattrstr
= PyString_InternFromString("__getattr__");
105 if (getattrstr
== NULL
)
107 setattrstr
= PyString_InternFromString("__setattr__");
108 if (setattrstr
== NULL
)
110 delattrstr
= PyString_InternFromString("__delattr__");
111 if (delattrstr
== NULL
)
115 op
= PyObject_GC_New(PyClassObject
, &PyClass_Type
);
121 op
->cl_bases
= bases
;
127 op
->cl_getattr
= class_lookup(op
, getattrstr
, &dummy
);
128 op
->cl_setattr
= class_lookup(op
, setattrstr
, &dummy
);
129 op
->cl_delattr
= class_lookup(op
, delattrstr
, &dummy
);
130 Py_XINCREF(op
->cl_getattr
);
131 Py_XINCREF(op
->cl_setattr
);
132 Py_XINCREF(op
->cl_delattr
);
133 _PyObject_GC_TRACK(op
);
134 return (PyObject
*) op
;
138 PyMethod_Function(PyObject
*im
)
140 if (!PyMethod_Check(im
)) {
141 PyErr_BadInternalCall();
144 return ((PyMethodObject
*)im
)->im_func
;
148 PyMethod_Self(PyObject
*im
)
150 if (!PyMethod_Check(im
)) {
151 PyErr_BadInternalCall();
154 return ((PyMethodObject
*)im
)->im_self
;
158 PyMethod_Class(PyObject
*im
)
160 if (!PyMethod_Check(im
)) {
161 PyErr_BadInternalCall();
164 return ((PyMethodObject
*)im
)->im_class
;
167 PyDoc_STRVAR(class_doc
,
168 "classobj(name, bases, dict)\n\
170 Create a class object. The name must be a string; the second argument\n\
171 a tuple of classes, and the third a dictionary.");
174 class_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
176 PyObject
*name
, *bases
, *dict
;
177 static char *kwlist
[] = {"name", "bases", "dict", 0};
179 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "SOO", kwlist
,
180 &name
, &bases
, &dict
))
182 return PyClass_New(bases
, dict
, name
);
188 class_dealloc(PyClassObject
*op
)
190 _PyObject_GC_UNTRACK(op
);
191 Py_DECREF(op
->cl_bases
);
192 Py_DECREF(op
->cl_dict
);
193 Py_XDECREF(op
->cl_name
);
194 Py_XDECREF(op
->cl_getattr
);
195 Py_XDECREF(op
->cl_setattr
);
196 Py_XDECREF(op
->cl_delattr
);
201 class_lookup(PyClassObject
*cp
, PyObject
*name
, PyClassObject
**pclass
)
204 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
209 n
= PyTuple_Size(cp
->cl_bases
);
210 for (i
= 0; i
< n
; i
++) {
211 /* XXX What if one of the bases is not a class? */
212 PyObject
*v
= class_lookup(
214 PyTuple_GetItem(cp
->cl_bases
, i
), name
, pclass
);
222 class_getattr(register PyClassObject
*op
, PyObject
*name
)
224 register PyObject
*v
;
225 register char *sname
= PyString_AsString(name
);
226 PyClassObject
*klass
;
229 if (sname
[0] == '_' && sname
[1] == '_') {
230 if (strcmp(sname
, "__dict__") == 0) {
231 if (PyEval_GetRestricted()) {
232 PyErr_SetString(PyExc_RuntimeError
,
233 "class.__dict__ not accessible in restricted mode");
236 Py_INCREF(op
->cl_dict
);
239 if (strcmp(sname
, "__bases__") == 0) {
240 Py_INCREF(op
->cl_bases
);
243 if (strcmp(sname
, "__name__") == 0) {
244 if (op
->cl_name
== NULL
)
252 v
= class_lookup(op
, name
, &klass
);
254 PyErr_Format(PyExc_AttributeError
,
255 "class %.50s has no attribute '%.400s'",
256 PyString_AS_STRING(op
->cl_name
), sname
);
259 f
= TP_DESCR_GET(v
->ob_type
);
263 v
= f(v
, (PyObject
*)NULL
, (PyObject
*)op
);
268 set_slot(PyObject
**slot
, PyObject
*v
)
270 PyObject
*temp
= *slot
;
277 set_attr_slots(PyClassObject
*c
)
279 PyClassObject
*dummy
;
281 set_slot(&c
->cl_getattr
, class_lookup(c
, getattrstr
, &dummy
));
282 set_slot(&c
->cl_setattr
, class_lookup(c
, setattrstr
, &dummy
));
283 set_slot(&c
->cl_delattr
, class_lookup(c
, delattrstr
, &dummy
));
287 set_dict(PyClassObject
*c
, PyObject
*v
)
289 if (v
== NULL
|| !PyDict_Check(v
))
290 return "__dict__ must be a dictionary object";
291 set_slot(&c
->cl_dict
, v
);
297 set_bases(PyClassObject
*c
, PyObject
*v
)
301 if (v
== NULL
|| !PyTuple_Check(v
))
302 return "__bases__ must be a tuple object";
304 for (i
= 0; i
< n
; i
++) {
305 PyObject
*x
= PyTuple_GET_ITEM(v
, i
);
306 if (!PyClass_Check(x
))
307 return "__bases__ items must be classes";
308 if (PyClass_IsSubclass(x
, (PyObject
*)c
))
309 return "a __bases__ item causes an inheritance cycle";
311 set_slot(&c
->cl_bases
, v
);
317 set_name(PyClassObject
*c
, PyObject
*v
)
319 if (v
== NULL
|| !PyString_Check(v
))
320 return "__name__ must be a string object";
321 if (strlen(PyString_AS_STRING(v
)) != (size_t)PyString_GET_SIZE(v
))
322 return "__name__ must not contain null bytes";
323 set_slot(&c
->cl_name
, v
);
328 class_setattr(PyClassObject
*op
, PyObject
*name
, PyObject
*v
)
331 if (PyEval_GetRestricted()) {
332 PyErr_SetString(PyExc_RuntimeError
,
333 "classes are read-only in restricted mode");
336 sname
= PyString_AsString(name
);
337 if (sname
[0] == '_' && sname
[1] == '_') {
338 Py_ssize_t n
= PyString_Size(name
);
339 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
341 if (strcmp(sname
, "__dict__") == 0)
342 err
= set_dict(op
, v
);
343 else if (strcmp(sname
, "__bases__") == 0)
344 err
= set_bases(op
, v
);
345 else if (strcmp(sname
, "__name__") == 0)
346 err
= set_name(op
, v
);
347 else if (strcmp(sname
, "__getattr__") == 0)
348 set_slot(&op
->cl_getattr
, v
);
349 else if (strcmp(sname
, "__setattr__") == 0)
350 set_slot(&op
->cl_setattr
, v
);
351 else if (strcmp(sname
, "__delattr__") == 0)
352 set_slot(&op
->cl_delattr
, v
);
353 /* For the last three, we fall through to update the
354 dictionary as well. */
358 PyErr_SetString(PyExc_TypeError
, err
);
364 int rv
= PyDict_DelItem(op
->cl_dict
, name
);
366 PyErr_Format(PyExc_AttributeError
,
367 "class %.50s has no attribute '%.400s'",
368 PyString_AS_STRING(op
->cl_name
), sname
);
372 return PyDict_SetItem(op
->cl_dict
, name
, v
);
376 class_repr(PyClassObject
*op
)
378 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
380 if (op
->cl_name
== NULL
|| !PyString_Check(op
->cl_name
))
383 name
= PyString_AsString(op
->cl_name
);
384 if (mod
== NULL
|| !PyString_Check(mod
))
385 return PyString_FromFormat("<class ?.%s at %p>", name
, op
);
387 return PyString_FromFormat("<class %s.%s at %p>",
388 PyString_AsString(mod
),
393 class_str(PyClassObject
*op
)
395 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
396 PyObject
*name
= op
->cl_name
;
400 if (name
== NULL
|| !PyString_Check(name
))
401 return class_repr(op
);
402 if (mod
== NULL
|| !PyString_Check(mod
)) {
406 m
= PyString_GET_SIZE(mod
);
407 n
= PyString_GET_SIZE(name
);
408 res
= PyString_FromStringAndSize((char *)NULL
, m
+1+n
);
410 char *s
= PyString_AS_STRING(res
);
411 memcpy(s
, PyString_AS_STRING(mod
), m
);
414 memcpy(s
, PyString_AS_STRING(name
), n
);
420 class_traverse(PyClassObject
*o
, visitproc visit
, void *arg
)
422 Py_VISIT(o
->cl_bases
);
423 Py_VISIT(o
->cl_dict
);
424 Py_VISIT(o
->cl_name
);
425 Py_VISIT(o
->cl_getattr
);
426 Py_VISIT(o
->cl_setattr
);
427 Py_VISIT(o
->cl_delattr
);
431 PyTypeObject PyClass_Type
= {
432 PyObject_HEAD_INIT(&PyType_Type
)
435 sizeof(PyClassObject
),
437 (destructor
)class_dealloc
, /* tp_dealloc */
442 (reprfunc
)class_repr
, /* tp_repr */
443 0, /* tp_as_number */
444 0, /* tp_as_sequence */
445 0, /* tp_as_mapping */
447 PyInstance_New
, /* tp_call */
448 (reprfunc
)class_str
, /* tp_str */
449 (getattrofunc
)class_getattr
, /* tp_getattro */
450 (setattrofunc
)class_setattr
, /* tp_setattro */
451 0, /* tp_as_buffer */
452 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
453 class_doc
, /* tp_doc */
454 (traverseproc
)class_traverse
, /* tp_traverse */
456 0, /* tp_richcompare */
457 0, /* tp_weaklistoffset */
465 0, /* tp_descr_get */
466 0, /* tp_descr_set */
467 0, /* tp_dictoffset */
470 class_new
, /* tp_new */
474 PyClass_IsSubclass(PyObject
*klass
, PyObject
*base
)
480 if (PyTuple_Check(base
)) {
481 n
= PyTuple_GET_SIZE(base
);
482 for (i
= 0; i
< n
; i
++) {
483 if (PyClass_IsSubclass(klass
, PyTuple_GET_ITEM(base
, i
)))
488 if (klass
== NULL
|| !PyClass_Check(klass
))
490 cp
= (PyClassObject
*)klass
;
491 n
= PyTuple_Size(cp
->cl_bases
);
492 for (i
= 0; i
< n
; i
++) {
493 if (PyClass_IsSubclass(PyTuple_GetItem(cp
->cl_bases
, i
), base
))
500 /* Instance objects */
503 PyInstance_NewRaw(PyObject
*klass
, PyObject
*dict
)
505 PyInstanceObject
*inst
;
507 if (!PyClass_Check(klass
)) {
508 PyErr_BadInternalCall();
517 if (!PyDict_Check(dict
)) {
518 PyErr_BadInternalCall();
523 inst
= PyObject_GC_New(PyInstanceObject
, &PyInstance_Type
);
528 inst
->in_weakreflist
= NULL
;
530 inst
->in_class
= (PyClassObject
*)klass
;
531 inst
->in_dict
= dict
;
532 _PyObject_GC_TRACK(inst
);
533 return (PyObject
*)inst
;
537 PyInstance_New(PyObject
*klass
, PyObject
*arg
, PyObject
*kw
)
539 register PyInstanceObject
*inst
;
541 static PyObject
*initstr
;
543 if (initstr
== NULL
) {
544 initstr
= PyString_InternFromString("__init__");
548 inst
= (PyInstanceObject
*) PyInstance_NewRaw(klass
, NULL
);
551 init
= instance_getattr2(inst
, initstr
);
553 if (PyErr_Occurred()) {
557 if ((arg
!= NULL
&& (!PyTuple_Check(arg
) ||
558 PyTuple_Size(arg
) != 0))
559 || (kw
!= NULL
&& (!PyDict_Check(kw
) ||
560 PyDict_Size(kw
) != 0))) {
561 PyErr_SetString(PyExc_TypeError
,
562 "this constructor takes no arguments");
568 PyObject
*res
= PyEval_CallObjectWithKeywords(init
, arg
, kw
);
575 if (res
!= Py_None
) {
576 PyErr_SetString(PyExc_TypeError
,
577 "__init__() should return None");
584 return (PyObject
*)inst
;
587 /* Instance methods */
589 PyDoc_STRVAR(instance_doc
,
590 "instance(class[, dict])\n\
592 Create an instance without calling its __init__() method.\n\
593 The class must be a classic class.\n\
594 If present, dict must be a dictionary or None.");
597 instance_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
600 PyObject
*dict
= Py_None
;
602 if (!PyArg_ParseTuple(args
, "O!|O:instance",
603 &PyClass_Type
, &klass
, &dict
))
608 else if (!PyDict_Check(dict
)) {
609 PyErr_SetString(PyExc_TypeError
,
610 "instance() second arg must be dictionary or None");
613 return PyInstance_NewRaw(klass
, dict
);
618 instance_dealloc(register PyInstanceObject
*inst
)
620 PyObject
*error_type
, *error_value
, *error_traceback
;
622 static PyObject
*delstr
;
624 _PyObject_GC_UNTRACK(inst
);
625 if (inst
->in_weakreflist
!= NULL
)
626 PyObject_ClearWeakRefs((PyObject
*) inst
);
628 /* Temporarily resurrect the object. */
629 assert(inst
->ob_type
== &PyInstance_Type
);
630 assert(inst
->ob_refcnt
== 0);
633 /* Save the current exception, if any. */
634 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
635 /* Execute __del__ method, if any. */
636 if (delstr
== NULL
) {
637 delstr
= PyString_InternFromString("__del__");
639 PyErr_WriteUnraisable((PyObject
*)inst
);
641 if (delstr
&& (del
= instance_getattr2(inst
, delstr
)) != NULL
) {
642 PyObject
*res
= PyEval_CallObject(del
, (PyObject
*)NULL
);
644 PyErr_WriteUnraisable(del
);
649 /* Restore the saved exception. */
650 PyErr_Restore(error_type
, error_value
, error_traceback
);
652 /* Undo the temporary resurrection; can't use DECREF here, it would
653 * cause a recursive call.
655 assert(inst
->ob_refcnt
> 0);
656 if (--inst
->ob_refcnt
== 0) {
658 /* New weakrefs could be created during the finalizer call.
659 If this occurs, clear them out without calling their
660 finalizers since they might rely on part of the object
661 being finalized that has already been destroyed. */
662 while (inst
->in_weakreflist
!= NULL
) {
663 _PyWeakref_ClearRef((PyWeakReference
*)
664 (inst
->in_weakreflist
));
667 Py_DECREF(inst
->in_class
);
668 Py_XDECREF(inst
->in_dict
);
669 PyObject_GC_Del(inst
);
672 Py_ssize_t refcnt
= inst
->ob_refcnt
;
673 /* __del__ resurrected it! Make it look like the original
674 * Py_DECREF never happened.
676 _Py_NewReference((PyObject
*)inst
);
677 inst
->ob_refcnt
= refcnt
;
678 _PyObject_GC_TRACK(inst
);
679 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
680 * we need to undo that. */
682 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
683 * object chain, so no more to do there.
684 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
685 * _Py_NewReference bumped tp_allocs: both of those need to be
689 --inst
->ob_type
->tp_frees
;
690 --inst
->ob_type
->tp_allocs
;
696 instance_getattr1(register PyInstanceObject
*inst
, PyObject
*name
)
698 register PyObject
*v
;
699 register char *sname
= PyString_AsString(name
);
700 if (sname
[0] == '_' && sname
[1] == '_') {
701 if (strcmp(sname
, "__dict__") == 0) {
702 if (PyEval_GetRestricted()) {
703 PyErr_SetString(PyExc_RuntimeError
,
704 "instance.__dict__ not accessible in restricted mode");
707 Py_INCREF(inst
->in_dict
);
708 return inst
->in_dict
;
710 if (strcmp(sname
, "__class__") == 0) {
711 Py_INCREF(inst
->in_class
);
712 return (PyObject
*)inst
->in_class
;
715 v
= instance_getattr2(inst
, name
);
716 if (v
== NULL
&& !PyErr_Occurred()) {
717 PyErr_Format(PyExc_AttributeError
,
718 "%.50s instance has no attribute '%.400s'",
719 PyString_AS_STRING(inst
->in_class
->cl_name
), sname
);
725 instance_getattr2(register PyInstanceObject
*inst
, PyObject
*name
)
727 register PyObject
*v
;
728 PyClassObject
*klass
;
731 v
= PyDict_GetItem(inst
->in_dict
, name
);
736 v
= class_lookup(inst
->in_class
, name
, &klass
);
739 f
= TP_DESCR_GET(v
->ob_type
);
741 PyObject
*w
= f(v
, (PyObject
*)inst
,
742 (PyObject
*)(inst
->in_class
));
751 instance_getattr(register PyInstanceObject
*inst
, PyObject
*name
)
753 register PyObject
*func
, *res
;
754 res
= instance_getattr1(inst
, name
);
755 if (res
== NULL
&& (func
= inst
->in_class
->cl_getattr
) != NULL
) {
757 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
760 args
= PyTuple_Pack(2, inst
, name
);
763 res
= PyEval_CallObject(func
, args
);
769 /* See classobject.h comments: this only does dict lookups, and is always
773 _PyInstance_Lookup(PyObject
*pinst
, PyObject
*name
)
776 PyClassObject
*klass
;
777 PyInstanceObject
*inst
; /* pinst cast to the right type */
779 assert(PyInstance_Check(pinst
));
780 inst
= (PyInstanceObject
*)pinst
;
782 assert(PyString_Check(name
));
784 v
= PyDict_GetItem(inst
->in_dict
, name
);
786 v
= class_lookup(inst
->in_class
, name
, &klass
);
791 instance_setattr1(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
794 int rv
= PyDict_DelItem(inst
->in_dict
, name
);
796 PyErr_Format(PyExc_AttributeError
,
797 "%.50s instance has no attribute '%.400s'",
798 PyString_AS_STRING(inst
->in_class
->cl_name
),
799 PyString_AS_STRING(name
));
803 return PyDict_SetItem(inst
->in_dict
, name
, v
);
807 instance_setattr(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
809 PyObject
*func
, *args
, *res
, *tmp
;
810 char *sname
= PyString_AsString(name
);
811 if (sname
[0] == '_' && sname
[1] == '_') {
812 Py_ssize_t n
= PyString_Size(name
);
813 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
814 if (strcmp(sname
, "__dict__") == 0) {
815 if (PyEval_GetRestricted()) {
816 PyErr_SetString(PyExc_RuntimeError
,
817 "__dict__ not accessible in restricted mode");
820 if (v
== NULL
|| !PyDict_Check(v
)) {
821 PyErr_SetString(PyExc_TypeError
,
822 "__dict__ must be set to a dictionary");
831 if (strcmp(sname
, "__class__") == 0) {
832 if (PyEval_GetRestricted()) {
833 PyErr_SetString(PyExc_RuntimeError
,
834 "__class__ not accessible in restricted mode");
837 if (v
== NULL
|| !PyClass_Check(v
)) {
838 PyErr_SetString(PyExc_TypeError
,
839 "__class__ must be set to a class");
842 tmp
= (PyObject
*)(inst
->in_class
);
844 inst
->in_class
= (PyClassObject
*)v
;
851 func
= inst
->in_class
->cl_delattr
;
853 func
= inst
->in_class
->cl_setattr
;
855 return instance_setattr1(inst
, name
, v
);
857 args
= PyTuple_Pack(2, inst
, name
);
859 args
= PyTuple_Pack(3, inst
, name
, v
);
862 res
= PyEval_CallObject(func
, args
);
871 instance_repr(PyInstanceObject
*inst
)
875 static PyObject
*reprstr
;
877 if (reprstr
== NULL
) {
878 reprstr
= PyString_InternFromString("__repr__");
882 func
= instance_getattr(inst
, reprstr
);
884 PyObject
*classname
, *mod
;
886 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
889 classname
= inst
->in_class
->cl_name
;
890 mod
= PyDict_GetItemString(inst
->in_class
->cl_dict
,
892 if (classname
!= NULL
&& PyString_Check(classname
))
893 cname
= PyString_AsString(classname
);
896 if (mod
== NULL
|| !PyString_Check(mod
))
897 return PyString_FromFormat("<?.%s instance at %p>",
900 return PyString_FromFormat("<%s.%s instance at %p>",
901 PyString_AsString(mod
),
904 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
910 instance_str(PyInstanceObject
*inst
)
914 static PyObject
*strstr
;
916 if (strstr
== NULL
) {
917 strstr
= PyString_InternFromString("__str__");
921 func
= instance_getattr(inst
, strstr
);
923 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
926 return instance_repr(inst
);
928 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
934 instance_hash(PyInstanceObject
*inst
)
939 static PyObject
*hashstr
, *eqstr
, *cmpstr
;
941 if (hashstr
== NULL
) {
942 hashstr
= PyString_InternFromString("__hash__");
946 func
= instance_getattr(inst
, hashstr
);
948 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
951 /* If there is no __eq__ and no __cmp__ method, we hash on the
952 address. If an __eq__ or __cmp__ method exists, there must
955 eqstr
= PyString_InternFromString("__eq__");
959 func
= instance_getattr(inst
, eqstr
);
961 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
964 if (cmpstr
== NULL
) {
965 cmpstr
= PyString_InternFromString("__cmp__");
969 func
= instance_getattr(inst
, cmpstr
);
971 if (!PyErr_ExceptionMatches(
972 PyExc_AttributeError
))
975 return _Py_HashPointer(inst
);
979 PyErr_SetString(PyExc_TypeError
, "unhashable instance");
982 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
986 if (PyInt_Check(res
) || PyLong_Check(res
))
987 /* This already converts a -1 result to -2. */
988 outcome
= res
->ob_type
->tp_hash(res
);
990 PyErr_SetString(PyExc_TypeError
,
991 "__hash__() should return an int");
999 instance_traverse(PyInstanceObject
*o
, visitproc visit
, void *arg
)
1001 Py_VISIT(o
->in_class
);
1002 Py_VISIT(o
->in_dict
);
1006 static PyObject
*getitemstr
, *setitemstr
, *delitemstr
, *lenstr
;
1007 static PyObject
*iterstr
, *nextstr
;
1010 instance_length(PyInstanceObject
*inst
)
1016 if (lenstr
== NULL
) {
1017 lenstr
= PyString_InternFromString("__len__");
1021 func
= instance_getattr(inst
, lenstr
);
1024 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1028 if (PyInt_Check(res
)) {
1029 outcome
= PyInt_AsSsize_t(res
);
1030 if (outcome
== -1 && PyErr_Occurred()) {
1034 #if SIZEOF_SIZE_T < SIZEOF_INT
1035 /* Overflow check -- range of PyInt is more than C int */
1036 if (outcome
!= (int)outcome
) {
1037 PyErr_SetString(PyExc_OverflowError
,
1038 "__len__() should return 0 <= outcome < 2**31");
1044 PyErr_SetString(PyExc_ValueError
,
1045 "__len__() should return >= 0");
1050 PyErr_SetString(PyExc_TypeError
,
1051 "__len__() should return an int");
1059 instance_subscript(PyInstanceObject
*inst
, PyObject
*key
)
1065 if (getitemstr
== NULL
) {
1066 getitemstr
= PyString_InternFromString("__getitem__");
1067 if (getitemstr
== NULL
)
1070 func
= instance_getattr(inst
, getitemstr
);
1073 arg
= PyTuple_Pack(1, key
);
1078 res
= PyEval_CallObject(func
, arg
);
1085 instance_ass_subscript(PyInstanceObject
*inst
, PyObject
*key
, PyObject
*value
)
1091 if (value
== NULL
) {
1092 if (delitemstr
== NULL
) {
1093 delitemstr
= PyString_InternFromString("__delitem__");
1094 if (delitemstr
== NULL
)
1097 func
= instance_getattr(inst
, delitemstr
);
1100 if (setitemstr
== NULL
) {
1101 setitemstr
= PyString_InternFromString("__setitem__");
1102 if (setitemstr
== NULL
)
1105 func
= instance_getattr(inst
, setitemstr
);
1110 arg
= PyTuple_Pack(1, key
);
1112 arg
= PyTuple_Pack(2, key
, value
);
1117 res
= PyEval_CallObject(func
, arg
);
1126 static PyMappingMethods instance_as_mapping
= {
1127 (lenfunc
)instance_length
, /* mp_length */
1128 (binaryfunc
)instance_subscript
, /* mp_subscript */
1129 (objobjargproc
)instance_ass_subscript
, /* mp_ass_subscript */
1133 instance_item(PyInstanceObject
*inst
, Py_ssize_t i
)
1135 PyObject
*func
, *res
;
1137 if (getitemstr
== NULL
) {
1138 getitemstr
= PyString_InternFromString("__getitem__");
1139 if (getitemstr
== NULL
)
1142 func
= instance_getattr(inst
, getitemstr
);
1145 res
= PyObject_CallFunction(func
, "n", i
);
1151 instance_slice(PyInstanceObject
*inst
, Py_ssize_t i
, Py_ssize_t j
)
1153 PyObject
*func
, *arg
, *res
;
1154 static PyObject
*getslicestr
;
1156 if (getslicestr
== NULL
) {
1157 getslicestr
= PyString_InternFromString("__getslice__");
1158 if (getslicestr
== NULL
)
1161 func
= instance_getattr(inst
, getslicestr
);
1164 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1168 if (getitemstr
== NULL
) {
1169 getitemstr
= PyString_InternFromString("__getitem__");
1170 if (getitemstr
== NULL
)
1173 func
= instance_getattr(inst
, getitemstr
);
1176 arg
= Py_BuildValue("(N)", _PySlice_FromIndices(i
, j
));
1178 arg
= Py_BuildValue("(nn)", i
, j
);
1184 res
= PyEval_CallObject(func
, arg
);
1191 instance_ass_item(PyInstanceObject
*inst
, Py_ssize_t i
, PyObject
*item
)
1193 PyObject
*func
, *arg
, *res
;
1196 if (delitemstr
== NULL
) {
1197 delitemstr
= PyString_InternFromString("__delitem__");
1198 if (delitemstr
== NULL
)
1201 func
= instance_getattr(inst
, delitemstr
);
1204 if (setitemstr
== NULL
) {
1205 setitemstr
= PyString_InternFromString("__setitem__");
1206 if (setitemstr
== NULL
)
1209 func
= instance_getattr(inst
, setitemstr
);
1214 arg
= PyInt_FromSsize_t(i
);
1216 arg
= Py_BuildValue("(nO)", i
, item
);
1221 res
= PyEval_CallObject(func
, arg
);
1231 instance_ass_slice(PyInstanceObject
*inst
, Py_ssize_t i
, Py_ssize_t j
, PyObject
*value
)
1233 PyObject
*func
, *arg
, *res
;
1234 static PyObject
*setslicestr
, *delslicestr
;
1236 if (value
== NULL
) {
1237 if (delslicestr
== NULL
) {
1239 PyString_InternFromString("__delslice__");
1240 if (delslicestr
== NULL
)
1243 func
= instance_getattr(inst
, delslicestr
);
1245 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1248 if (delitemstr
== NULL
) {
1250 PyString_InternFromString("__delitem__");
1251 if (delitemstr
== NULL
)
1254 func
= instance_getattr(inst
, delitemstr
);
1258 arg
= Py_BuildValue("(N)",
1259 _PySlice_FromIndices(i
, j
));
1261 arg
= Py_BuildValue("(nn)", i
, j
);
1264 if (setslicestr
== NULL
) {
1266 PyString_InternFromString("__setslice__");
1267 if (setslicestr
== NULL
)
1270 func
= instance_getattr(inst
, setslicestr
);
1272 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1275 if (setitemstr
== NULL
) {
1277 PyString_InternFromString("__setitem__");
1278 if (setitemstr
== NULL
)
1281 func
= instance_getattr(inst
, setitemstr
);
1285 arg
= Py_BuildValue("(NO)",
1286 _PySlice_FromIndices(i
, j
), value
);
1288 arg
= Py_BuildValue("(nnO)", i
, j
, value
);
1294 res
= PyEval_CallObject(func
, arg
);
1304 instance_contains(PyInstanceObject
*inst
, PyObject
*member
)
1306 static PyObject
*__contains__
;
1309 /* Try __contains__ first.
1310 * If that can't be done, try iterator-based searching.
1313 if(__contains__
== NULL
) {
1314 __contains__
= PyString_InternFromString("__contains__");
1315 if(__contains__
== NULL
)
1318 func
= instance_getattr(inst
, __contains__
);
1322 PyObject
*arg
= PyTuple_Pack(1, member
);
1327 res
= PyEval_CallObject(func
, arg
);
1332 ret
= PyObject_IsTrue(res
);
1337 /* Couldn't find __contains__. */
1338 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1340 /* Assume the failure was simply due to that there is no
1341 * __contains__ attribute, and try iterating instead.
1344 rc
= _PySequence_IterSearch((PyObject
*)inst
, member
,
1345 PY_ITERSEARCH_CONTAINS
);
1352 static PySequenceMethods
1353 instance_as_sequence
= {
1354 (lenfunc
)instance_length
, /* sq_length */
1357 (ssizeargfunc
)instance_item
, /* sq_item */
1358 (ssizessizeargfunc
)instance_slice
, /* sq_slice */
1359 (ssizeobjargproc
)instance_ass_item
, /* sq_ass_item */
1360 (ssizessizeobjargproc
)instance_ass_slice
,/* sq_ass_slice */
1361 (objobjproc
)instance_contains
, /* sq_contains */
1365 generic_unary_op(PyInstanceObject
*self
, PyObject
*methodname
)
1367 PyObject
*func
, *res
;
1369 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1371 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1377 generic_binary_op(PyObject
*v
, PyObject
*w
, char *opname
)
1381 PyObject
*func
= PyObject_GetAttrString(v
, opname
);
1383 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1386 Py_INCREF(Py_NotImplemented
);
1387 return Py_NotImplemented
;
1389 args
= PyTuple_Pack(1, w
);
1394 result
= PyEval_CallObject(func
, args
);
1401 static PyObject
*coerce_obj
;
1403 /* Try one half of a binary operator involving a class instance. */
1405 half_binop(PyObject
*v
, PyObject
*w
, char *opname
, binaryfunc thisfunc
,
1409 PyObject
*coercefunc
;
1410 PyObject
*coerced
= NULL
;
1414 if (!PyInstance_Check(v
)) {
1415 Py_INCREF(Py_NotImplemented
);
1416 return Py_NotImplemented
;
1419 if (coerce_obj
== NULL
) {
1420 coerce_obj
= PyString_InternFromString("__coerce__");
1421 if (coerce_obj
== NULL
)
1424 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1425 if (coercefunc
== NULL
) {
1426 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1429 return generic_binary_op(v
, w
, opname
);
1432 args
= PyTuple_Pack(1, w
);
1434 Py_DECREF(coercefunc
);
1437 coerced
= PyEval_CallObject(coercefunc
, args
);
1439 Py_DECREF(coercefunc
);
1440 if (coerced
== NULL
) {
1443 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1445 return generic_binary_op(v
, w
, opname
);
1447 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1449 PyErr_SetString(PyExc_TypeError
,
1450 "coercion should return None or 2-tuple");
1453 v1
= PyTuple_GetItem(coerced
, 0);
1454 w
= PyTuple_GetItem(coerced
, 1);
1455 if (v1
->ob_type
== v
->ob_type
&& PyInstance_Check(v
)) {
1456 /* prevent recursion if __coerce__ returns self as the first
1458 result
= generic_binary_op(v1
, w
, opname
);
1460 if (Py_EnterRecursiveCall(" after coercion"))
1463 result
= (thisfunc
)(w
, v1
);
1465 result
= (thisfunc
)(v1
, w
);
1466 Py_LeaveRecursiveCall();
1472 /* Implement a binary operator involving at least one class instance. */
1474 do_binop(PyObject
*v
, PyObject
*w
, char *opname
, char *ropname
,
1475 binaryfunc thisfunc
)
1477 PyObject
*result
= half_binop(v
, w
, opname
, thisfunc
, 0);
1478 if (result
== Py_NotImplemented
) {
1480 result
= half_binop(w
, v
, ropname
, thisfunc
, 1);
1486 do_binop_inplace(PyObject
*v
, PyObject
*w
, char *iopname
, char *opname
,
1487 char *ropname
, binaryfunc thisfunc
)
1489 PyObject
*result
= half_binop(v
, w
, iopname
, thisfunc
, 0);
1490 if (result
== Py_NotImplemented
) {
1492 result
= do_binop(v
, w
, opname
, ropname
, thisfunc
);
1498 instance_coerce(PyObject
**pv
, PyObject
**pw
)
1502 PyObject
*coercefunc
;
1506 if (coerce_obj
== NULL
) {
1507 coerce_obj
= PyString_InternFromString("__coerce__");
1508 if (coerce_obj
== NULL
)
1511 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1512 if (coercefunc
== NULL
) {
1513 /* No __coerce__ method */
1514 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1519 /* Has __coerce__ method: call it */
1520 args
= PyTuple_Pack(1, w
);
1524 coerced
= PyEval_CallObject(coercefunc
, args
);
1526 Py_DECREF(coercefunc
);
1527 if (coerced
== NULL
) {
1528 /* __coerce__ call raised an exception */
1531 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1532 /* __coerce__ says "I can't do it" */
1536 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1537 /* __coerce__ return value is malformed */
1539 PyErr_SetString(PyExc_TypeError
,
1540 "coercion should return None or 2-tuple");
1543 /* __coerce__ returned two new values */
1544 *pv
= PyTuple_GetItem(coerced
, 0);
1545 *pw
= PyTuple_GetItem(coerced
, 1);
1552 #define UNARY(funcname, methodname) \
1553 static PyObject *funcname(PyInstanceObject *self) { \
1554 static PyObject *o; \
1555 if (o == NULL) { o = PyString_InternFromString(methodname); \
1556 if (o == NULL) return NULL; } \
1557 return generic_unary_op(self, o); \
1560 /* unary function with a fallback */
1561 #define UNARY_FB(funcname, methodname, funcname_fb) \
1562 static PyObject *funcname(PyInstanceObject *self) { \
1563 static PyObject *o; \
1564 if (o == NULL) { o = PyString_InternFromString(methodname); \
1565 if (o == NULL) return NULL; } \
1566 if (PyObject_HasAttr((PyObject*)self, o)) \
1567 return generic_unary_op(self, o); \
1569 return funcname_fb(self); \
1572 #define BINARY(f, m, n) \
1573 static PyObject *f(PyObject *v, PyObject *w) { \
1574 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1577 #define BINARY_INPLACE(f, m, n) \
1578 static PyObject *f(PyObject *v, PyObject *w) { \
1579 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1583 UNARY(instance_neg
, "__neg__")
1584 UNARY(instance_pos
, "__pos__")
1585 UNARY(instance_abs
, "__abs__")
1587 BINARY(instance_or
, "or", PyNumber_Or
)
1588 BINARY(instance_and
, "and", PyNumber_And
)
1589 BINARY(instance_xor
, "xor", PyNumber_Xor
)
1590 BINARY(instance_lshift
, "lshift", PyNumber_Lshift
)
1591 BINARY(instance_rshift
, "rshift", PyNumber_Rshift
)
1592 BINARY(instance_add
, "add", PyNumber_Add
)
1593 BINARY(instance_sub
, "sub", PyNumber_Subtract
)
1594 BINARY(instance_mul
, "mul", PyNumber_Multiply
)
1595 BINARY(instance_div
, "div", PyNumber_Divide
)
1596 BINARY(instance_mod
, "mod", PyNumber_Remainder
)
1597 BINARY(instance_divmod
, "divmod", PyNumber_Divmod
)
1598 BINARY(instance_floordiv
, "floordiv", PyNumber_FloorDivide
)
1599 BINARY(instance_truediv
, "truediv", PyNumber_TrueDivide
)
1601 BINARY_INPLACE(instance_ior
, "or", PyNumber_InPlaceOr
)
1602 BINARY_INPLACE(instance_ixor
, "xor", PyNumber_InPlaceXor
)
1603 BINARY_INPLACE(instance_iand
, "and", PyNumber_InPlaceAnd
)
1604 BINARY_INPLACE(instance_ilshift
, "lshift", PyNumber_InPlaceLshift
)
1605 BINARY_INPLACE(instance_irshift
, "rshift", PyNumber_InPlaceRshift
)
1606 BINARY_INPLACE(instance_iadd
, "add", PyNumber_InPlaceAdd
)
1607 BINARY_INPLACE(instance_isub
, "sub", PyNumber_InPlaceSubtract
)
1608 BINARY_INPLACE(instance_imul
, "mul", PyNumber_InPlaceMultiply
)
1609 BINARY_INPLACE(instance_idiv
, "div", PyNumber_InPlaceDivide
)
1610 BINARY_INPLACE(instance_imod
, "mod", PyNumber_InPlaceRemainder
)
1611 BINARY_INPLACE(instance_ifloordiv
, "floordiv", PyNumber_InPlaceFloorDivide
)
1612 BINARY_INPLACE(instance_itruediv
, "truediv", PyNumber_InPlaceTrueDivide
)
1614 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1615 -2 for an exception;
1619 2 if this particular 3-way comparison is not implemented or undefined.
1622 half_cmp(PyObject
*v
, PyObject
*w
)
1624 static PyObject
*cmp_obj
;
1630 assert(PyInstance_Check(v
));
1632 if (cmp_obj
== NULL
) {
1633 cmp_obj
= PyString_InternFromString("__cmp__");
1634 if (cmp_obj
== NULL
)
1638 cmp_func
= PyObject_GetAttr(v
, cmp_obj
);
1639 if (cmp_func
== NULL
) {
1640 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1646 args
= PyTuple_Pack(1, w
);
1648 Py_DECREF(cmp_func
);
1652 result
= PyEval_CallObject(cmp_func
, args
);
1654 Py_DECREF(cmp_func
);
1659 if (result
== Py_NotImplemented
) {
1664 l
= PyInt_AsLong(result
);
1666 if (l
== -1 && PyErr_Occurred()) {
1667 PyErr_SetString(PyExc_TypeError
,
1668 "comparison did not return an int");
1672 return l
< 0 ? -1 : l
> 0 ? 1 : 0;
1675 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1676 We first try a coercion. Return:
1677 -2 for an exception;
1681 2 if this particular 3-way comparison is not implemented or undefined.
1682 THIS IS ONLY CALLED FROM object.c!
1685 instance_compare(PyObject
*v
, PyObject
*w
)
1689 c
= PyNumber_CoerceEx(&v
, &w
);
1693 /* If neither is now an instance, use regular comparison */
1694 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1695 c
= PyObject_Compare(v
, w
);
1698 if (PyErr_Occurred())
1700 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
1704 /* The coercion didn't do anything.
1705 Treat this the same as returning v and w unchanged. */
1710 if (PyInstance_Check(v
)) {
1718 if (PyInstance_Check(w
)) {
1734 instance_nonzero(PyInstanceObject
*self
)
1736 PyObject
*func
, *res
;
1738 static PyObject
*nonzerostr
;
1740 if (nonzerostr
== NULL
) {
1741 nonzerostr
= PyString_InternFromString("__nonzero__");
1742 if (nonzerostr
== NULL
)
1745 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1746 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1749 if (lenstr
== NULL
) {
1750 lenstr
= PyString_InternFromString("__len__");
1754 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1755 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1758 /* Fall back to the default behavior:
1759 all instances are nonzero */
1763 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1767 if (!PyInt_Check(res
)) {
1769 PyErr_SetString(PyExc_TypeError
,
1770 "__nonzero__ should return an int");
1773 outcome
= PyInt_AsLong(res
);
1776 PyErr_SetString(PyExc_ValueError
,
1777 "__nonzero__ should return >= 0");
1784 instance_index(PyInstanceObject
*self
)
1786 PyObject
*func
, *res
;
1787 static PyObject
*indexstr
= NULL
;
1789 if (indexstr
== NULL
) {
1790 indexstr
= PyString_InternFromString("__index__");
1791 if (indexstr
== NULL
)
1794 if ((func
= instance_getattr(self
, indexstr
)) == NULL
) {
1795 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1798 PyErr_SetString(PyExc_TypeError
,
1799 "object cannot be interpreted as an index");
1802 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1808 UNARY(instance_invert
, "__invert__")
1809 UNARY(_instance_trunc
, "__trunc__")
1812 instance_int(PyInstanceObject
*self
)
1814 PyObject
*truncated
;
1815 static PyObject
*int_name
;
1816 if (int_name
== NULL
) {
1817 int_name
= PyString_InternFromString("__int__");
1818 if (int_name
== NULL
)
1821 if (PyObject_HasAttr((PyObject
*)self
, int_name
))
1822 return generic_unary_op(self
, int_name
);
1824 truncated
= _instance_trunc(self
);
1825 /* __trunc__ is specified to return an Integral type, but
1826 int() needs to return an int. */
1827 return _PyNumber_ConvertIntegralToInt(
1829 "__trunc__ returned non-Integral (type %.200s)");
1832 UNARY_FB(instance_long
, "__long__", instance_int
)
1833 UNARY(instance_float
, "__float__")
1834 UNARY(instance_oct
, "__oct__")
1835 UNARY(instance_hex
, "__hex__")
1838 bin_power(PyObject
*v
, PyObject
*w
)
1840 return PyNumber_Power(v
, w
, Py_None
);
1843 /* This version is for ternary calls only (z != None) */
1845 instance_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1848 return do_binop(v
, w
, "__pow__", "__rpow__", bin_power
);
1855 /* XXX Doesn't do coercions... */
1856 func
= PyObject_GetAttrString(v
, "__pow__");
1859 args
= PyTuple_Pack(2, w
, z
);
1864 result
= PyEval_CallObject(func
, args
);
1872 bin_inplace_power(PyObject
*v
, PyObject
*w
)
1874 return PyNumber_InPlacePower(v
, w
, Py_None
);
1879 instance_ipow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1882 return do_binop_inplace(v
, w
, "__ipow__", "__pow__",
1883 "__rpow__", bin_inplace_power
);
1886 /* XXX Doesn't do coercions... */
1891 func
= PyObject_GetAttrString(v
, "__ipow__");
1893 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1896 return instance_pow(v
, w
, z
);
1898 args
= PyTuple_Pack(2, w
, z
);
1903 result
= PyEval_CallObject(func
, args
);
1911 /* Map rich comparison operators to their __xx__ namesakes */
1913 static PyObject
**name_op
= NULL
;
1919 char *_name_op
[] = {
1928 name_op
= (PyObject
**)malloc(sizeof(PyObject
*) * NAME_OPS
);
1929 if (name_op
== NULL
)
1931 for (i
= 0; i
< NAME_OPS
; ++i
) {
1932 name_op
[i
] = PyString_InternFromString(_name_op
[i
]);
1933 if (name_op
[i
] == NULL
)
1940 half_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1946 assert(PyInstance_Check(v
));
1948 if (name_op
== NULL
) {
1949 if (init_name_op() < 0)
1952 /* If the instance doesn't define an __getattr__ method, use
1953 instance_getattr2 directly because it will not set an
1954 exception on failure. */
1955 if (((PyInstanceObject
*)v
)->in_class
->cl_getattr
== NULL
)
1956 method
= instance_getattr2((PyInstanceObject
*)v
,
1959 method
= PyObject_GetAttr(v
, name_op
[op
]);
1960 if (method
== NULL
) {
1961 if (PyErr_Occurred()) {
1962 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1966 res
= Py_NotImplemented
;
1971 args
= PyTuple_Pack(1, w
);
1977 res
= PyEval_CallObject(method
, args
);
1985 instance_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1989 if (PyInstance_Check(v
)) {
1990 res
= half_richcompare(v
, w
, op
);
1991 if (res
!= Py_NotImplemented
)
1996 if (PyInstance_Check(w
)) {
1997 res
= half_richcompare(w
, v
, _Py_SwappedOp
[op
]);
1998 if (res
!= Py_NotImplemented
)
2003 Py_INCREF(Py_NotImplemented
);
2004 return Py_NotImplemented
;
2008 /* Get the iterator */
2010 instance_getiter(PyInstanceObject
*self
)
2014 if (iterstr
== NULL
) {
2015 iterstr
= PyString_InternFromString("__iter__");
2016 if (iterstr
== NULL
)
2019 if (getitemstr
== NULL
) {
2020 getitemstr
= PyString_InternFromString("__getitem__");
2021 if (getitemstr
== NULL
)
2025 if ((func
= instance_getattr(self
, iterstr
)) != NULL
) {
2026 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
2028 if (res
!= NULL
&& !PyIter_Check(res
)) {
2029 PyErr_Format(PyExc_TypeError
,
2030 "__iter__ returned non-iterator "
2032 res
->ob_type
->tp_name
);
2038 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2041 if ((func
= instance_getattr(self
, getitemstr
)) == NULL
) {
2042 PyErr_SetString(PyExc_TypeError
,
2043 "iteration over non-sequence");
2047 return PySeqIter_New((PyObject
*)self
);
2051 /* Call the iterator's next */
2053 instance_iternext(PyInstanceObject
*self
)
2057 if (nextstr
== NULL
) {
2058 nextstr
= PyString_InternFromString("next");
2059 if (nextstr
== NULL
)
2063 if ((func
= instance_getattr(self
, nextstr
)) != NULL
) {
2064 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
2069 if (PyErr_ExceptionMatches(PyExc_StopIteration
)) {
2075 PyErr_SetString(PyExc_TypeError
, "instance has no next() method");
2080 instance_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2082 PyObject
*res
, *call
= PyObject_GetAttrString(func
, "__call__");
2084 PyInstanceObject
*inst
= (PyInstanceObject
*) func
;
2085 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2088 PyErr_Format(PyExc_AttributeError
,
2089 "%.200s instance has no __call__ method",
2090 PyString_AsString(inst
->in_class
->cl_name
));
2093 /* We must check and increment the recursion depth here. Scenario:
2096 A.__call__ = A() # that's right
2098 a() # infinite recursion
2099 This bounces between instance_call() and PyObject_Call() without
2100 ever hitting eval_frame() (which has the main recursion check). */
2101 if (Py_EnterRecursiveCall(" in __call__")) {
2105 res
= PyObject_Call(call
, arg
, kw
);
2106 Py_LeaveRecursiveCall();
2113 static PyNumberMethods instance_as_number
= {
2114 instance_add
, /* nb_add */
2115 instance_sub
, /* nb_subtract */
2116 instance_mul
, /* nb_multiply */
2117 instance_div
, /* nb_divide */
2118 instance_mod
, /* nb_remainder */
2119 instance_divmod
, /* nb_divmod */
2120 instance_pow
, /* nb_power */
2121 (unaryfunc
)instance_neg
, /* nb_negative */
2122 (unaryfunc
)instance_pos
, /* nb_positive */
2123 (unaryfunc
)instance_abs
, /* nb_absolute */
2124 (inquiry
)instance_nonzero
, /* nb_nonzero */
2125 (unaryfunc
)instance_invert
, /* nb_invert */
2126 instance_lshift
, /* nb_lshift */
2127 instance_rshift
, /* nb_rshift */
2128 instance_and
, /* nb_and */
2129 instance_xor
, /* nb_xor */
2130 instance_or
, /* nb_or */
2131 instance_coerce
, /* nb_coerce */
2132 (unaryfunc
)instance_int
, /* nb_int */
2133 (unaryfunc
)instance_long
, /* nb_long */
2134 (unaryfunc
)instance_float
, /* nb_float */
2135 (unaryfunc
)instance_oct
, /* nb_oct */
2136 (unaryfunc
)instance_hex
, /* nb_hex */
2137 instance_iadd
, /* nb_inplace_add */
2138 instance_isub
, /* nb_inplace_subtract */
2139 instance_imul
, /* nb_inplace_multiply */
2140 instance_idiv
, /* nb_inplace_divide */
2141 instance_imod
, /* nb_inplace_remainder */
2142 instance_ipow
, /* nb_inplace_power */
2143 instance_ilshift
, /* nb_inplace_lshift */
2144 instance_irshift
, /* nb_inplace_rshift */
2145 instance_iand
, /* nb_inplace_and */
2146 instance_ixor
, /* nb_inplace_xor */
2147 instance_ior
, /* nb_inplace_or */
2148 instance_floordiv
, /* nb_floor_divide */
2149 instance_truediv
, /* nb_true_divide */
2150 instance_ifloordiv
, /* nb_inplace_floor_divide */
2151 instance_itruediv
, /* nb_inplace_true_divide */
2152 (unaryfunc
)instance_index
, /* nb_index */
2155 PyTypeObject PyInstance_Type
= {
2156 PyObject_HEAD_INIT(&PyType_Type
)
2159 sizeof(PyInstanceObject
),
2161 (destructor
)instance_dealloc
, /* tp_dealloc */
2165 instance_compare
, /* tp_compare */
2166 (reprfunc
)instance_repr
, /* tp_repr */
2167 &instance_as_number
, /* tp_as_number */
2168 &instance_as_sequence
, /* tp_as_sequence */
2169 &instance_as_mapping
, /* tp_as_mapping */
2170 (hashfunc
)instance_hash
, /* tp_hash */
2171 instance_call
, /* tp_call */
2172 (reprfunc
)instance_str
, /* tp_str */
2173 (getattrofunc
)instance_getattr
, /* tp_getattro */
2174 (setattrofunc
)instance_setattr
, /* tp_setattro */
2175 0, /* tp_as_buffer */
2176 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
,/*tp_flags*/
2177 instance_doc
, /* tp_doc */
2178 (traverseproc
)instance_traverse
, /* tp_traverse */
2180 instance_richcompare
, /* tp_richcompare */
2181 offsetof(PyInstanceObject
, in_weakreflist
), /* tp_weaklistoffset */
2182 (getiterfunc
)instance_getiter
, /* tp_iter */
2183 (iternextfunc
)instance_iternext
, /* tp_iternext */
2189 0, /* tp_descr_get */
2190 0, /* tp_descr_set */
2191 0, /* tp_dictoffset */
2194 instance_new
, /* tp_new */
2198 /* Instance method objects are used for two purposes:
2199 (a) as bound instance methods (returned by instancename.methodname)
2200 (b) as unbound methods (returned by ClassName.methodname)
2201 In case (b), im_self is NULL
2205 PyMethod_New(PyObject
*func
, PyObject
*self
, PyObject
*klass
)
2207 register PyMethodObject
*im
;
2208 if (!PyCallable_Check(func
)) {
2209 PyErr_BadInternalCall();
2214 free_list
= (PyMethodObject
*)(im
->im_self
);
2215 PyObject_INIT(im
, &PyMethod_Type
);
2219 im
= PyObject_GC_New(PyMethodObject
, &PyMethod_Type
);
2223 im
->im_weakreflist
= NULL
;
2229 im
->im_class
= klass
;
2230 _PyObject_GC_TRACK(im
);
2231 return (PyObject
*)im
;
2234 /* Descriptors for PyMethod attributes */
2236 /* im_class, im_func and im_self are stored in the PyMethod object */
2238 #define OFF(x) offsetof(PyMethodObject, x)
2240 static PyMemberDef instancemethod_memberlist
[] = {
2241 {"im_class", T_OBJECT
, OFF(im_class
), READONLY
|RESTRICTED
,
2242 "the class associated with a method"},
2243 {"im_func", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2244 "the function (or other callable) implementing a method"},
2245 {"__func__", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2246 "the function (or other callable) implementing a method"},
2247 {"im_self", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2248 "the instance to which a method is bound; None for unbound methods"},
2249 {"__self__", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2250 "the instance to which a method is bound; None for unbound methods"},
2251 {NULL
} /* Sentinel */
2254 /* Christian Tismer argued convincingly that method attributes should
2255 (nearly) always override function attributes.
2256 The one exception is __doc__; there's a default __doc__ which
2257 should only be used for the class, not for instances */
2260 instancemethod_get_doc(PyMethodObject
*im
, void *context
)
2262 static PyObject
*docstr
;
2263 if (docstr
== NULL
) {
2264 docstr
= PyString_InternFromString("__doc__");
2268 return PyObject_GetAttr(im
->im_func
, docstr
);
2271 static PyGetSetDef instancemethod_getset
[] = {
2272 {"__doc__", (getter
)instancemethod_get_doc
, NULL
, NULL
},
2277 instancemethod_getattro(PyObject
*obj
, PyObject
*name
)
2279 PyMethodObject
*im
= (PyMethodObject
*)obj
;
2280 PyTypeObject
*tp
= obj
->ob_type
;
2281 PyObject
*descr
= NULL
;
2283 if (PyType_HasFeature(tp
, Py_TPFLAGS_HAVE_CLASS
)) {
2284 if (tp
->tp_dict
== NULL
) {
2285 if (PyType_Ready(tp
) < 0)
2288 descr
= _PyType_Lookup(tp
, name
);
2291 if (descr
!= NULL
) {
2292 descrgetfunc f
= TP_DESCR_GET(descr
->ob_type
);
2294 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2301 return PyObject_GetAttr(im
->im_func
, name
);
2304 PyDoc_STRVAR(instancemethod_doc
,
2305 "instancemethod(function, instance, class)\n\
2307 Create an instance method object.");
2310 instancemethod_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
2314 PyObject
*classObj
= NULL
;
2316 if (!_PyArg_NoKeywords("instancemethod", kw
))
2318 if (!PyArg_UnpackTuple(args
, "instancemethod", 2, 3,
2319 &func
, &self
, &classObj
))
2321 if (!PyCallable_Check(func
)) {
2322 PyErr_SetString(PyExc_TypeError
,
2323 "first argument must be callable");
2326 if (self
== Py_None
)
2328 if (self
== NULL
&& classObj
== NULL
) {
2329 PyErr_SetString(PyExc_TypeError
,
2330 "unbound methods must have non-NULL im_class");
2334 return PyMethod_New(func
, self
, classObj
);
2338 instancemethod_dealloc(register PyMethodObject
*im
)
2340 _PyObject_GC_UNTRACK(im
);
2341 if (im
->im_weakreflist
!= NULL
)
2342 PyObject_ClearWeakRefs((PyObject
*)im
);
2343 Py_DECREF(im
->im_func
);
2344 Py_XDECREF(im
->im_self
);
2345 Py_XDECREF(im
->im_class
);
2346 if (numfree
< PyMethod_MAXFREELIST
) {
2347 im
->im_self
= (PyObject
*)free_list
;
2352 PyObject_GC_Del(im
);
2357 instancemethod_compare(PyMethodObject
*a
, PyMethodObject
*b
)
2360 cmp
= PyObject_Compare(a
->im_func
, b
->im_func
);
2364 if (a
->im_self
== b
->im_self
)
2366 if (a
->im_self
== NULL
|| b
->im_self
== NULL
)
2367 return (a
->im_self
< b
->im_self
) ? -1 : 1;
2369 return PyObject_Compare(a
->im_self
, b
->im_self
);
2373 instancemethod_repr(PyMethodObject
*a
)
2375 PyObject
*self
= a
->im_self
;
2376 PyObject
*func
= a
->im_func
;
2377 PyObject
*klass
= a
->im_class
;
2378 PyObject
*funcname
= NULL
, *klassname
= NULL
, *result
= NULL
;
2379 char *sfuncname
= "?", *sklassname
= "?";
2381 funcname
= PyObject_GetAttrString(func
, "__name__");
2382 if (funcname
== NULL
) {
2383 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2387 else if (!PyString_Check(funcname
)) {
2388 Py_DECREF(funcname
);
2392 sfuncname
= PyString_AS_STRING(funcname
);
2396 klassname
= PyObject_GetAttrString(klass
, "__name__");
2397 if (klassname
== NULL
) {
2398 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2402 else if (!PyString_Check(klassname
)) {
2403 Py_DECREF(klassname
);
2407 sklassname
= PyString_AS_STRING(klassname
);
2410 result
= PyString_FromFormat("<unbound method %s.%s>",
2411 sklassname
, sfuncname
);
2413 /* XXX Shouldn't use repr() here! */
2414 PyObject
*selfrepr
= PyObject_Repr(self
);
2415 if (selfrepr
== NULL
)
2417 if (!PyString_Check(selfrepr
)) {
2418 Py_DECREF(selfrepr
);
2421 result
= PyString_FromFormat("<bound method %s.%s of %s>",
2422 sklassname
, sfuncname
,
2423 PyString_AS_STRING(selfrepr
));
2424 Py_DECREF(selfrepr
);
2427 Py_XDECREF(funcname
);
2428 Py_XDECREF(klassname
);
2433 instancemethod_hash(PyMethodObject
*a
)
2436 if (a
->im_self
== NULL
)
2437 x
= PyObject_Hash(Py_None
);
2439 x
= PyObject_Hash(a
->im_self
);
2442 y
= PyObject_Hash(a
->im_func
);
2452 instancemethod_traverse(PyMethodObject
*im
, visitproc visit
, void *arg
)
2454 Py_VISIT(im
->im_func
);
2455 Py_VISIT(im
->im_self
);
2456 Py_VISIT(im
->im_class
);
2461 getclassname(PyObject
*klass
, char *buf
, int bufsize
)
2465 assert(bufsize
> 1);
2466 strcpy(buf
, "?"); /* Default outcome */
2469 name
= PyObject_GetAttrString(klass
, "__name__");
2471 /* This function cannot return an exception */
2475 if (PyString_Check(name
)) {
2476 strncpy(buf
, PyString_AS_STRING(name
), bufsize
);
2477 buf
[bufsize
-1] = '\0';
2483 getinstclassname(PyObject
*inst
, char *buf
, int bufsize
)
2488 assert(bufsize
> 0 && (size_t)bufsize
> strlen("nothing"));
2489 strcpy(buf
, "nothing");
2493 klass
= PyObject_GetAttrString(inst
, "__class__");
2494 if (klass
== NULL
) {
2495 /* This function cannot return an exception */
2497 klass
= (PyObject
*)(inst
->ob_type
);
2500 getclassname(klass
, buf
, bufsize
);
2505 instancemethod_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2507 PyObject
*self
= PyMethod_GET_SELF(func
);
2508 PyObject
*klass
= PyMethod_GET_CLASS(func
);
2511 func
= PyMethod_GET_FUNCTION(func
);
2513 /* Unbound methods must be called with an instance of
2514 the class (or a derived class) as first argument */
2516 if (PyTuple_Size(arg
) >= 1)
2517 self
= PyTuple_GET_ITEM(arg
, 0);
2521 ok
= PyObject_IsInstance(self
, klass
);
2528 getclassname(klass
, clsbuf
, sizeof(clsbuf
));
2529 getinstclassname(self
, instbuf
, sizeof(instbuf
));
2530 PyErr_Format(PyExc_TypeError
,
2531 "unbound method %s%s must be called with "
2532 "%s instance as first argument "
2533 "(got %s%s instead)",
2534 PyEval_GetFuncName(func
),
2535 PyEval_GetFuncDesc(func
),
2538 self
== NULL
? "" : " instance");
2544 Py_ssize_t argcount
= PyTuple_Size(arg
);
2545 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2550 PyTuple_SET_ITEM(newarg
, 0, self
);
2551 for (i
= 0; i
< argcount
; i
++) {
2552 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2554 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2558 result
= PyObject_Call((PyObject
*)func
, arg
, kw
);
2564 instancemethod_descr_get(PyObject
*meth
, PyObject
*obj
, PyObject
*cls
)
2566 /* Don't rebind an already bound method, or an unbound method
2567 of a class that's not a base class of cls. */
2569 if (PyMethod_GET_SELF(meth
) != NULL
) {
2574 /* No, it is an unbound method */
2575 if (PyMethod_GET_CLASS(meth
) != NULL
&& cls
!= NULL
) {
2576 /* Do subclass test. If it fails, return meth unchanged. */
2577 int ok
= PyObject_IsSubclass(cls
, PyMethod_GET_CLASS(meth
));
2585 /* Bind it to obj */
2586 return PyMethod_New(PyMethod_GET_FUNCTION(meth
), obj
, cls
);
2589 PyTypeObject PyMethod_Type
= {
2590 PyObject_HEAD_INIT(&PyType_Type
)
2593 sizeof(PyMethodObject
),
2595 (destructor
)instancemethod_dealloc
, /* tp_dealloc */
2599 (cmpfunc
)instancemethod_compare
, /* tp_compare */
2600 (reprfunc
)instancemethod_repr
, /* tp_repr */
2601 0, /* tp_as_number */
2602 0, /* tp_as_sequence */
2603 0, /* tp_as_mapping */
2604 (hashfunc
)instancemethod_hash
, /* tp_hash */
2605 instancemethod_call
, /* tp_call */
2607 instancemethod_getattro
, /* tp_getattro */
2608 PyObject_GenericSetAttr
, /* tp_setattro */
2609 0, /* tp_as_buffer */
2610 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
2611 instancemethod_doc
, /* tp_doc */
2612 (traverseproc
)instancemethod_traverse
, /* tp_traverse */
2614 0, /* tp_richcompare */
2615 offsetof(PyMethodObject
, im_weakreflist
), /* tp_weaklistoffset */
2617 0, /* tp_iternext */
2619 instancemethod_memberlist
, /* tp_members */
2620 instancemethod_getset
, /* tp_getset */
2623 instancemethod_descr_get
, /* tp_descr_get */
2624 0, /* tp_descr_set */
2625 0, /* tp_dictoffset */
2628 instancemethod_new
, /* tp_new */
2631 /* Clear out the free list */
2634 PyMethod_ClearFreeList(void)
2636 int freelist_size
= numfree
;
2639 PyMethodObject
*im
= free_list
;
2640 free_list
= (PyMethodObject
*)(im
->im_self
);
2641 PyObject_GC_Del(im
);
2644 assert(numfree
== 0);
2645 return freelist_size
;
2651 (void)PyMethod_ClearFreeList();