2 /* Class object implementation */
5 #include "structmember.h"
7 /* Free list for method objects to save 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
;
126 op
->cl_weakreflist
= NULL
;
128 op
->cl_getattr
= class_lookup(op
, getattrstr
, &dummy
);
129 op
->cl_setattr
= class_lookup(op
, setattrstr
, &dummy
);
130 op
->cl_delattr
= class_lookup(op
, delattrstr
, &dummy
);
131 Py_XINCREF(op
->cl_getattr
);
132 Py_XINCREF(op
->cl_setattr
);
133 Py_XINCREF(op
->cl_delattr
);
134 _PyObject_GC_TRACK(op
);
135 return (PyObject
*) op
;
139 PyMethod_Function(PyObject
*im
)
141 if (!PyMethod_Check(im
)) {
142 PyErr_BadInternalCall();
145 return ((PyMethodObject
*)im
)->im_func
;
149 PyMethod_Self(PyObject
*im
)
151 if (!PyMethod_Check(im
)) {
152 PyErr_BadInternalCall();
155 return ((PyMethodObject
*)im
)->im_self
;
159 PyMethod_Class(PyObject
*im
)
161 if (!PyMethod_Check(im
)) {
162 PyErr_BadInternalCall();
165 return ((PyMethodObject
*)im
)->im_class
;
168 PyDoc_STRVAR(class_doc
,
169 "classobj(name, bases, dict)\n\
171 Create a class object. The name must be a string; the second argument\n\
172 a tuple of classes, and the third a dictionary.");
175 class_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
177 PyObject
*name
, *bases
, *dict
;
178 static char *kwlist
[] = {"name", "bases", "dict", 0};
180 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "SOO", kwlist
,
181 &name
, &bases
, &dict
))
183 return PyClass_New(bases
, dict
, name
);
189 class_dealloc(PyClassObject
*op
)
191 _PyObject_GC_UNTRACK(op
);
192 if (op
->cl_weakreflist
!= NULL
)
193 PyObject_ClearWeakRefs((PyObject
*) op
);
194 Py_DECREF(op
->cl_bases
);
195 Py_DECREF(op
->cl_dict
);
196 Py_XDECREF(op
->cl_name
);
197 Py_XDECREF(op
->cl_getattr
);
198 Py_XDECREF(op
->cl_setattr
);
199 Py_XDECREF(op
->cl_delattr
);
204 class_lookup(PyClassObject
*cp
, PyObject
*name
, PyClassObject
**pclass
)
207 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
212 n
= PyTuple_Size(cp
->cl_bases
);
213 for (i
= 0; i
< n
; i
++) {
214 /* XXX What if one of the bases is not a class? */
215 PyObject
*v
= class_lookup(
217 PyTuple_GetItem(cp
->cl_bases
, i
), name
, pclass
);
225 class_getattr(register PyClassObject
*op
, PyObject
*name
)
227 register PyObject
*v
;
228 register char *sname
;
229 PyClassObject
*klass
;
232 if (!PyString_Check(name
)) {
233 PyErr_SetString(PyExc_TypeError
, "attribute name must be a string");
237 sname
= PyString_AsString(name
);
238 if (sname
[0] == '_' && sname
[1] == '_') {
239 if (strcmp(sname
, "__dict__") == 0) {
240 if (PyEval_GetRestricted()) {
241 PyErr_SetString(PyExc_RuntimeError
,
242 "class.__dict__ not accessible in restricted mode");
245 Py_INCREF(op
->cl_dict
);
248 if (strcmp(sname
, "__bases__") == 0) {
249 Py_INCREF(op
->cl_bases
);
252 if (strcmp(sname
, "__name__") == 0) {
253 if (op
->cl_name
== NULL
)
261 v
= class_lookup(op
, name
, &klass
);
263 PyErr_Format(PyExc_AttributeError
,
264 "class %.50s has no attribute '%.400s'",
265 PyString_AS_STRING(op
->cl_name
), sname
);
268 f
= TP_DESCR_GET(v
->ob_type
);
272 v
= f(v
, (PyObject
*)NULL
, (PyObject
*)op
);
277 set_slot(PyObject
**slot
, PyObject
*v
)
279 PyObject
*temp
= *slot
;
286 set_attr_slots(PyClassObject
*c
)
288 PyClassObject
*dummy
;
290 set_slot(&c
->cl_getattr
, class_lookup(c
, getattrstr
, &dummy
));
291 set_slot(&c
->cl_setattr
, class_lookup(c
, setattrstr
, &dummy
));
292 set_slot(&c
->cl_delattr
, class_lookup(c
, delattrstr
, &dummy
));
296 set_dict(PyClassObject
*c
, PyObject
*v
)
298 if (v
== NULL
|| !PyDict_Check(v
))
299 return "__dict__ must be a dictionary object";
300 set_slot(&c
->cl_dict
, v
);
306 set_bases(PyClassObject
*c
, PyObject
*v
)
310 if (v
== NULL
|| !PyTuple_Check(v
))
311 return "__bases__ must be a tuple object";
313 for (i
= 0; i
< n
; i
++) {
314 PyObject
*x
= PyTuple_GET_ITEM(v
, i
);
315 if (!PyClass_Check(x
))
316 return "__bases__ items must be classes";
317 if (PyClass_IsSubclass(x
, (PyObject
*)c
))
318 return "a __bases__ item causes an inheritance cycle";
320 set_slot(&c
->cl_bases
, v
);
326 set_name(PyClassObject
*c
, PyObject
*v
)
328 if (v
== NULL
|| !PyString_Check(v
))
329 return "__name__ must be a string object";
330 if (strlen(PyString_AS_STRING(v
)) != (size_t)PyString_GET_SIZE(v
))
331 return "__name__ must not contain null bytes";
332 set_slot(&c
->cl_name
, v
);
337 class_setattr(PyClassObject
*op
, PyObject
*name
, PyObject
*v
)
340 if (PyEval_GetRestricted()) {
341 PyErr_SetString(PyExc_RuntimeError
,
342 "classes are read-only in restricted mode");
345 if (!PyString_Check(name
)) {
346 PyErr_SetString(PyExc_TypeError
, "attribute name must be a string");
349 sname
= PyString_AsString(name
);
350 if (sname
[0] == '_' && sname
[1] == '_') {
351 Py_ssize_t n
= PyString_Size(name
);
352 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
354 if (strcmp(sname
, "__dict__") == 0)
355 err
= set_dict(op
, v
);
356 else if (strcmp(sname
, "__bases__") == 0)
357 err
= set_bases(op
, v
);
358 else if (strcmp(sname
, "__name__") == 0)
359 err
= set_name(op
, v
);
360 else if (strcmp(sname
, "__getattr__") == 0)
361 set_slot(&op
->cl_getattr
, v
);
362 else if (strcmp(sname
, "__setattr__") == 0)
363 set_slot(&op
->cl_setattr
, v
);
364 else if (strcmp(sname
, "__delattr__") == 0)
365 set_slot(&op
->cl_delattr
, v
);
366 /* For the last three, we fall through to update the
367 dictionary as well. */
371 PyErr_SetString(PyExc_TypeError
, err
);
377 int rv
= PyDict_DelItem(op
->cl_dict
, name
);
379 PyErr_Format(PyExc_AttributeError
,
380 "class %.50s has no attribute '%.400s'",
381 PyString_AS_STRING(op
->cl_name
), sname
);
385 return PyDict_SetItem(op
->cl_dict
, name
, v
);
389 class_repr(PyClassObject
*op
)
391 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
393 if (op
->cl_name
== NULL
|| !PyString_Check(op
->cl_name
))
396 name
= PyString_AsString(op
->cl_name
);
397 if (mod
== NULL
|| !PyString_Check(mod
))
398 return PyString_FromFormat("<class ?.%s at %p>", name
, op
);
400 return PyString_FromFormat("<class %s.%s at %p>",
401 PyString_AsString(mod
),
406 class_str(PyClassObject
*op
)
408 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
409 PyObject
*name
= op
->cl_name
;
413 if (name
== NULL
|| !PyString_Check(name
))
414 return class_repr(op
);
415 if (mod
== NULL
|| !PyString_Check(mod
)) {
419 m
= PyString_GET_SIZE(mod
);
420 n
= PyString_GET_SIZE(name
);
421 res
= PyString_FromStringAndSize((char *)NULL
, m
+1+n
);
423 char *s
= PyString_AS_STRING(res
);
424 memcpy(s
, PyString_AS_STRING(mod
), m
);
427 memcpy(s
, PyString_AS_STRING(name
), n
);
433 class_traverse(PyClassObject
*o
, visitproc visit
, void *arg
)
435 Py_VISIT(o
->cl_bases
);
436 Py_VISIT(o
->cl_dict
);
437 Py_VISIT(o
->cl_name
);
438 Py_VISIT(o
->cl_getattr
);
439 Py_VISIT(o
->cl_setattr
);
440 Py_VISIT(o
->cl_delattr
);
444 PyTypeObject PyClass_Type
= {
445 PyObject_HEAD_INIT(&PyType_Type
)
448 sizeof(PyClassObject
),
450 (destructor
)class_dealloc
, /* tp_dealloc */
455 (reprfunc
)class_repr
, /* tp_repr */
456 0, /* tp_as_number */
457 0, /* tp_as_sequence */
458 0, /* tp_as_mapping */
460 PyInstance_New
, /* tp_call */
461 (reprfunc
)class_str
, /* tp_str */
462 (getattrofunc
)class_getattr
, /* tp_getattro */
463 (setattrofunc
)class_setattr
, /* tp_setattro */
464 0, /* tp_as_buffer */
465 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
466 class_doc
, /* tp_doc */
467 (traverseproc
)class_traverse
, /* tp_traverse */
469 0, /* tp_richcompare */
470 offsetof(PyClassObject
, cl_weakreflist
), /* tp_weaklistoffset */
478 0, /* tp_descr_get */
479 0, /* tp_descr_set */
480 0, /* tp_dictoffset */
483 class_new
, /* tp_new */
487 PyClass_IsSubclass(PyObject
*klass
, PyObject
*base
)
493 if (PyTuple_Check(base
)) {
494 n
= PyTuple_GET_SIZE(base
);
495 for (i
= 0; i
< n
; i
++) {
496 if (PyClass_IsSubclass(klass
, PyTuple_GET_ITEM(base
, i
)))
501 if (klass
== NULL
|| !PyClass_Check(klass
))
503 cp
= (PyClassObject
*)klass
;
504 n
= PyTuple_Size(cp
->cl_bases
);
505 for (i
= 0; i
< n
; i
++) {
506 if (PyClass_IsSubclass(PyTuple_GetItem(cp
->cl_bases
, i
), base
))
513 /* Instance objects */
516 PyInstance_NewRaw(PyObject
*klass
, PyObject
*dict
)
518 PyInstanceObject
*inst
;
520 if (!PyClass_Check(klass
)) {
521 PyErr_BadInternalCall();
530 if (!PyDict_Check(dict
)) {
531 PyErr_BadInternalCall();
536 inst
= PyObject_GC_New(PyInstanceObject
, &PyInstance_Type
);
541 inst
->in_weakreflist
= NULL
;
543 inst
->in_class
= (PyClassObject
*)klass
;
544 inst
->in_dict
= dict
;
545 _PyObject_GC_TRACK(inst
);
546 return (PyObject
*)inst
;
550 PyInstance_New(PyObject
*klass
, PyObject
*arg
, PyObject
*kw
)
552 register PyInstanceObject
*inst
;
554 static PyObject
*initstr
;
556 if (initstr
== NULL
) {
557 initstr
= PyString_InternFromString("__init__");
561 inst
= (PyInstanceObject
*) PyInstance_NewRaw(klass
, NULL
);
564 init
= instance_getattr2(inst
, initstr
);
566 if (PyErr_Occurred()) {
570 if ((arg
!= NULL
&& (!PyTuple_Check(arg
) ||
571 PyTuple_Size(arg
) != 0))
572 || (kw
!= NULL
&& (!PyDict_Check(kw
) ||
573 PyDict_Size(kw
) != 0))) {
574 PyErr_SetString(PyExc_TypeError
,
575 "this constructor takes no arguments");
581 PyObject
*res
= PyEval_CallObjectWithKeywords(init
, arg
, kw
);
588 if (res
!= Py_None
) {
589 PyErr_SetString(PyExc_TypeError
,
590 "__init__() should return None");
597 return (PyObject
*)inst
;
600 /* Instance methods */
602 PyDoc_STRVAR(instance_doc
,
603 "instance(class[, dict])\n\
605 Create an instance without calling its __init__() method.\n\
606 The class must be a classic class.\n\
607 If present, dict must be a dictionary or None.");
610 instance_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
613 PyObject
*dict
= Py_None
;
615 if (!PyArg_ParseTuple(args
, "O!|O:instance",
616 &PyClass_Type
, &klass
, &dict
))
621 else if (!PyDict_Check(dict
)) {
622 PyErr_SetString(PyExc_TypeError
,
623 "instance() second arg must be dictionary or None");
626 return PyInstance_NewRaw(klass
, dict
);
631 instance_dealloc(register PyInstanceObject
*inst
)
633 PyObject
*error_type
, *error_value
, *error_traceback
;
635 static PyObject
*delstr
;
637 _PyObject_GC_UNTRACK(inst
);
638 if (inst
->in_weakreflist
!= NULL
)
639 PyObject_ClearWeakRefs((PyObject
*) inst
);
641 /* Temporarily resurrect the object. */
642 assert(inst
->ob_type
== &PyInstance_Type
);
643 assert(inst
->ob_refcnt
== 0);
646 /* Save the current exception, if any. */
647 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
648 /* Execute __del__ method, if any. */
649 if (delstr
== NULL
) {
650 delstr
= PyString_InternFromString("__del__");
652 PyErr_WriteUnraisable((PyObject
*)inst
);
654 if (delstr
&& (del
= instance_getattr2(inst
, delstr
)) != NULL
) {
655 PyObject
*res
= PyEval_CallObject(del
, (PyObject
*)NULL
);
657 PyErr_WriteUnraisable(del
);
662 /* Restore the saved exception. */
663 PyErr_Restore(error_type
, error_value
, error_traceback
);
665 /* Undo the temporary resurrection; can't use DECREF here, it would
666 * cause a recursive call.
668 assert(inst
->ob_refcnt
> 0);
669 if (--inst
->ob_refcnt
== 0) {
671 /* New weakrefs could be created during the finalizer call.
672 If this occurs, clear them out without calling their
673 finalizers since they might rely on part of the object
674 being finalized that has already been destroyed. */
675 while (inst
->in_weakreflist
!= NULL
) {
676 _PyWeakref_ClearRef((PyWeakReference
*)
677 (inst
->in_weakreflist
));
680 Py_DECREF(inst
->in_class
);
681 Py_XDECREF(inst
->in_dict
);
682 PyObject_GC_Del(inst
);
685 Py_ssize_t refcnt
= inst
->ob_refcnt
;
686 /* __del__ resurrected it! Make it look like the original
687 * Py_DECREF never happened.
689 _Py_NewReference((PyObject
*)inst
);
690 inst
->ob_refcnt
= refcnt
;
691 _PyObject_GC_TRACK(inst
);
692 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
693 * we need to undo that. */
695 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
696 * object chain, so no more to do there.
697 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
698 * _Py_NewReference bumped tp_allocs: both of those need to be
702 --inst
->ob_type
->tp_frees
;
703 --inst
->ob_type
->tp_allocs
;
709 instance_getattr1(register PyInstanceObject
*inst
, PyObject
*name
)
711 register PyObject
*v
;
712 register char *sname
;
714 if (!PyString_Check(name
)) {
715 PyErr_SetString(PyExc_TypeError
, "attribute name must be a string");
719 sname
= PyString_AsString(name
);
720 if (sname
[0] == '_' && sname
[1] == '_') {
721 if (strcmp(sname
, "__dict__") == 0) {
722 if (PyEval_GetRestricted()) {
723 PyErr_SetString(PyExc_RuntimeError
,
724 "instance.__dict__ not accessible in restricted mode");
727 Py_INCREF(inst
->in_dict
);
728 return inst
->in_dict
;
730 if (strcmp(sname
, "__class__") == 0) {
731 Py_INCREF(inst
->in_class
);
732 return (PyObject
*)inst
->in_class
;
735 v
= instance_getattr2(inst
, name
);
736 if (v
== NULL
&& !PyErr_Occurred()) {
737 PyErr_Format(PyExc_AttributeError
,
738 "%.50s instance has no attribute '%.400s'",
739 PyString_AS_STRING(inst
->in_class
->cl_name
), sname
);
745 instance_getattr2(register PyInstanceObject
*inst
, PyObject
*name
)
747 register PyObject
*v
;
748 PyClassObject
*klass
;
751 v
= PyDict_GetItem(inst
->in_dict
, name
);
756 v
= class_lookup(inst
->in_class
, name
, &klass
);
759 f
= TP_DESCR_GET(v
->ob_type
);
761 PyObject
*w
= f(v
, (PyObject
*)inst
,
762 (PyObject
*)(inst
->in_class
));
771 instance_getattr(register PyInstanceObject
*inst
, PyObject
*name
)
773 register PyObject
*func
, *res
;
774 res
= instance_getattr1(inst
, name
);
775 if (res
== NULL
&& (func
= inst
->in_class
->cl_getattr
) != NULL
) {
777 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
780 args
= PyTuple_Pack(2, inst
, name
);
783 res
= PyEval_CallObject(func
, args
);
789 /* See classobject.h comments: this only does dict lookups, and is always
793 _PyInstance_Lookup(PyObject
*pinst
, PyObject
*name
)
796 PyClassObject
*klass
;
797 PyInstanceObject
*inst
; /* pinst cast to the right type */
799 assert(PyInstance_Check(pinst
));
800 inst
= (PyInstanceObject
*)pinst
;
802 assert(PyString_Check(name
));
804 v
= PyDict_GetItem(inst
->in_dict
, name
);
806 v
= class_lookup(inst
->in_class
, name
, &klass
);
811 instance_setattr1(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
814 int rv
= PyDict_DelItem(inst
->in_dict
, name
);
816 PyErr_Format(PyExc_AttributeError
,
817 "%.50s instance has no attribute '%.400s'",
818 PyString_AS_STRING(inst
->in_class
->cl_name
),
819 PyString_AS_STRING(name
));
823 return PyDict_SetItem(inst
->in_dict
, name
, v
);
827 instance_setattr(PyInstanceObject
*inst
, PyObject
*name
, PyObject
*v
)
829 PyObject
*func
, *args
, *res
, *tmp
;
832 if (!PyString_Check(name
)) {
833 PyErr_SetString(PyExc_TypeError
, "attribute name must be a string");
837 sname
= PyString_AsString(name
);
838 if (sname
[0] == '_' && sname
[1] == '_') {
839 Py_ssize_t n
= PyString_Size(name
);
840 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
841 if (strcmp(sname
, "__dict__") == 0) {
842 if (PyEval_GetRestricted()) {
843 PyErr_SetString(PyExc_RuntimeError
,
844 "__dict__ not accessible in restricted mode");
847 if (v
== NULL
|| !PyDict_Check(v
)) {
848 PyErr_SetString(PyExc_TypeError
,
849 "__dict__ must be set to a dictionary");
858 if (strcmp(sname
, "__class__") == 0) {
859 if (PyEval_GetRestricted()) {
860 PyErr_SetString(PyExc_RuntimeError
,
861 "__class__ not accessible in restricted mode");
864 if (v
== NULL
|| !PyClass_Check(v
)) {
865 PyErr_SetString(PyExc_TypeError
,
866 "__class__ must be set to a class");
869 tmp
= (PyObject
*)(inst
->in_class
);
871 inst
->in_class
= (PyClassObject
*)v
;
878 func
= inst
->in_class
->cl_delattr
;
880 func
= inst
->in_class
->cl_setattr
;
882 return instance_setattr1(inst
, name
, v
);
884 args
= PyTuple_Pack(2, inst
, name
);
886 args
= PyTuple_Pack(3, inst
, name
, v
);
889 res
= PyEval_CallObject(func
, args
);
898 instance_repr(PyInstanceObject
*inst
)
902 static PyObject
*reprstr
;
904 if (reprstr
== NULL
) {
905 reprstr
= PyString_InternFromString("__repr__");
909 func
= instance_getattr(inst
, reprstr
);
911 PyObject
*classname
, *mod
;
913 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
916 classname
= inst
->in_class
->cl_name
;
917 mod
= PyDict_GetItemString(inst
->in_class
->cl_dict
,
919 if (classname
!= NULL
&& PyString_Check(classname
))
920 cname
= PyString_AsString(classname
);
923 if (mod
== NULL
|| !PyString_Check(mod
))
924 return PyString_FromFormat("<?.%s instance at %p>",
927 return PyString_FromFormat("<%s.%s instance at %p>",
928 PyString_AsString(mod
),
931 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
937 instance_str(PyInstanceObject
*inst
)
941 static PyObject
*strstr
;
943 if (strstr
== NULL
) {
944 strstr
= PyString_InternFromString("__str__");
948 func
= instance_getattr(inst
, strstr
);
950 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
953 return instance_repr(inst
);
955 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
961 instance_hash(PyInstanceObject
*inst
)
966 static PyObject
*hashstr
, *eqstr
, *cmpstr
;
968 if (hashstr
== NULL
) {
969 hashstr
= PyString_InternFromString("__hash__");
973 func
= instance_getattr(inst
, hashstr
);
975 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
978 /* If there is no __eq__ and no __cmp__ method, we hash on the
979 address. If an __eq__ or __cmp__ method exists, there must
982 eqstr
= PyString_InternFromString("__eq__");
986 func
= instance_getattr(inst
, eqstr
);
988 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
991 if (cmpstr
== NULL
) {
992 cmpstr
= PyString_InternFromString("__cmp__");
996 func
= instance_getattr(inst
, cmpstr
);
998 if (!PyErr_ExceptionMatches(
999 PyExc_AttributeError
))
1002 return _Py_HashPointer(inst
);
1006 PyErr_SetString(PyExc_TypeError
, "unhashable instance");
1009 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1013 if (PyInt_Check(res
) || PyLong_Check(res
))
1014 /* This already converts a -1 result to -2. */
1015 outcome
= res
->ob_type
->tp_hash(res
);
1017 PyErr_SetString(PyExc_TypeError
,
1018 "__hash__() should return an int");
1026 instance_traverse(PyInstanceObject
*o
, visitproc visit
, void *arg
)
1028 Py_VISIT(o
->in_class
);
1029 Py_VISIT(o
->in_dict
);
1033 static PyObject
*getitemstr
, *setitemstr
, *delitemstr
, *lenstr
;
1034 static PyObject
*iterstr
, *nextstr
;
1037 instance_length(PyInstanceObject
*inst
)
1043 if (lenstr
== NULL
) {
1044 lenstr
= PyString_InternFromString("__len__");
1048 func
= instance_getattr(inst
, lenstr
);
1051 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1055 if (PyInt_Check(res
)) {
1056 outcome
= PyInt_AsSsize_t(res
);
1057 if (outcome
== -1 && PyErr_Occurred()) {
1061 #if SIZEOF_SIZE_T < SIZEOF_INT
1062 /* Overflow check -- range of PyInt is more than C int */
1063 if (outcome
!= (int)outcome
) {
1064 PyErr_SetString(PyExc_OverflowError
,
1065 "__len__() should return 0 <= outcome < 2**31");
1071 PyErr_SetString(PyExc_ValueError
,
1072 "__len__() should return >= 0");
1077 PyErr_SetString(PyExc_TypeError
,
1078 "__len__() should return an int");
1086 instance_subscript(PyInstanceObject
*inst
, PyObject
*key
)
1092 if (getitemstr
== NULL
) {
1093 getitemstr
= PyString_InternFromString("__getitem__");
1094 if (getitemstr
== NULL
)
1097 func
= instance_getattr(inst
, getitemstr
);
1100 arg
= PyTuple_Pack(1, key
);
1105 res
= PyEval_CallObject(func
, arg
);
1112 instance_ass_subscript(PyInstanceObject
*inst
, PyObject
*key
, PyObject
*value
)
1118 if (value
== NULL
) {
1119 if (delitemstr
== NULL
) {
1120 delitemstr
= PyString_InternFromString("__delitem__");
1121 if (delitemstr
== NULL
)
1124 func
= instance_getattr(inst
, delitemstr
);
1127 if (setitemstr
== NULL
) {
1128 setitemstr
= PyString_InternFromString("__setitem__");
1129 if (setitemstr
== NULL
)
1132 func
= instance_getattr(inst
, setitemstr
);
1137 arg
= PyTuple_Pack(1, key
);
1139 arg
= PyTuple_Pack(2, key
, value
);
1144 res
= PyEval_CallObject(func
, arg
);
1153 static PyMappingMethods instance_as_mapping
= {
1154 (lenfunc
)instance_length
, /* mp_length */
1155 (binaryfunc
)instance_subscript
, /* mp_subscript */
1156 (objobjargproc
)instance_ass_subscript
, /* mp_ass_subscript */
1160 instance_item(PyInstanceObject
*inst
, Py_ssize_t i
)
1162 PyObject
*func
, *res
;
1164 if (getitemstr
== NULL
) {
1165 getitemstr
= PyString_InternFromString("__getitem__");
1166 if (getitemstr
== NULL
)
1169 func
= instance_getattr(inst
, getitemstr
);
1172 res
= PyObject_CallFunction(func
, "n", i
);
1178 instance_slice(PyInstanceObject
*inst
, Py_ssize_t i
, Py_ssize_t j
)
1180 PyObject
*func
, *arg
, *res
;
1181 static PyObject
*getslicestr
;
1183 if (getslicestr
== NULL
) {
1184 getslicestr
= PyString_InternFromString("__getslice__");
1185 if (getslicestr
== NULL
)
1188 func
= instance_getattr(inst
, getslicestr
);
1191 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1195 if (getitemstr
== NULL
) {
1196 getitemstr
= PyString_InternFromString("__getitem__");
1197 if (getitemstr
== NULL
)
1200 func
= instance_getattr(inst
, getitemstr
);
1203 arg
= Py_BuildValue("(N)", _PySlice_FromIndices(i
, j
));
1206 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
1207 "use __getitem__", 1) < 0) {
1211 arg
= Py_BuildValue("(nn)", i
, j
);
1218 res
= PyEval_CallObject(func
, arg
);
1225 instance_ass_item(PyInstanceObject
*inst
, Py_ssize_t i
, PyObject
*item
)
1227 PyObject
*func
, *arg
, *res
;
1230 if (delitemstr
== NULL
) {
1231 delitemstr
= PyString_InternFromString("__delitem__");
1232 if (delitemstr
== NULL
)
1235 func
= instance_getattr(inst
, delitemstr
);
1238 if (setitemstr
== NULL
) {
1239 setitemstr
= PyString_InternFromString("__setitem__");
1240 if (setitemstr
== NULL
)
1243 func
= instance_getattr(inst
, setitemstr
);
1248 arg
= Py_BuildValue("(n)", i
);
1250 arg
= Py_BuildValue("(nO)", i
, item
);
1255 res
= PyEval_CallObject(func
, arg
);
1265 instance_ass_slice(PyInstanceObject
*inst
, Py_ssize_t i
, Py_ssize_t j
, PyObject
*value
)
1267 PyObject
*func
, *arg
, *res
;
1268 static PyObject
*setslicestr
, *delslicestr
;
1270 if (value
== NULL
) {
1271 if (delslicestr
== NULL
) {
1273 PyString_InternFromString("__delslice__");
1274 if (delslicestr
== NULL
)
1277 func
= instance_getattr(inst
, delslicestr
);
1279 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1282 if (delitemstr
== NULL
) {
1284 PyString_InternFromString("__delitem__");
1285 if (delitemstr
== NULL
)
1288 func
= instance_getattr(inst
, delitemstr
);
1292 arg
= Py_BuildValue("(N)",
1293 _PySlice_FromIndices(i
, j
));
1296 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
1297 "removed; use __delitem__", 1) < 0) {
1301 arg
= Py_BuildValue("(nn)", i
, j
);
1305 if (setslicestr
== NULL
) {
1307 PyString_InternFromString("__setslice__");
1308 if (setslicestr
== NULL
)
1311 func
= instance_getattr(inst
, setslicestr
);
1313 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1316 if (setitemstr
== NULL
) {
1318 PyString_InternFromString("__setitem__");
1319 if (setitemstr
== NULL
)
1322 func
= instance_getattr(inst
, setitemstr
);
1326 arg
= Py_BuildValue("(NO)",
1327 _PySlice_FromIndices(i
, j
), value
);
1330 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
1331 "removed; use __setitem__", 1) < 0) {
1335 arg
= Py_BuildValue("(nnO)", i
, j
, value
);
1342 res
= PyEval_CallObject(func
, arg
);
1352 instance_contains(PyInstanceObject
*inst
, PyObject
*member
)
1354 static PyObject
*__contains__
;
1357 /* Try __contains__ first.
1358 * If that can't be done, try iterator-based searching.
1361 if(__contains__
== NULL
) {
1362 __contains__
= PyString_InternFromString("__contains__");
1363 if(__contains__
== NULL
)
1366 func
= instance_getattr(inst
, __contains__
);
1370 PyObject
*arg
= PyTuple_Pack(1, member
);
1375 res
= PyEval_CallObject(func
, arg
);
1380 ret
= PyObject_IsTrue(res
);
1385 /* Couldn't find __contains__. */
1386 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1388 /* Assume the failure was simply due to that there is no
1389 * __contains__ attribute, and try iterating instead.
1392 rc
= _PySequence_IterSearch((PyObject
*)inst
, member
,
1393 PY_ITERSEARCH_CONTAINS
);
1400 static PySequenceMethods
1401 instance_as_sequence
= {
1402 (lenfunc
)instance_length
, /* sq_length */
1405 (ssizeargfunc
)instance_item
, /* sq_item */
1406 (ssizessizeargfunc
)instance_slice
, /* sq_slice */
1407 (ssizeobjargproc
)instance_ass_item
, /* sq_ass_item */
1408 (ssizessizeobjargproc
)instance_ass_slice
,/* sq_ass_slice */
1409 (objobjproc
)instance_contains
, /* sq_contains */
1413 generic_unary_op(PyInstanceObject
*self
, PyObject
*methodname
)
1415 PyObject
*func
, *res
;
1417 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1419 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1425 generic_binary_op(PyObject
*v
, PyObject
*w
, char *opname
)
1429 PyObject
*func
= PyObject_GetAttrString(v
, opname
);
1431 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1434 Py_INCREF(Py_NotImplemented
);
1435 return Py_NotImplemented
;
1437 args
= PyTuple_Pack(1, w
);
1442 result
= PyEval_CallObject(func
, args
);
1449 static PyObject
*coerce_obj
;
1451 /* Try one half of a binary operator involving a class instance. */
1453 half_binop(PyObject
*v
, PyObject
*w
, char *opname
, binaryfunc thisfunc
,
1457 PyObject
*coercefunc
;
1458 PyObject
*coerced
= NULL
;
1462 if (!PyInstance_Check(v
)) {
1463 Py_INCREF(Py_NotImplemented
);
1464 return Py_NotImplemented
;
1467 if (coerce_obj
== NULL
) {
1468 coerce_obj
= PyString_InternFromString("__coerce__");
1469 if (coerce_obj
== NULL
)
1472 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1473 if (coercefunc
== NULL
) {
1474 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1477 return generic_binary_op(v
, w
, opname
);
1480 args
= PyTuple_Pack(1, w
);
1482 Py_DECREF(coercefunc
);
1485 coerced
= PyEval_CallObject(coercefunc
, args
);
1487 Py_DECREF(coercefunc
);
1488 if (coerced
== NULL
) {
1491 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1493 return generic_binary_op(v
, w
, opname
);
1495 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1497 PyErr_SetString(PyExc_TypeError
,
1498 "coercion should return None or 2-tuple");
1501 v1
= PyTuple_GetItem(coerced
, 0);
1502 w
= PyTuple_GetItem(coerced
, 1);
1503 if (v1
->ob_type
== v
->ob_type
&& PyInstance_Check(v
)) {
1504 /* prevent recursion if __coerce__ returns self as the first
1506 result
= generic_binary_op(v1
, w
, opname
);
1508 if (Py_EnterRecursiveCall(" after coercion"))
1511 result
= (thisfunc
)(w
, v1
);
1513 result
= (thisfunc
)(v1
, w
);
1514 Py_LeaveRecursiveCall();
1520 /* Implement a binary operator involving at least one class instance. */
1522 do_binop(PyObject
*v
, PyObject
*w
, char *opname
, char *ropname
,
1523 binaryfunc thisfunc
)
1525 PyObject
*result
= half_binop(v
, w
, opname
, thisfunc
, 0);
1526 if (result
== Py_NotImplemented
) {
1528 result
= half_binop(w
, v
, ropname
, thisfunc
, 1);
1534 do_binop_inplace(PyObject
*v
, PyObject
*w
, char *iopname
, char *opname
,
1535 char *ropname
, binaryfunc thisfunc
)
1537 PyObject
*result
= half_binop(v
, w
, iopname
, thisfunc
, 0);
1538 if (result
== Py_NotImplemented
) {
1540 result
= do_binop(v
, w
, opname
, ropname
, thisfunc
);
1546 instance_coerce(PyObject
**pv
, PyObject
**pw
)
1550 PyObject
*coercefunc
;
1554 if (coerce_obj
== NULL
) {
1555 coerce_obj
= PyString_InternFromString("__coerce__");
1556 if (coerce_obj
== NULL
)
1559 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1560 if (coercefunc
== NULL
) {
1561 /* No __coerce__ method */
1562 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1567 /* Has __coerce__ method: call it */
1568 args
= PyTuple_Pack(1, w
);
1572 coerced
= PyEval_CallObject(coercefunc
, args
);
1574 Py_DECREF(coercefunc
);
1575 if (coerced
== NULL
) {
1576 /* __coerce__ call raised an exception */
1579 if (coerced
== Py_None
|| coerced
== Py_NotImplemented
) {
1580 /* __coerce__ says "I can't do it" */
1584 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1585 /* __coerce__ return value is malformed */
1587 PyErr_SetString(PyExc_TypeError
,
1588 "coercion should return None or 2-tuple");
1591 /* __coerce__ returned two new values */
1592 *pv
= PyTuple_GetItem(coerced
, 0);
1593 *pw
= PyTuple_GetItem(coerced
, 1);
1600 #define UNARY(funcname, methodname) \
1601 static PyObject *funcname(PyInstanceObject *self) { \
1602 static PyObject *o; \
1603 if (o == NULL) { o = PyString_InternFromString(methodname); \
1604 if (o == NULL) return NULL; } \
1605 return generic_unary_op(self, o); \
1608 /* unary function with a fallback */
1609 #define UNARY_FB(funcname, methodname, funcname_fb) \
1610 static PyObject *funcname(PyInstanceObject *self) { \
1611 static PyObject *o; \
1612 if (o == NULL) { o = PyString_InternFromString(methodname); \
1613 if (o == NULL) return NULL; } \
1614 if (PyObject_HasAttr((PyObject*)self, o)) \
1615 return generic_unary_op(self, o); \
1617 return funcname_fb(self); \
1620 #define BINARY(f, m, n) \
1621 static PyObject *f(PyObject *v, PyObject *w) { \
1622 return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1625 #define BINARY_INPLACE(f, m, n) \
1626 static PyObject *f(PyObject *v, PyObject *w) { \
1627 return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1631 UNARY(instance_neg
, "__neg__")
1632 UNARY(instance_pos
, "__pos__")
1633 UNARY(instance_abs
, "__abs__")
1635 BINARY(instance_or
, "or", PyNumber_Or
)
1636 BINARY(instance_and
, "and", PyNumber_And
)
1637 BINARY(instance_xor
, "xor", PyNumber_Xor
)
1638 BINARY(instance_lshift
, "lshift", PyNumber_Lshift
)
1639 BINARY(instance_rshift
, "rshift", PyNumber_Rshift
)
1640 BINARY(instance_add
, "add", PyNumber_Add
)
1641 BINARY(instance_sub
, "sub", PyNumber_Subtract
)
1642 BINARY(instance_mul
, "mul", PyNumber_Multiply
)
1643 BINARY(instance_div
, "div", PyNumber_Divide
)
1644 BINARY(instance_mod
, "mod", PyNumber_Remainder
)
1645 BINARY(instance_divmod
, "divmod", PyNumber_Divmod
)
1646 BINARY(instance_floordiv
, "floordiv", PyNumber_FloorDivide
)
1647 BINARY(instance_truediv
, "truediv", PyNumber_TrueDivide
)
1649 BINARY_INPLACE(instance_ior
, "or", PyNumber_InPlaceOr
)
1650 BINARY_INPLACE(instance_ixor
, "xor", PyNumber_InPlaceXor
)
1651 BINARY_INPLACE(instance_iand
, "and", PyNumber_InPlaceAnd
)
1652 BINARY_INPLACE(instance_ilshift
, "lshift", PyNumber_InPlaceLshift
)
1653 BINARY_INPLACE(instance_irshift
, "rshift", PyNumber_InPlaceRshift
)
1654 BINARY_INPLACE(instance_iadd
, "add", PyNumber_InPlaceAdd
)
1655 BINARY_INPLACE(instance_isub
, "sub", PyNumber_InPlaceSubtract
)
1656 BINARY_INPLACE(instance_imul
, "mul", PyNumber_InPlaceMultiply
)
1657 BINARY_INPLACE(instance_idiv
, "div", PyNumber_InPlaceDivide
)
1658 BINARY_INPLACE(instance_imod
, "mod", PyNumber_InPlaceRemainder
)
1659 BINARY_INPLACE(instance_ifloordiv
, "floordiv", PyNumber_InPlaceFloorDivide
)
1660 BINARY_INPLACE(instance_itruediv
, "truediv", PyNumber_InPlaceTrueDivide
)
1662 /* Try a 3-way comparison, returning an int; v is an instance. Return:
1663 -2 for an exception;
1667 2 if this particular 3-way comparison is not implemented or undefined.
1670 half_cmp(PyObject
*v
, PyObject
*w
)
1672 static PyObject
*cmp_obj
;
1678 assert(PyInstance_Check(v
));
1680 if (cmp_obj
== NULL
) {
1681 cmp_obj
= PyString_InternFromString("__cmp__");
1682 if (cmp_obj
== NULL
)
1686 cmp_func
= PyObject_GetAttr(v
, cmp_obj
);
1687 if (cmp_func
== NULL
) {
1688 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1694 args
= PyTuple_Pack(1, w
);
1696 Py_DECREF(cmp_func
);
1700 result
= PyEval_CallObject(cmp_func
, args
);
1702 Py_DECREF(cmp_func
);
1707 if (result
== Py_NotImplemented
) {
1712 l
= PyInt_AsLong(result
);
1714 if (l
== -1 && PyErr_Occurred()) {
1715 PyErr_SetString(PyExc_TypeError
,
1716 "comparison did not return an int");
1720 return l
< 0 ? -1 : l
> 0 ? 1 : 0;
1723 /* Try a 3-way comparison, returning an int; either v or w is an instance.
1724 We first try a coercion. Return:
1725 -2 for an exception;
1729 2 if this particular 3-way comparison is not implemented or undefined.
1730 THIS IS ONLY CALLED FROM object.c!
1733 instance_compare(PyObject
*v
, PyObject
*w
)
1737 c
= PyNumber_CoerceEx(&v
, &w
);
1741 /* If neither is now an instance, use regular comparison */
1742 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1743 c
= PyObject_Compare(v
, w
);
1746 if (PyErr_Occurred())
1748 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
1752 /* The coercion didn't do anything.
1753 Treat this the same as returning v and w unchanged. */
1758 if (PyInstance_Check(v
)) {
1766 if (PyInstance_Check(w
)) {
1782 instance_nonzero(PyInstanceObject
*self
)
1784 PyObject
*func
, *res
;
1786 static PyObject
*nonzerostr
;
1788 if (nonzerostr
== NULL
) {
1789 nonzerostr
= PyString_InternFromString("__nonzero__");
1790 if (nonzerostr
== NULL
)
1793 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1794 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1797 if (lenstr
== NULL
) {
1798 lenstr
= PyString_InternFromString("__len__");
1802 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1803 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1806 /* Fall back to the default behavior:
1807 all instances are nonzero */
1811 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1815 if (!PyInt_Check(res
)) {
1817 PyErr_SetString(PyExc_TypeError
,
1818 "__nonzero__ should return an int");
1821 outcome
= PyInt_AsLong(res
);
1824 PyErr_SetString(PyExc_ValueError
,
1825 "__nonzero__ should return >= 0");
1832 instance_index(PyInstanceObject
*self
)
1834 PyObject
*func
, *res
;
1835 static PyObject
*indexstr
= NULL
;
1837 if (indexstr
== NULL
) {
1838 indexstr
= PyString_InternFromString("__index__");
1839 if (indexstr
== NULL
)
1842 if ((func
= instance_getattr(self
, indexstr
)) == NULL
) {
1843 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1846 PyErr_SetString(PyExc_TypeError
,
1847 "object cannot be interpreted as an index");
1850 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1856 UNARY(instance_invert
, "__invert__")
1857 UNARY(_instance_trunc
, "__trunc__")
1860 instance_int(PyInstanceObject
*self
)
1862 PyObject
*truncated
;
1863 static PyObject
*int_name
;
1864 if (int_name
== NULL
) {
1865 int_name
= PyString_InternFromString("__int__");
1866 if (int_name
== NULL
)
1869 if (PyObject_HasAttr((PyObject
*)self
, int_name
))
1870 return generic_unary_op(self
, int_name
);
1872 truncated
= _instance_trunc(self
);
1873 /* __trunc__ is specified to return an Integral type, but
1874 int() needs to return an int. */
1875 return _PyNumber_ConvertIntegralToInt(
1877 "__trunc__ returned non-Integral (type %.200s)");
1880 UNARY_FB(instance_long
, "__long__", instance_int
)
1881 UNARY(instance_float
, "__float__")
1882 UNARY(instance_oct
, "__oct__")
1883 UNARY(instance_hex
, "__hex__")
1886 bin_power(PyObject
*v
, PyObject
*w
)
1888 return PyNumber_Power(v
, w
, Py_None
);
1891 /* This version is for ternary calls only (z != None) */
1893 instance_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1896 return do_binop(v
, w
, "__pow__", "__rpow__", bin_power
);
1903 /* XXX Doesn't do coercions... */
1904 func
= PyObject_GetAttrString(v
, "__pow__");
1907 args
= PyTuple_Pack(2, w
, z
);
1912 result
= PyEval_CallObject(func
, args
);
1920 bin_inplace_power(PyObject
*v
, PyObject
*w
)
1922 return PyNumber_InPlacePower(v
, w
, Py_None
);
1927 instance_ipow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1930 return do_binop_inplace(v
, w
, "__ipow__", "__pow__",
1931 "__rpow__", bin_inplace_power
);
1934 /* XXX Doesn't do coercions... */
1939 func
= PyObject_GetAttrString(v
, "__ipow__");
1941 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1944 return instance_pow(v
, w
, z
);
1946 args
= PyTuple_Pack(2, w
, z
);
1951 result
= PyEval_CallObject(func
, args
);
1959 /* Map rich comparison operators to their __xx__ namesakes */
1961 static PyObject
**name_op
= NULL
;
1967 char *_name_op
[] = {
1976 name_op
= (PyObject
**)malloc(sizeof(PyObject
*) * NAME_OPS
);
1977 if (name_op
== NULL
)
1979 for (i
= 0; i
< NAME_OPS
; ++i
) {
1980 name_op
[i
] = PyString_InternFromString(_name_op
[i
]);
1981 if (name_op
[i
] == NULL
)
1988 half_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1994 assert(PyInstance_Check(v
));
1996 if (name_op
== NULL
) {
1997 if (init_name_op() < 0)
2000 /* If the instance doesn't define an __getattr__ method, use
2001 instance_getattr2 directly because it will not set an
2002 exception on failure. */
2003 if (((PyInstanceObject
*)v
)->in_class
->cl_getattr
== NULL
)
2004 method
= instance_getattr2((PyInstanceObject
*)v
,
2007 method
= PyObject_GetAttr(v
, name_op
[op
]);
2008 if (method
== NULL
) {
2009 if (PyErr_Occurred()) {
2010 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2014 res
= Py_NotImplemented
;
2019 args
= PyTuple_Pack(1, w
);
2025 res
= PyEval_CallObject(method
, args
);
2033 instance_richcompare(PyObject
*v
, PyObject
*w
, int op
)
2037 if (PyInstance_Check(v
)) {
2038 res
= half_richcompare(v
, w
, op
);
2039 if (res
!= Py_NotImplemented
)
2044 if (PyInstance_Check(w
)) {
2045 res
= half_richcompare(w
, v
, _Py_SwappedOp
[op
]);
2046 if (res
!= Py_NotImplemented
)
2051 Py_INCREF(Py_NotImplemented
);
2052 return Py_NotImplemented
;
2056 /* Get the iterator */
2058 instance_getiter(PyInstanceObject
*self
)
2062 if (iterstr
== NULL
) {
2063 iterstr
= PyString_InternFromString("__iter__");
2064 if (iterstr
== NULL
)
2067 if (getitemstr
== NULL
) {
2068 getitemstr
= PyString_InternFromString("__getitem__");
2069 if (getitemstr
== NULL
)
2073 if ((func
= instance_getattr(self
, iterstr
)) != NULL
) {
2074 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
2076 if (res
!= NULL
&& !PyIter_Check(res
)) {
2077 PyErr_Format(PyExc_TypeError
,
2078 "__iter__ returned non-iterator "
2080 res
->ob_type
->tp_name
);
2086 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2089 if ((func
= instance_getattr(self
, getitemstr
)) == NULL
) {
2090 PyErr_SetString(PyExc_TypeError
,
2091 "iteration over non-sequence");
2095 return PySeqIter_New((PyObject
*)self
);
2099 /* Call the iterator's next */
2101 instance_iternext(PyInstanceObject
*self
)
2105 if (nextstr
== NULL
) {
2106 nextstr
= PyString_InternFromString("next");
2107 if (nextstr
== NULL
)
2111 if ((func
= instance_getattr(self
, nextstr
)) != NULL
) {
2112 PyObject
*res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
2117 if (PyErr_ExceptionMatches(PyExc_StopIteration
)) {
2123 PyErr_SetString(PyExc_TypeError
, "instance has no next() method");
2128 instance_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2130 PyObject
*res
, *call
= PyObject_GetAttrString(func
, "__call__");
2132 PyInstanceObject
*inst
= (PyInstanceObject
*) func
;
2133 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2136 PyErr_Format(PyExc_AttributeError
,
2137 "%.200s instance has no __call__ method",
2138 PyString_AsString(inst
->in_class
->cl_name
));
2141 /* We must check and increment the recursion depth here. Scenario:
2144 A.__call__ = A() # that's right
2146 a() # infinite recursion
2147 This bounces between instance_call() and PyObject_Call() without
2148 ever hitting eval_frame() (which has the main recursion check). */
2149 if (Py_EnterRecursiveCall(" in __call__")) {
2153 res
= PyObject_Call(call
, arg
, kw
);
2154 Py_LeaveRecursiveCall();
2161 static PyNumberMethods instance_as_number
= {
2162 instance_add
, /* nb_add */
2163 instance_sub
, /* nb_subtract */
2164 instance_mul
, /* nb_multiply */
2165 instance_div
, /* nb_divide */
2166 instance_mod
, /* nb_remainder */
2167 instance_divmod
, /* nb_divmod */
2168 instance_pow
, /* nb_power */
2169 (unaryfunc
)instance_neg
, /* nb_negative */
2170 (unaryfunc
)instance_pos
, /* nb_positive */
2171 (unaryfunc
)instance_abs
, /* nb_absolute */
2172 (inquiry
)instance_nonzero
, /* nb_nonzero */
2173 (unaryfunc
)instance_invert
, /* nb_invert */
2174 instance_lshift
, /* nb_lshift */
2175 instance_rshift
, /* nb_rshift */
2176 instance_and
, /* nb_and */
2177 instance_xor
, /* nb_xor */
2178 instance_or
, /* nb_or */
2179 instance_coerce
, /* nb_coerce */
2180 (unaryfunc
)instance_int
, /* nb_int */
2181 (unaryfunc
)instance_long
, /* nb_long */
2182 (unaryfunc
)instance_float
, /* nb_float */
2183 (unaryfunc
)instance_oct
, /* nb_oct */
2184 (unaryfunc
)instance_hex
, /* nb_hex */
2185 instance_iadd
, /* nb_inplace_add */
2186 instance_isub
, /* nb_inplace_subtract */
2187 instance_imul
, /* nb_inplace_multiply */
2188 instance_idiv
, /* nb_inplace_divide */
2189 instance_imod
, /* nb_inplace_remainder */
2190 instance_ipow
, /* nb_inplace_power */
2191 instance_ilshift
, /* nb_inplace_lshift */
2192 instance_irshift
, /* nb_inplace_rshift */
2193 instance_iand
, /* nb_inplace_and */
2194 instance_ixor
, /* nb_inplace_xor */
2195 instance_ior
, /* nb_inplace_or */
2196 instance_floordiv
, /* nb_floor_divide */
2197 instance_truediv
, /* nb_true_divide */
2198 instance_ifloordiv
, /* nb_inplace_floor_divide */
2199 instance_itruediv
, /* nb_inplace_true_divide */
2200 (unaryfunc
)instance_index
, /* nb_index */
2203 PyTypeObject PyInstance_Type
= {
2204 PyObject_HEAD_INIT(&PyType_Type
)
2207 sizeof(PyInstanceObject
),
2209 (destructor
)instance_dealloc
, /* tp_dealloc */
2213 instance_compare
, /* tp_compare */
2214 (reprfunc
)instance_repr
, /* tp_repr */
2215 &instance_as_number
, /* tp_as_number */
2216 &instance_as_sequence
, /* tp_as_sequence */
2217 &instance_as_mapping
, /* tp_as_mapping */
2218 (hashfunc
)instance_hash
, /* tp_hash */
2219 instance_call
, /* tp_call */
2220 (reprfunc
)instance_str
, /* tp_str */
2221 (getattrofunc
)instance_getattr
, /* tp_getattro */
2222 (setattrofunc
)instance_setattr
, /* tp_setattro */
2223 0, /* tp_as_buffer */
2224 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
,/*tp_flags*/
2225 instance_doc
, /* tp_doc */
2226 (traverseproc
)instance_traverse
, /* tp_traverse */
2228 instance_richcompare
, /* tp_richcompare */
2229 offsetof(PyInstanceObject
, in_weakreflist
), /* tp_weaklistoffset */
2230 (getiterfunc
)instance_getiter
, /* tp_iter */
2231 (iternextfunc
)instance_iternext
, /* tp_iternext */
2237 0, /* tp_descr_get */
2238 0, /* tp_descr_set */
2239 0, /* tp_dictoffset */
2242 instance_new
, /* tp_new */
2246 /* Instance method objects are used for two purposes:
2247 (a) as bound instance methods (returned by instancename.methodname)
2248 (b) as unbound methods (returned by ClassName.methodname)
2249 In case (b), im_self is NULL
2253 PyMethod_New(PyObject
*func
, PyObject
*self
, PyObject
*klass
)
2255 register PyMethodObject
*im
;
2258 free_list
= (PyMethodObject
*)(im
->im_self
);
2259 PyObject_INIT(im
, &PyMethod_Type
);
2263 im
= PyObject_GC_New(PyMethodObject
, &PyMethod_Type
);
2267 im
->im_weakreflist
= NULL
;
2273 im
->im_class
= klass
;
2274 _PyObject_GC_TRACK(im
);
2275 return (PyObject
*)im
;
2278 /* Descriptors for PyMethod attributes */
2280 /* im_class, im_func and im_self are stored in the PyMethod object */
2282 #define OFF(x) offsetof(PyMethodObject, x)
2284 static PyMemberDef instancemethod_memberlist
[] = {
2285 {"im_class", T_OBJECT
, OFF(im_class
), READONLY
|RESTRICTED
,
2286 "the class associated with a method"},
2287 {"im_func", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2288 "the function (or other callable) implementing a method"},
2289 {"__func__", T_OBJECT
, OFF(im_func
), READONLY
|RESTRICTED
,
2290 "the function (or other callable) implementing a method"},
2291 {"im_self", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2292 "the instance to which a method is bound; None for unbound methods"},
2293 {"__self__", T_OBJECT
, OFF(im_self
), READONLY
|RESTRICTED
,
2294 "the instance to which a method is bound; None for unbound methods"},
2295 {NULL
} /* Sentinel */
2298 /* Christian Tismer argued convincingly that method attributes should
2299 (nearly) always override function attributes.
2300 The one exception is __doc__; there's a default __doc__ which
2301 should only be used for the class, not for instances */
2304 instancemethod_get_doc(PyMethodObject
*im
, void *context
)
2306 static PyObject
*docstr
;
2307 if (docstr
== NULL
) {
2308 docstr
= PyString_InternFromString("__doc__");
2312 return PyObject_GetAttr(im
->im_func
, docstr
);
2315 static PyGetSetDef instancemethod_getset
[] = {
2316 {"__doc__", (getter
)instancemethod_get_doc
, NULL
, NULL
},
2321 instancemethod_getattro(PyObject
*obj
, PyObject
*name
)
2323 PyMethodObject
*im
= (PyMethodObject
*)obj
;
2324 PyTypeObject
*tp
= obj
->ob_type
;
2325 PyObject
*descr
= NULL
;
2327 if (PyType_HasFeature(tp
, Py_TPFLAGS_HAVE_CLASS
)) {
2328 if (tp
->tp_dict
== NULL
) {
2329 if (PyType_Ready(tp
) < 0)
2332 descr
= _PyType_Lookup(tp
, name
);
2335 if (descr
!= NULL
) {
2336 descrgetfunc f
= TP_DESCR_GET(descr
->ob_type
);
2338 return f(descr
, obj
, (PyObject
*)obj
->ob_type
);
2345 return PyObject_GetAttr(im
->im_func
, name
);
2348 PyDoc_STRVAR(instancemethod_doc
,
2349 "instancemethod(function, instance, class)\n\
2351 Create an instance method object.");
2354 instancemethod_new(PyTypeObject
* type
, PyObject
* args
, PyObject
*kw
)
2358 PyObject
*classObj
= NULL
;
2360 if (!_PyArg_NoKeywords("instancemethod", kw
))
2362 if (!PyArg_UnpackTuple(args
, "instancemethod", 2, 3,
2363 &func
, &self
, &classObj
))
2365 if (!PyCallable_Check(func
)) {
2366 PyErr_SetString(PyExc_TypeError
,
2367 "first argument must be callable");
2370 if (self
== Py_None
)
2372 if (self
== NULL
&& classObj
== NULL
) {
2373 PyErr_SetString(PyExc_TypeError
,
2374 "unbound methods must have non-NULL im_class");
2378 return PyMethod_New(func
, self
, classObj
);
2382 instancemethod_dealloc(register PyMethodObject
*im
)
2384 _PyObject_GC_UNTRACK(im
);
2385 if (im
->im_weakreflist
!= NULL
)
2386 PyObject_ClearWeakRefs((PyObject
*)im
);
2387 Py_DECREF(im
->im_func
);
2388 Py_XDECREF(im
->im_self
);
2389 Py_XDECREF(im
->im_class
);
2390 if (numfree
< PyMethod_MAXFREELIST
) {
2391 im
->im_self
= (PyObject
*)free_list
;
2396 PyObject_GC_Del(im
);
2401 instancemethod_compare(PyMethodObject
*a
, PyMethodObject
*b
)
2404 cmp
= PyObject_Compare(a
->im_func
, b
->im_func
);
2408 if (a
->im_self
== b
->im_self
)
2410 if (a
->im_self
== NULL
|| b
->im_self
== NULL
)
2411 return (a
->im_self
< b
->im_self
) ? -1 : 1;
2413 return PyObject_Compare(a
->im_self
, b
->im_self
);
2417 instancemethod_repr(PyMethodObject
*a
)
2419 PyObject
*self
= a
->im_self
;
2420 PyObject
*func
= a
->im_func
;
2421 PyObject
*klass
= a
->im_class
;
2422 PyObject
*funcname
= NULL
, *klassname
= NULL
, *result
= NULL
;
2423 char *sfuncname
= "?", *sklassname
= "?";
2425 funcname
= PyObject_GetAttrString(func
, "__name__");
2426 if (funcname
== NULL
) {
2427 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2431 else if (!PyString_Check(funcname
)) {
2432 Py_DECREF(funcname
);
2436 sfuncname
= PyString_AS_STRING(funcname
);
2440 klassname
= PyObject_GetAttrString(klass
, "__name__");
2441 if (klassname
== NULL
) {
2442 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
2446 else if (!PyString_Check(klassname
)) {
2447 Py_DECREF(klassname
);
2451 sklassname
= PyString_AS_STRING(klassname
);
2454 result
= PyString_FromFormat("<unbound method %s.%s>",
2455 sklassname
, sfuncname
);
2457 /* XXX Shouldn't use repr() here! */
2458 PyObject
*selfrepr
= PyObject_Repr(self
);
2459 if (selfrepr
== NULL
)
2461 if (!PyString_Check(selfrepr
)) {
2462 Py_DECREF(selfrepr
);
2465 result
= PyString_FromFormat("<bound method %s.%s of %s>",
2466 sklassname
, sfuncname
,
2467 PyString_AS_STRING(selfrepr
));
2468 Py_DECREF(selfrepr
);
2471 Py_XDECREF(funcname
);
2472 Py_XDECREF(klassname
);
2477 instancemethod_hash(PyMethodObject
*a
)
2480 if (a
->im_self
== NULL
)
2481 x
= PyObject_Hash(Py_None
);
2483 x
= PyObject_Hash(a
->im_self
);
2486 y
= PyObject_Hash(a
->im_func
);
2496 instancemethod_traverse(PyMethodObject
*im
, visitproc visit
, void *arg
)
2498 Py_VISIT(im
->im_func
);
2499 Py_VISIT(im
->im_self
);
2500 Py_VISIT(im
->im_class
);
2505 getclassname(PyObject
*klass
, char *buf
, int bufsize
)
2509 assert(bufsize
> 1);
2510 strcpy(buf
, "?"); /* Default outcome */
2513 name
= PyObject_GetAttrString(klass
, "__name__");
2515 /* This function cannot return an exception */
2519 if (PyString_Check(name
)) {
2520 strncpy(buf
, PyString_AS_STRING(name
), bufsize
);
2521 buf
[bufsize
-1] = '\0';
2527 getinstclassname(PyObject
*inst
, char *buf
, int bufsize
)
2532 assert(bufsize
> 0 && (size_t)bufsize
> strlen("nothing"));
2533 strcpy(buf
, "nothing");
2537 klass
= PyObject_GetAttrString(inst
, "__class__");
2538 if (klass
== NULL
) {
2539 /* This function cannot return an exception */
2541 klass
= (PyObject
*)(inst
->ob_type
);
2544 getclassname(klass
, buf
, bufsize
);
2549 instancemethod_call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2551 PyObject
*self
= PyMethod_GET_SELF(func
);
2552 PyObject
*klass
= PyMethod_GET_CLASS(func
);
2555 func
= PyMethod_GET_FUNCTION(func
);
2557 /* Unbound methods must be called with an instance of
2558 the class (or a derived class) as first argument */
2560 if (PyTuple_Size(arg
) >= 1)
2561 self
= PyTuple_GET_ITEM(arg
, 0);
2565 ok
= PyObject_IsInstance(self
, klass
);
2572 getclassname(klass
, clsbuf
, sizeof(clsbuf
));
2573 getinstclassname(self
, instbuf
, sizeof(instbuf
));
2574 PyErr_Format(PyExc_TypeError
,
2575 "unbound method %s%s must be called with "
2576 "%s instance as first argument "
2577 "(got %s%s instead)",
2578 PyEval_GetFuncName(func
),
2579 PyEval_GetFuncDesc(func
),
2582 self
== NULL
? "" : " instance");
2588 Py_ssize_t argcount
= PyTuple_Size(arg
);
2589 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2594 PyTuple_SET_ITEM(newarg
, 0, self
);
2595 for (i
= 0; i
< argcount
; i
++) {
2596 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2598 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2602 result
= PyObject_Call((PyObject
*)func
, arg
, kw
);
2608 instancemethod_descr_get(PyObject
*meth
, PyObject
*obj
, PyObject
*cls
)
2610 /* Don't rebind an already bound method, or an unbound method
2611 of a class that's not a base class of cls. */
2613 if (PyMethod_GET_SELF(meth
) != NULL
) {
2618 /* No, it is an unbound method */
2619 if (PyMethod_GET_CLASS(meth
) != NULL
&& cls
!= NULL
) {
2620 /* Do subclass test. If it fails, return meth unchanged. */
2621 int ok
= PyObject_IsSubclass(cls
, PyMethod_GET_CLASS(meth
));
2629 /* Bind it to obj */
2630 return PyMethod_New(PyMethod_GET_FUNCTION(meth
), obj
, cls
);
2633 PyTypeObject PyMethod_Type
= {
2634 PyObject_HEAD_INIT(&PyType_Type
)
2637 sizeof(PyMethodObject
),
2639 (destructor
)instancemethod_dealloc
, /* tp_dealloc */
2643 (cmpfunc
)instancemethod_compare
, /* tp_compare */
2644 (reprfunc
)instancemethod_repr
, /* tp_repr */
2645 0, /* tp_as_number */
2646 0, /* tp_as_sequence */
2647 0, /* tp_as_mapping */
2648 (hashfunc
)instancemethod_hash
, /* tp_hash */
2649 instancemethod_call
, /* tp_call */
2651 instancemethod_getattro
, /* tp_getattro */
2652 PyObject_GenericSetAttr
, /* tp_setattro */
2653 0, /* tp_as_buffer */
2654 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
2655 instancemethod_doc
, /* tp_doc */
2656 (traverseproc
)instancemethod_traverse
, /* tp_traverse */
2658 0, /* tp_richcompare */
2659 offsetof(PyMethodObject
, im_weakreflist
), /* tp_weaklistoffset */
2661 0, /* tp_iternext */
2663 instancemethod_memberlist
, /* tp_members */
2664 instancemethod_getset
, /* tp_getset */
2667 instancemethod_descr_get
, /* tp_descr_get */
2668 0, /* tp_descr_set */
2669 0, /* tp_dictoffset */
2672 instancemethod_new
, /* tp_new */
2675 /* Clear out the free list */
2678 PyMethod_ClearFreeList(void)
2680 int freelist_size
= numfree
;
2683 PyMethodObject
*im
= free_list
;
2684 free_list
= (PyMethodObject
*)(im
->im_self
);
2685 PyObject_GC_Del(im
);
2688 assert(numfree
== 0);
2689 return freelist_size
;
2695 (void)PyMethod_ClearFreeList();