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
));
1179 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
1180 "use __getitem__", 1) < 0) {
1184 arg
= Py_BuildValue("(nn)", i
, j
);
1191 res
= PyEval_CallObject(func
, arg
);
1198 instance_ass_item(PyInstanceObject
*inst
, Py_ssize_t i
, PyObject
*item
)
1200 PyObject
*func
, *arg
, *res
;
1203 if (delitemstr
== NULL
) {
1204 delitemstr
= PyString_InternFromString("__delitem__");
1205 if (delitemstr
== NULL
)
1208 func
= instance_getattr(inst
, delitemstr
);
1211 if (setitemstr
== NULL
) {
1212 setitemstr
= PyString_InternFromString("__setitem__");
1213 if (setitemstr
== NULL
)
1216 func
= instance_getattr(inst
, setitemstr
);
1221 arg
= PyInt_FromSsize_t(i
);
1223 arg
= Py_BuildValue("(nO)", i
, item
);
1228 res
= PyEval_CallObject(func
, arg
);
1238 instance_ass_slice(PyInstanceObject
*inst
, Py_ssize_t i
, Py_ssize_t j
, PyObject
*value
)
1240 PyObject
*func
, *arg
, *res
;
1241 static PyObject
*setslicestr
, *delslicestr
;
1243 if (value
== NULL
) {
1244 if (delslicestr
== NULL
) {
1246 PyString_InternFromString("__delslice__");
1247 if (delslicestr
== NULL
)
1250 func
= instance_getattr(inst
, delslicestr
);
1252 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1255 if (delitemstr
== NULL
) {
1257 PyString_InternFromString("__delitem__");
1258 if (delitemstr
== NULL
)
1261 func
= instance_getattr(inst
, delitemstr
);
1265 arg
= Py_BuildValue("(N)",
1266 _PySlice_FromIndices(i
, j
));
1269 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
1270 "removed; use __delitem__", 1) < 0) {
1274 arg
= Py_BuildValue("(nn)", i
, j
);
1278 if (setslicestr
== NULL
) {
1280 PyString_InternFromString("__setslice__");
1281 if (setslicestr
== NULL
)
1284 func
= instance_getattr(inst
, setslicestr
);
1286 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1289 if (setitemstr
== NULL
) {
1291 PyString_InternFromString("__setitem__");
1292 if (setitemstr
== NULL
)
1295 func
= instance_getattr(inst
, setitemstr
);
1299 arg
= Py_BuildValue("(NO)",
1300 _PySlice_FromIndices(i
, j
), value
);
1303 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
1304 "removed; use __setitem__", 1) < 0) {
1308 arg
= Py_BuildValue("(nnO)", i
, j
, value
);
1315 res
= PyEval_CallObject(func
, arg
);
1325 instance_contains(PyInstanceObject
*inst
, PyObject
*member
)
1327 static PyObject
*__contains__
;
1330 /* Try __contains__ first.
1331 * If that can't be done, try iterator-based searching.
1334 if(__contains__
== NULL
) {
1335 __contains__
= PyString_InternFromString("__contains__");
1336 if(__contains__
== NULL
)
1339 func
= instance_getattr(inst
, __contains__
);
1343 PyObject
*arg
= PyTuple_Pack(1, member
);
1348 res
= PyEval_CallObject(func
, arg
);
1353 ret
= PyObject_IsTrue(res
);
1358 /* Couldn't find __contains__. */
1359 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1361 /* Assume the failure was simply due to that there is no
1362 * __contains__ attribute, and try iterating instead.
1365 rc
= _PySequence_IterSearch((PyObject
*)inst
, member
,
1366 PY_ITERSEARCH_CONTAINS
);
1373 static PySequenceMethods
1374 instance_as_sequence
= {
1375 (lenfunc
)instance_length
, /* sq_length */
1378 (ssizeargfunc
)instance_item
, /* sq_item */
1379 (ssizessizeargfunc
)instance_slice
, /* sq_slice */
1380 (ssizeobjargproc
)instance_ass_item
, /* sq_ass_item */
1381 (ssizessizeobjargproc
)instance_ass_slice
,/* sq_ass_slice */
1382 (objobjproc
)instance_contains
, /* sq_contains */
1386 generic_unary_op(PyInstanceObject
*self
, PyObject
*methodname
)
1388 PyObject
*func
, *res
;
1390 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1392 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1398 generic_binary_op(PyObject
*v
, PyObject
*w
, char *opname
)
1402 PyObject
*func
= PyObject_GetAttrString(v
, opname
);
1404 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1407 Py_INCREF(Py_NotImplemented
);
1408 return Py_NotImplemented
;
1410 args
= PyTuple_Pack(1, w
);
1415 result
= PyEval_CallObject(func
, args
);
1422 static PyObject
*coerce_obj
;
1424 /* Try one half of a binary operator involving a class instance. */
1426 half_binop(PyObject
*v
, PyObject
*w
, char *opname
, binaryfunc thisfunc
,
1430 PyObject
*coercefunc
;
1431 PyObject
*coerced
= NULL
;
1435 if (!PyInstance_Check(v
)) {
1436 Py_INCREF(Py_NotImplemented
);
1437 return Py_NotImplemented
;
1440 if (coerce_obj
== NULL
) {
1441 coerce_obj
= PyString_InternFromString("__coerce__");
1442 if (coerce_obj
== NULL
)
1445 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1446 if (coercefunc
== NULL
) {
1447 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1450 return generic_binary_op(v
, w
, opname
);
1453 args
= PyTuple_Pack(1, w
);
1455 Py_DECREF(coercefunc
);
1458 coerced
= PyEval_CallObject(coercefunc
, args
);
1460 Py_DECREF(coercefunc
);
1461 if (coerced
== NULL
) {
1464 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1466 return generic_binary_op(v
, w
, opname
);
1468 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1470 PyErr_SetString(PyExc_TypeError
,
1471 "coercion should return None or 2-tuple");
1474 v1
= PyTuple_GetItem(coerced
, 0);
1475 w
= PyTuple_GetItem(coerced
, 1);
1476 if (v1
->ob_type
== v
->ob_type
&& PyInstance_Check(v
)) {
1477 /* prevent recursion if __coerce__ returns self as the first
1479 result
= generic_binary_op(v1
, w
, opname
);
1481 if (Py_EnterRecursiveCall(" after coercion"))
1484 result
= (thisfunc
)(w
, v1
);
1486 result
= (thisfunc
)(v1
, w
);
1487 Py_LeaveRecursiveCall();
1493 /* Implement a binary operator involving at least one class instance. */
1495 do_binop(PyObject
*v
, PyObject
*w
, char *opname
, char *ropname
,
1496 binaryfunc thisfunc
)
1498 PyObject
*result
= half_binop(v
, w
, opname
, thisfunc
, 0);
1499 if (result
== Py_NotImplemented
) {
1501 result
= half_binop(w
, v
, ropname
, thisfunc
, 1);
1507 do_binop_inplace(PyObject
*v
, PyObject
*w
, char *iopname
, char *opname
,
1508 char *ropname
, binaryfunc thisfunc
)
1510 PyObject
*result
= half_binop(v
, w
, iopname
, thisfunc
, 0);
1511 if (result
== Py_NotImplemented
) {
1513 result
= do_binop(v
, w
, opname
, ropname
, thisfunc
);
1519 instance_coerce(PyObject
**pv
, PyObject
**pw
)
1523 PyObject
*coercefunc
;
1527 if (coerce_obj
== NULL
) {
1528 coerce_obj
= PyString_InternFromString("__coerce__");
1529 if (coerce_obj
== NULL
)
1532 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1533 if (coercefunc
== NULL
) {
1534 /* No __coerce__ method */
1535 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1540 /* Has __coerce__ method: call it */
1541 args
= PyTuple_Pack(1, w
);
1545 coerced
= PyEval_CallObject(coercefunc
, args
);
1547 Py_DECREF(coercefunc
);
1548 if (coerced
== NULL
) {
1549 /* __coerce__ call raised an exception */
1552 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1553 /* __coerce__ says "I can't do it" */
1557 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1558 /* __coerce__ return value is malformed */
1560 PyErr_SetString(PyExc_TypeError
,
1561 "coercion should return None or 2-tuple");
1564 /* __coerce__ returned two new values */
1565 *pv
= PyTuple_GetItem(coerced
, 0);
1566 *pw
= PyTuple_GetItem(coerced
, 1);
1573 #define UNARY(funcname, methodname) \
1574 static PyObject *funcname(PyInstanceObject *self) { \
1575 static PyObject *o; \
1576 if (o == NULL) { o = PyString_InternFromString(methodname); \
1577 if (o == NULL) return NULL; } \
1578 return generic_unary_op(self, o); \
1581 /* unary function with a fallback */
1582 #define UNARY_FB(funcname, methodname, funcname_fb) \
1583 static PyObject *funcname(PyInstanceObject *self) { \
1584 static PyObject *o; \
1585 if (o == NULL) { o = PyString_InternFromString(methodname); \
1586 if (o == NULL) return NULL; } \
1587 if (PyObject_HasAttr((PyObject*)self, o)) \
1588 return generic_unary_op(self, o); \
1590 return funcname_fb(self); \
1593 #define BINARY(f, m, n) \
1594 static PyObject *f(PyObject *v, PyObject *w) { \
1595 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1598 #define BINARY_INPLACE(f, m, n) \
1599 static PyObject *f(PyObject *v, PyObject *w) { \
1600 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1604 UNARY(instance_neg
, "__neg__")
1605 UNARY(instance_pos
, "__pos__")
1606 UNARY(instance_abs
, "__abs__")
1608 BINARY(instance_or
, "or", PyNumber_Or
)
1609 BINARY(instance_and
, "and", PyNumber_And
)
1610 BINARY(instance_xor
, "xor", PyNumber_Xor
)
1611 BINARY(instance_lshift
, "lshift", PyNumber_Lshift
)
1612 BINARY(instance_rshift
, "rshift", PyNumber_Rshift
)
1613 BINARY(instance_add
, "add", PyNumber_Add
)
1614 BINARY(instance_sub
, "sub", PyNumber_Subtract
)
1615 BINARY(instance_mul
, "mul", PyNumber_Multiply
)
1616 BINARY(instance_div
, "div", PyNumber_Divide
)
1617 BINARY(instance_mod
, "mod", PyNumber_Remainder
)
1618 BINARY(instance_divmod
, "divmod", PyNumber_Divmod
)
1619 BINARY(instance_floordiv
, "floordiv", PyNumber_FloorDivide
)
1620 BINARY(instance_truediv
, "truediv", PyNumber_TrueDivide
)
1622 BINARY_INPLACE(instance_ior
, "or", PyNumber_InPlaceOr
)
1623 BINARY_INPLACE(instance_ixor
, "xor", PyNumber_InPlaceXor
)
1624 BINARY_INPLACE(instance_iand
, "and", PyNumber_InPlaceAnd
)
1625 BINARY_INPLACE(instance_ilshift
, "lshift", PyNumber_InPlaceLshift
)
1626 BINARY_INPLACE(instance_irshift
, "rshift", PyNumber_InPlaceRshift
)
1627 BINARY_INPLACE(instance_iadd
, "add", PyNumber_InPlaceAdd
)
1628 BINARY_INPLACE(instance_isub
, "sub", PyNumber_InPlaceSubtract
)
1629 BINARY_INPLACE(instance_imul
, "mul", PyNumber_InPlaceMultiply
)
1630 BINARY_INPLACE(instance_idiv
, "div", PyNumber_InPlaceDivide
)
1631 BINARY_INPLACE(instance_imod
, "mod", PyNumber_InPlaceRemainder
)
1632 BINARY_INPLACE(instance_ifloordiv
, "floordiv", PyNumber_InPlaceFloorDivide
)
1633 BINARY_INPLACE(instance_itruediv
, "truediv", PyNumber_InPlaceTrueDivide
)
1635 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1636 -2 for an exception;
1640 2 if this particular 3-way comparison is not implemented or undefined.
1643 half_cmp(PyObject
*v
, PyObject
*w
)
1645 static PyObject
*cmp_obj
;
1651 assert(PyInstance_Check(v
));
1653 if (cmp_obj
== NULL
) {
1654 cmp_obj
= PyString_InternFromString("__cmp__");
1655 if (cmp_obj
== NULL
)
1659 cmp_func
= PyObject_GetAttr(v
, cmp_obj
);
1660 if (cmp_func
== NULL
) {
1661 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1667 args
= PyTuple_Pack(1, w
);
1669 Py_DECREF(cmp_func
);
1673 result
= PyEval_CallObject(cmp_func
, args
);
1675 Py_DECREF(cmp_func
);
1680 if (result
== Py_NotImplemented
) {
1685 l
= PyInt_AsLong(result
);
1687 if (l
== -1 && PyErr_Occurred()) {
1688 PyErr_SetString(PyExc_TypeError
,
1689 "comparison did not return an int");
1693 return l
< 0 ? -1 : l
> 0 ? 1 : 0;
1696 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1697 We first try a coercion. Return:
1698 -2 for an exception;
1702 2 if this particular 3-way comparison is not implemented or undefined.
1703 THIS IS ONLY CALLED FROM object.c!
1706 instance_compare(PyObject
*v
, PyObject
*w
)
1710 c
= PyNumber_CoerceEx(&v
, &w
);
1714 /* If neither is now an instance, use regular comparison */
1715 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1716 c
= PyObject_Compare(v
, w
);
1719 if (PyErr_Occurred())
1721 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
1725 /* The coercion didn't do anything.
1726 Treat this the same as returning v and w unchanged. */
1731 if (PyInstance_Check(v
)) {
1739 if (PyInstance_Check(w
)) {
1755 instance_nonzero(PyInstanceObject
*self
)
1757 PyObject
*func
, *res
;
1759 static PyObject
*nonzerostr
;
1761 if (nonzerostr
== NULL
) {
1762 nonzerostr
= PyString_InternFromString("__nonzero__");
1763 if (nonzerostr
== NULL
)
1766 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1767 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1770 if (lenstr
== NULL
) {
1771 lenstr
= PyString_InternFromString("__len__");
1775 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1776 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1779 /* Fall back to the default behavior:
1780 all instances are nonzero */
1784 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1788 if (!PyInt_Check(res
)) {
1790 PyErr_SetString(PyExc_TypeError
,
1791 "__nonzero__ should return an int");
1794 outcome
= PyInt_AsLong(res
);
1797 PyErr_SetString(PyExc_ValueError
,
1798 "__nonzero__ should return >= 0");
1805 instance_index(PyInstanceObject
*self
)
1807 PyObject
*func
, *res
;
1808 static PyObject
*indexstr
= NULL
;
1810 if (indexstr
== NULL
) {
1811 indexstr
= PyString_InternFromString("__index__");
1812 if (indexstr
== NULL
)
1815 if ((func
= instance_getattr(self
, indexstr
)) == NULL
) {
1816 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1819 PyErr_SetString(PyExc_TypeError
,
1820 "object cannot be interpreted as an index");
1823 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1829 UNARY(instance_invert
, "__invert__")
1830 UNARY(_instance_trunc
, "__trunc__")
1833 instance_int(PyInstanceObject
*self
)
1835 PyObject
*truncated
;
1836 static PyObject
*int_name
;
1837 if (int_name
== NULL
) {
1838 int_name
= PyString_InternFromString("__int__");
1839 if (int_name
== NULL
)
1842 if (PyObject_HasAttr((PyObject
*)self
, int_name
))
1843 return generic_unary_op(self
, int_name
);
1845 truncated
= _instance_trunc(self
);
1846 /* __trunc__ is specified to return an Integral type, but
1847 int() needs to return an int. */
1848 return _PyNumber_ConvertIntegralToInt(
1850 "__trunc__ returned non-Integral (type %.200s)");
1853 UNARY_FB(instance_long
, "__long__", instance_int
)
1854 UNARY(instance_float
, "__float__")
1855 UNARY(instance_oct
, "__oct__")
1856 UNARY(instance_hex
, "__hex__")
1859 bin_power(PyObject
*v
, PyObject
*w
)
1861 return PyNumber_Power(v
, w
, Py_None
);
1864 /* This version is for ternary calls only (z != None) */
1866 instance_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1869 return do_binop(v
, w
, "__pow__", "__rpow__", bin_power
);
1876 /* XXX Doesn't do coercions... */
1877 func
= PyObject_GetAttrString(v
, "__pow__");
1880 args
= PyTuple_Pack(2, w
, z
);
1885 result
= PyEval_CallObject(func
, args
);
1893 bin_inplace_power(PyObject
*v
, PyObject
*w
)
1895 return PyNumber_InPlacePower(v
, w
, Py_None
);
1900 instance_ipow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1903 return do_binop_inplace(v
, w
, "__ipow__", "__pow__",
1904 "__rpow__", bin_inplace_power
);
1907 /* XXX Doesn't do coercions... */
1912 func
= PyObject_GetAttrString(v
, "__ipow__");
1914 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1917 return instance_pow(v
, w
, z
);
1919 args
= PyTuple_Pack(2, w
, z
);
1924 result
= PyEval_CallObject(func
, args
);
1932 /* Map rich comparison operators to their __xx__ namesakes */
1934 static PyObject
**name_op
= NULL
;
1940 char *_name_op
[] = {
1949 name_op
= (PyObject
**)malloc(sizeof(PyObject
*) * NAME_OPS
);
1950 if (name_op
== NULL
)
1952 for (i
= 0; i
< NAME_OPS
; ++i
) {
1953 name_op
[i
] = PyString_InternFromString(_name_op
[i
]);
1954 if (name_op
[i
] == NULL
)
1961 half_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1967 assert(PyInstance_Check(v
));
1969 if (name_op
== NULL
) {
1970 if (init_name_op() < 0)
1973 /* If the instance doesn't define an __getattr__ method, use
1974 instance_getattr2 directly because it will not set an
1975 exception on failure. */
1976 if (((PyInstanceObject
*)v
)->in_class
->cl_getattr
== NULL
)
1977 method
= instance_getattr2((PyInstanceObject
*)v
,
1980 method
= PyObject_GetAttr(v
, name_op
[op
]);
1981 if (method
== NULL
) {
1982 if (PyErr_Occurred()) {
1983 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1987 res
= Py_NotImplemented
;
1992 args
= PyTuple_Pack(1, w
);
1998 res
= PyEval_CallObject(method
, args
);
2006 instance_richcompare(PyObject
*v
, PyObject
*w
, int op
)
2010 if (PyInstance_Check(v
)) {
2011 res
= half_richcompare(v
, w
, op
);
2012 if (res
!= Py_NotImplemented
)
2017 if (PyInstance_Check(w
)) {
2018 res
= half_richcompare(w
, v
, _Py_SwappedOp
[op
]);
2019 if (res
!= Py_NotImplemented
)
2024 Py_INCREF(Py_NotImplemented
);
2025 return Py_NotImplemented
;
2029 /* Get the iterator */
2031 instance_getiter(PyInstanceObject
*self
)
2035 if (iterstr
== NULL
) {
2036 iterstr
= PyString_InternFromString("__iter__");
2037 if (iterstr
== NULL
)
2040 if (getitemstr
== NULL
) {
2041 getitemstr
= PyString_InternFromString("__getitem__");
2042 if (getitemstr
== NULL
)
2046 if ((func
= instance_getattr(self
, iterstr
)) != NULL
) {
2047 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
2049 if (res
!= NULL
&& !PyIter_Check(res
)) {
2050 PyErr_Format(PyExc_TypeError
,
2051 "__iter__ returned non-iterator "
2053 res
->ob_type
->tp_name
);
2059 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2062 if ((func
= instance_getattr(self
, getitemstr
)) == NULL
) {
2063 PyErr_SetString(PyExc_TypeError
,
2064 "iteration over non-sequence");
2068 return PySeqIter_New((PyObject
*)self
);
2072 /* Call the iterator's next */
2074 instance_iternext(PyInstanceObject
*self
)
2078 if (nextstr
== NULL
) {
2079 nextstr
= PyString_InternFromString("next");
2080 if (nextstr
== NULL
)
2084 if ((func
= instance_getattr(self
, nextstr
)) != NULL
) {
2085 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
2090 if (PyErr_ExceptionMatches(PyExc_StopIteration
)) {
2096 PyErr_SetString(PyExc_TypeError
, "instance has no next() method");
2101 instance_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2103 PyObject
*res
, *call
= PyObject_GetAttrString(func
, "__call__");
2105 PyInstanceObject
*inst
= (PyInstanceObject
*) func
;
2106 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2109 PyErr_Format(PyExc_AttributeError
,
2110 "%.200s instance has no __call__ method",
2111 PyString_AsString(inst
->in_class
->cl_name
));
2114 /* We must check and increment the recursion depth here. Scenario:
2117 A.__call__ = A() # that's right
2119 a() # infinite recursion
2120 This bounces between instance_call() and PyObject_Call() without
2121 ever hitting eval_frame() (which has the main recursion check). */
2122 if (Py_EnterRecursiveCall(" in __call__")) {
2126 res
= PyObject_Call(call
, arg
, kw
);
2127 Py_LeaveRecursiveCall();
2134 static PyNumberMethods instance_as_number
= {
2135 instance_add
, /* nb_add */
2136 instance_sub
, /* nb_subtract */
2137 instance_mul
, /* nb_multiply */
2138 instance_div
, /* nb_divide */
2139 instance_mod
, /* nb_remainder */
2140 instance_divmod
, /* nb_divmod */
2141 instance_pow
, /* nb_power */
2142 (unaryfunc
)instance_neg
, /* nb_negative */
2143 (unaryfunc
)instance_pos
, /* nb_positive */
2144 (unaryfunc
)instance_abs
, /* nb_absolute */
2145 (inquiry
)instance_nonzero
, /* nb_nonzero */
2146 (unaryfunc
)instance_invert
, /* nb_invert */
2147 instance_lshift
, /* nb_lshift */
2148 instance_rshift
, /* nb_rshift */
2149 instance_and
, /* nb_and */
2150 instance_xor
, /* nb_xor */
2151 instance_or
, /* nb_or */
2152 instance_coerce
, /* nb_coerce */
2153 (unaryfunc
)instance_int
, /* nb_int */
2154 (unaryfunc
)instance_long
, /* nb_long */
2155 (unaryfunc
)instance_float
, /* nb_float */
2156 (unaryfunc
)instance_oct
, /* nb_oct */
2157 (unaryfunc
)instance_hex
, /* nb_hex */
2158 instance_iadd
, /* nb_inplace_add */
2159 instance_isub
, /* nb_inplace_subtract */
2160 instance_imul
, /* nb_inplace_multiply */
2161 instance_idiv
, /* nb_inplace_divide */
2162 instance_imod
, /* nb_inplace_remainder */
2163 instance_ipow
, /* nb_inplace_power */
2164 instance_ilshift
, /* nb_inplace_lshift */
2165 instance_irshift
, /* nb_inplace_rshift */
2166 instance_iand
, /* nb_inplace_and */
2167 instance_ixor
, /* nb_inplace_xor */
2168 instance_ior
, /* nb_inplace_or */
2169 instance_floordiv
, /* nb_floor_divide */
2170 instance_truediv
, /* nb_true_divide */
2171 instance_ifloordiv
, /* nb_inplace_floor_divide */
2172 instance_itruediv
, /* nb_inplace_true_divide */
2173 (unaryfunc
)instance_index
, /* nb_index */
2176 PyTypeObject PyInstance_Type
= {
2177 PyObject_HEAD_INIT(&PyType_Type
)
2180 sizeof(PyInstanceObject
),
2182 (destructor
)instance_dealloc
, /* tp_dealloc */
2186 instance_compare
, /* tp_compare */
2187 (reprfunc
)instance_repr
, /* tp_repr */
2188 &instance_as_number
, /* tp_as_number */
2189 &instance_as_sequence
, /* tp_as_sequence */
2190 &instance_as_mapping
, /* tp_as_mapping */
2191 (hashfunc
)instance_hash
, /* tp_hash */
2192 instance_call
, /* tp_call */
2193 (reprfunc
)instance_str
, /* tp_str */
2194 (getattrofunc
)instance_getattr
, /* tp_getattro */
2195 (setattrofunc
)instance_setattr
, /* tp_setattro */
2196 0, /* tp_as_buffer */
2197 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
,/*tp_flags*/
2198 instance_doc
, /* tp_doc */
2199 (traverseproc
)instance_traverse
, /* tp_traverse */
2201 instance_richcompare
, /* tp_richcompare */
2202 offsetof(PyInstanceObject
, in_weakreflist
), /* tp_weaklistoffset */
2203 (getiterfunc
)instance_getiter
, /* tp_iter */
2204 (iternextfunc
)instance_iternext
, /* tp_iternext */
2210 0, /* tp_descr_get */
2211 0, /* tp_descr_set */
2212 0, /* tp_dictoffset */
2215 instance_new
, /* tp_new */
2219 /* Instance method objects are used for two purposes:
2220 (a) as bound instance methods (returned by instancename.methodname)
2221 (b) as unbound methods (returned by ClassName.methodname)
2222 In case (b), im_self is NULL
2226 PyMethod_New(PyObject
*func
, PyObject
*self
, PyObject
*klass
)
2228 register PyMethodObject
*im
;
2231 free_list
= (PyMethodObject
*)(im
->im_self
);
2232 PyObject_INIT(im
, &PyMethod_Type
);
2236 im
= PyObject_GC_New(PyMethodObject
, &PyMethod_Type
);
2240 im
->im_weakreflist
= NULL
;
2246 im
->im_class
= klass
;
2247 _PyObject_GC_TRACK(im
);
2248 return (PyObject
*)im
;
2251 /* Descriptors for PyMethod attributes */
2253 /* im_class, im_func and im_self are stored in the PyMethod object */
2255 #define OFF(x) offsetof(PyMethodObject, x)
2257 static PyMemberDef instancemethod_memberlist
[] = {
2258 {"im_class", T_OBJECT
, OFF(im_class
), READONLY
|RESTRICTED
,
2259 "the class associated with a method"},
2260 {"im_func", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2261 "the function (or other callable) implementing a method"},
2262 {"__func__", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2263 "the function (or other callable) implementing a method"},
2264 {"im_self", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2265 "the instance to which a method is bound; None for unbound methods"},
2266 {"__self__", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2267 "the instance to which a method is bound; None for unbound methods"},
2268 {NULL
} /* Sentinel */
2271 /* Christian Tismer argued convincingly that method attributes should
2272 (nearly) always override function attributes.
2273 The one exception is __doc__; there's a default __doc__ which
2274 should only be used for the class, not for instances */
2277 instancemethod_get_doc(PyMethodObject
*im
, void *context
)
2279 static PyObject
*docstr
;
2280 if (docstr
== NULL
) {
2281 docstr
= PyString_InternFromString("__doc__");
2285 return PyObject_GetAttr(im
->im_func
, docstr
);
2288 static PyGetSetDef instancemethod_getset
[] = {
2289 {"__doc__", (getter
)instancemethod_get_doc
, NULL
, NULL
},
2294 instancemethod_getattro(PyObject
*obj
, PyObject
*name
)
2296 PyMethodObject
*im
= (PyMethodObject
*)obj
;
2297 PyTypeObject
*tp
= obj
->ob_type
;
2298 PyObject
*descr
= NULL
;
2300 if (PyType_HasFeature(tp
, Py_TPFLAGS_HAVE_CLASS
)) {
2301 if (tp
->tp_dict
== NULL
) {
2302 if (PyType_Ready(tp
) < 0)
2305 descr
= _PyType_Lookup(tp
, name
);
2308 if (descr
!= NULL
) {
2309 descrgetfunc f
= TP_DESCR_GET(descr
->ob_type
);
2311 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2318 return PyObject_GetAttr(im
->im_func
, name
);
2321 PyDoc_STRVAR(instancemethod_doc
,
2322 "instancemethod(function, instance, class)\n\
2324 Create an instance method object.");
2327 instancemethod_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
2331 PyObject
*classObj
= NULL
;
2333 if (!_PyArg_NoKeywords("instancemethod", kw
))
2335 if (!PyArg_UnpackTuple(args
, "instancemethod", 2, 3,
2336 &func
, &self
, &classObj
))
2338 if (!PyCallable_Check(func
)) {
2339 PyErr_SetString(PyExc_TypeError
,
2340 "first argument must be callable");
2343 if (self
== Py_None
)
2345 if (self
== NULL
&& classObj
== NULL
) {
2346 PyErr_SetString(PyExc_TypeError
,
2347 "unbound methods must have non-NULL im_class");
2351 return PyMethod_New(func
, self
, classObj
);
2355 instancemethod_dealloc(register PyMethodObject
*im
)
2357 _PyObject_GC_UNTRACK(im
);
2358 if (im
->im_weakreflist
!= NULL
)
2359 PyObject_ClearWeakRefs((PyObject
*)im
);
2360 Py_DECREF(im
->im_func
);
2361 Py_XDECREF(im
->im_self
);
2362 Py_XDECREF(im
->im_class
);
2363 if (numfree
< PyMethod_MAXFREELIST
) {
2364 im
->im_self
= (PyObject
*)free_list
;
2369 PyObject_GC_Del(im
);
2374 instancemethod_compare(PyMethodObject
*a
, PyMethodObject
*b
)
2377 cmp
= PyObject_Compare(a
->im_func
, b
->im_func
);
2381 if (a
->im_self
== b
->im_self
)
2383 if (a
->im_self
== NULL
|| b
->im_self
== NULL
)
2384 return (a
->im_self
< b
->im_self
) ? -1 : 1;
2386 return PyObject_Compare(a
->im_self
, b
->im_self
);
2390 instancemethod_repr(PyMethodObject
*a
)
2392 PyObject
*self
= a
->im_self
;
2393 PyObject
*func
= a
->im_func
;
2394 PyObject
*klass
= a
->im_class
;
2395 PyObject
*funcname
= NULL
, *klassname
= NULL
, *result
= NULL
;
2396 char *sfuncname
= "?", *sklassname
= "?";
2398 funcname
= PyObject_GetAttrString(func
, "__name__");
2399 if (funcname
== NULL
) {
2400 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2404 else if (!PyString_Check(funcname
)) {
2405 Py_DECREF(funcname
);
2409 sfuncname
= PyString_AS_STRING(funcname
);
2413 klassname
= PyObject_GetAttrString(klass
, "__name__");
2414 if (klassname
== NULL
) {
2415 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2419 else if (!PyString_Check(klassname
)) {
2420 Py_DECREF(klassname
);
2424 sklassname
= PyString_AS_STRING(klassname
);
2427 result
= PyString_FromFormat("<unbound method %s.%s>",
2428 sklassname
, sfuncname
);
2430 /* XXX Shouldn't use repr() here! */
2431 PyObject
*selfrepr
= PyObject_Repr(self
);
2432 if (selfrepr
== NULL
)
2434 if (!PyString_Check(selfrepr
)) {
2435 Py_DECREF(selfrepr
);
2438 result
= PyString_FromFormat("<bound method %s.%s of %s>",
2439 sklassname
, sfuncname
,
2440 PyString_AS_STRING(selfrepr
));
2441 Py_DECREF(selfrepr
);
2444 Py_XDECREF(funcname
);
2445 Py_XDECREF(klassname
);
2450 instancemethod_hash(PyMethodObject
*a
)
2453 if (a
->im_self
== NULL
)
2454 x
= PyObject_Hash(Py_None
);
2456 x
= PyObject_Hash(a
->im_self
);
2459 y
= PyObject_Hash(a
->im_func
);
2469 instancemethod_traverse(PyMethodObject
*im
, visitproc visit
, void *arg
)
2471 Py_VISIT(im
->im_func
);
2472 Py_VISIT(im
->im_self
);
2473 Py_VISIT(im
->im_class
);
2478 getclassname(PyObject
*klass
, char *buf
, int bufsize
)
2482 assert(bufsize
> 1);
2483 strcpy(buf
, "?"); /* Default outcome */
2486 name
= PyObject_GetAttrString(klass
, "__name__");
2488 /* This function cannot return an exception */
2492 if (PyString_Check(name
)) {
2493 strncpy(buf
, PyString_AS_STRING(name
), bufsize
);
2494 buf
[bufsize
-1] = '\0';
2500 getinstclassname(PyObject
*inst
, char *buf
, int bufsize
)
2505 assert(bufsize
> 0 && (size_t)bufsize
> strlen("nothing"));
2506 strcpy(buf
, "nothing");
2510 klass
= PyObject_GetAttrString(inst
, "__class__");
2511 if (klass
== NULL
) {
2512 /* This function cannot return an exception */
2514 klass
= (PyObject
*)(inst
->ob_type
);
2517 getclassname(klass
, buf
, bufsize
);
2522 instancemethod_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2524 PyObject
*self
= PyMethod_GET_SELF(func
);
2525 PyObject
*klass
= PyMethod_GET_CLASS(func
);
2528 func
= PyMethod_GET_FUNCTION(func
);
2530 /* Unbound methods must be called with an instance of
2531 the class (or a derived class) as first argument */
2533 if (PyTuple_Size(arg
) >= 1)
2534 self
= PyTuple_GET_ITEM(arg
, 0);
2538 ok
= PyObject_IsInstance(self
, klass
);
2545 getclassname(klass
, clsbuf
, sizeof(clsbuf
));
2546 getinstclassname(self
, instbuf
, sizeof(instbuf
));
2547 PyErr_Format(PyExc_TypeError
,
2548 "unbound method %s%s must be called with "
2549 "%s instance as first argument "
2550 "(got %s%s instead)",
2551 PyEval_GetFuncName(func
),
2552 PyEval_GetFuncDesc(func
),
2555 self
== NULL
? "" : " instance");
2561 Py_ssize_t argcount
= PyTuple_Size(arg
);
2562 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2567 PyTuple_SET_ITEM(newarg
, 0, self
);
2568 for (i
= 0; i
< argcount
; i
++) {
2569 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2571 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2575 result
= PyObject_Call((PyObject
*)func
, arg
, kw
);
2581 instancemethod_descr_get(PyObject
*meth
, PyObject
*obj
, PyObject
*cls
)
2583 /* Don't rebind an already bound method, or an unbound method
2584 of a class that's not a base class of cls. */
2586 if (PyMethod_GET_SELF(meth
) != NULL
) {
2591 /* No, it is an unbound method */
2592 if (PyMethod_GET_CLASS(meth
) != NULL
&& cls
!= NULL
) {
2593 /* Do subclass test. If it fails, return meth unchanged. */
2594 int ok
= PyObject_IsSubclass(cls
, PyMethod_GET_CLASS(meth
));
2602 /* Bind it to obj */
2603 return PyMethod_New(PyMethod_GET_FUNCTION(meth
), obj
, cls
);
2606 PyTypeObject PyMethod_Type
= {
2607 PyObject_HEAD_INIT(&PyType_Type
)
2610 sizeof(PyMethodObject
),
2612 (destructor
)instancemethod_dealloc
, /* tp_dealloc */
2616 (cmpfunc
)instancemethod_compare
, /* tp_compare */
2617 (reprfunc
)instancemethod_repr
, /* tp_repr */
2618 0, /* tp_as_number */
2619 0, /* tp_as_sequence */
2620 0, /* tp_as_mapping */
2621 (hashfunc
)instancemethod_hash
, /* tp_hash */
2622 instancemethod_call
, /* tp_call */
2624 instancemethod_getattro
, /* tp_getattro */
2625 PyObject_GenericSetAttr
, /* tp_setattro */
2626 0, /* tp_as_buffer */
2627 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
2628 instancemethod_doc
, /* tp_doc */
2629 (traverseproc
)instancemethod_traverse
, /* tp_traverse */
2631 0, /* tp_richcompare */
2632 offsetof(PyMethodObject
, im_weakreflist
), /* tp_weaklistoffset */
2634 0, /* tp_iternext */
2636 instancemethod_memberlist
, /* tp_members */
2637 instancemethod_getset
, /* tp_getset */
2640 instancemethod_descr_get
, /* tp_descr_get */
2641 0, /* tp_descr_set */
2642 0, /* tp_dictoffset */
2645 instancemethod_new
, /* tp_new */
2648 /* Clear out the free list */
2651 PyMethod_ClearFreeList(void)
2653 int freelist_size
= numfree
;
2656 PyMethodObject
*im
= free_list
;
2657 free_list
= (PyMethodObject
*)(im
->im_self
);
2658 PyObject_GC_Del(im
);
2661 assert(numfree
== 0);
2662 return freelist_size
;
2668 (void)PyMethod_ClearFreeList();