1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Class object implementation */
35 #include "structmember.h"
38 static PyObject
*class_lookup
39 Py_PROTO((PyClassObject
*, PyObject
*, PyClassObject
**));
40 static PyObject
*instance_getattr1
Py_PROTO((PyInstanceObject
*, PyObject
*));
42 static PyObject
*getattrstr
, *setattrstr
, *delattrstr
;
45 PyClass_New(bases
, dict
, name
)
46 PyObject
*bases
; /* NULL or tuple of classobjects! */
50 PyClassObject
*op
, *dummy
;
51 static PyObject
*docstr
, *modstr
, *namestr
;
53 docstr
= PyString_InternFromString("__doc__");
58 modstr
= PyString_InternFromString("__module__");
62 if (namestr
== NULL
) {
63 namestr
= PyString_InternFromString("__name__");
67 if (name
== NULL
|| !PyString_Check(name
)) {
68 PyErr_SetString(PyExc_SystemError
,
69 "PyClass_New: name must be a string");
72 if (dict
== NULL
|| !PyDict_Check(dict
)) {
73 PyErr_SetString(PyExc_SystemError
,
74 "PyClass_New: dict must be a dictionary");
77 if (PyDict_GetItem(dict
, docstr
) == NULL
) {
78 if (PyDict_SetItem(dict
, docstr
, Py_None
) < 0)
81 if (PyDict_GetItem(dict
, modstr
) == NULL
) {
82 PyObject
*globals
= PyEval_GetGlobals();
83 if (globals
!= NULL
) {
84 PyObject
*modname
= PyDict_GetItem(globals
, namestr
);
85 if (modname
!= NULL
) {
86 if (PyDict_SetItem(dict
, modstr
, modname
) < 0)
92 bases
= PyTuple_New(0);
98 if (!PyTuple_Check(bases
)) {
99 PyErr_SetString(PyExc_SystemError
,
100 "PyClass_New: bases must be a tuple");
103 i
= PyTuple_Size(bases
);
105 if (!PyClass_Check(PyTuple_GetItem(bases
, i
))) {
106 PyErr_SetString(PyExc_SystemError
,
107 "PyClass_New: base must be a class");
113 op
= PyObject_NEW(PyClassObject
, &PyClass_Type
);
118 op
->cl_bases
= bases
;
123 if (getattrstr
== NULL
) {
124 getattrstr
= PyString_InternFromString("__getattr__");
125 setattrstr
= PyString_InternFromString("__setattr__");
126 delattrstr
= PyString_InternFromString("__delattr__");
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 return (PyObject
*) op
;
143 Py_DECREF(op
->cl_bases
);
144 Py_DECREF(op
->cl_dict
);
145 Py_XDECREF(op
->cl_name
);
146 Py_XDECREF(op
->cl_getattr
);
147 Py_XDECREF(op
->cl_setattr
);
148 Py_XDECREF(op
->cl_delattr
);
153 class_lookup(cp
, name
, pclass
)
156 PyClassObject
**pclass
;
159 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
164 n
= PyTuple_Size(cp
->cl_bases
);
165 for (i
= 0; i
< n
; i
++) {
166 /* XXX What if one of the bases is not a class? */
167 PyObject
*v
= class_lookup(
169 PyTuple_GetItem(cp
->cl_bases
, i
), name
, pclass
);
177 class_getattr(op
, name
)
178 register PyClassObject
*op
;
181 register PyObject
*v
;
182 register char *sname
= PyString_AsString(name
);
183 PyClassObject
*class;
184 if (sname
[0] == '_' && sname
[1] == '_') {
185 if (strcmp(sname
, "__dict__") == 0) {
186 if (PyEval_GetRestricted()) {
187 PyErr_SetString(PyExc_RuntimeError
,
188 "class.__dict__ not accessible in restricted mode");
191 Py_INCREF(op
->cl_dict
);
194 if (strcmp(sname
, "__bases__") == 0) {
195 Py_INCREF(op
->cl_bases
);
198 if (strcmp(sname
, "__name__") == 0) {
199 if (op
->cl_name
== NULL
)
207 v
= class_lookup(op
, name
, &class);
209 PyErr_SetObject(PyExc_AttributeError
, name
);
213 if (PyFunction_Check(v
)) {
214 PyObject
*w
= PyMethod_New(v
, (PyObject
*)NULL
,
227 PyObject
*temp
= *slot
;
237 PyClassObject
*dummy
;
239 set_slot(&c
->cl_getattr
, class_lookup(c
, getattrstr
, &dummy
));
240 set_slot(&c
->cl_setattr
, class_lookup(c
, setattrstr
, &dummy
));
241 set_slot(&c
->cl_delattr
, class_lookup(c
, delattrstr
, &dummy
));
249 if (v
== NULL
|| !PyDict_Check(v
))
250 return "__dict__ must be a dictionary object";
251 set_slot(&c
->cl_dict
, v
);
263 if (v
== NULL
|| !PyTuple_Check(v
))
264 return "__bases__ must be a tuple object";
266 for (i
= 0; i
< n
; i
++) {
267 PyObject
*x
= PyTuple_GET_ITEM(v
, i
);
268 if (!PyClass_Check(x
))
269 return "__bases__ items must be classes";
270 if (PyClass_IsSubclass(x
, (PyObject
*)c
))
271 return "a __bases__ item causes an inheritance cycle";
273 set_slot(&c
->cl_bases
, v
);
283 if (v
== NULL
|| !PyString_Check(v
))
284 return "__name__ must be a string object";
285 if ((long)strlen(PyString_AS_STRING(v
)) != PyString_GET_SIZE(v
))
286 return "__name__ must not contain null bytes";
287 set_slot(&c
->cl_name
, v
);
292 class_setattr(op
, name
, v
)
298 if (PyEval_GetRestricted()) {
299 PyErr_SetString(PyExc_RuntimeError
,
300 "classes are read-only in restricted mode");
303 sname
= PyString_AsString(name
);
304 if (sname
[0] == '_' && sname
[1] == '_') {
305 int n
= PyString_Size(name
);
306 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
308 if (strcmp(sname
, "__dict__") == 0)
309 err
= set_dict(op
, v
);
310 else if (strcmp(sname
, "__bases__") == 0)
311 err
= set_bases(op
, v
);
312 else if (strcmp(sname
, "__name__") == 0)
313 err
= set_name(op
, v
);
314 else if (strcmp(sname
, "__getattr__") == 0)
315 set_slot(&op
->cl_getattr
, v
);
316 else if (strcmp(sname
, "__setattr__") == 0)
317 set_slot(&op
->cl_setattr
, v
);
318 else if (strcmp(sname
, "__delattr__") == 0)
319 set_slot(&op
->cl_delattr
, v
);
320 /* For the last three, we fall through to update the
321 dictionary as well. */
325 PyErr_SetString(PyExc_TypeError
, err
);
331 int rv
= PyDict_DelItem(op
->cl_dict
, name
);
333 PyErr_SetString(PyExc_AttributeError
,
334 "delete non-existing class attribute");
338 return PyDict_SetItem(op
->cl_dict
, name
, v
);
345 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
348 if (op
->cl_name
== NULL
|| !PyString_Check(op
->cl_name
))
351 name
= PyString_AsString(op
->cl_name
);
352 if (mod
== NULL
|| !PyString_Check(mod
))
353 sprintf(buf
, "<class ?.%.100s at %lx>", name
, (long)op
);
355 sprintf(buf
, "<class %.50s.%.50s at %lx>",
356 PyString_AsString(mod
),
358 return PyString_FromString(buf
);
365 PyObject
*mod
= PyDict_GetItemString(op
->cl_dict
, "__module__");
366 PyObject
*name
= op
->cl_name
;
370 if (name
== NULL
|| !PyString_Check(name
))
371 return class_repr(op
);
372 if (mod
== NULL
|| !PyString_Check(mod
)) {
376 m
= PyString_Size(mod
);
377 n
= PyString_Size(name
);
378 res
= PyString_FromStringAndSize((char *)NULL
, m
+1+n
);
380 char *s
= PyString_AsString(res
);
381 memcpy(s
, PyString_AsString(mod
), m
);
384 memcpy(s
, PyString_AsString(name
), n
);
389 PyTypeObject PyClass_Type
= {
390 PyObject_HEAD_INIT(&PyType_Type
)
393 sizeof(PyClassObject
),
395 (destructor
)class_dealloc
, /*tp_dealloc*/
400 (reprfunc
)class_repr
, /*tp_repr*/
402 0, /*tp_as_sequence*/
406 (reprfunc
)class_str
, /*tp_str*/
407 (getattrofunc
)class_getattr
, /*tp_getattro*/
408 (setattrofunc
)class_setattr
, /*tp_setattro*/
412 PyClass_IsSubclass(class, base
)
420 if (class == NULL
|| !PyClass_Check(class))
422 cp
= (PyClassObject
*)class;
423 n
= PyTuple_Size(cp
->cl_bases
);
424 for (i
= 0; i
< n
; i
++) {
425 if (PyClass_IsSubclass(PyTuple_GetItem(cp
->cl_bases
, i
), base
))
432 /* Instance objects */
435 PyInstance_New(class, arg
, kw
)
440 register PyInstanceObject
*inst
;
442 static PyObject
*initstr
;
443 if (!PyClass_Check(class)) {
444 PyErr_BadInternalCall();
447 inst
= PyObject_NEW(PyInstanceObject
, &PyInstance_Type
);
451 inst
->in_class
= (PyClassObject
*)class;
452 inst
->in_dict
= PyDict_New();
453 if (inst
->in_dict
== NULL
) {
458 initstr
= PyString_InternFromString("__init__");
459 init
= instance_getattr1(inst
, initstr
);
462 if ((arg
!= NULL
&& (!PyTuple_Check(arg
) ||
463 PyTuple_Size(arg
) != 0))
464 || (kw
!= NULL
&& (!PyDict_Check(kw
) ||
465 PyDict_Size(kw
) != 0))) {
466 PyErr_SetString(PyExc_TypeError
,
467 "this constructor takes no arguments");
473 PyObject
*res
= PyEval_CallObjectWithKeywords(init
, arg
, kw
);
480 if (res
!= Py_None
) {
481 PyErr_SetString(PyExc_TypeError
,
482 "__init__() should return None");
489 return (PyObject
*)inst
;
492 /* Instance methods */
495 instance_dealloc(inst
)
496 register PyInstanceObject
*inst
;
498 PyObject
*error_type
, *error_value
, *error_traceback
;
500 static PyObject
*delstr
;
501 /* Call the __del__ method if it exists. First temporarily
502 revive the object and save the current exception, if any. */
504 /* much too complicated if Py_TRACE_REFS defined */
505 extern long _Py_RefTotal
;
506 inst
->ob_type
= &PyInstance_Type
;
507 _Py_NewReference((PyObject
*)inst
);
508 _Py_RefTotal
--; /* compensate for increment in NEWREF */
510 inst
->ob_type
->tp_alloc
--; /* ditto */
512 #else /* !Py_TRACE_REFS */
514 #endif /* !Py_TRACE_REFS */
515 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
517 delstr
= PyString_InternFromString("__del__");
518 if ((del
= instance_getattr1(inst
, delstr
)) != NULL
) {
519 PyObject
*res
= PyEval_CallObject(del
, (PyObject
*)NULL
);
521 PyObject
*f
, *t
, *v
, *tb
;
522 PyErr_Fetch(&t
, &v
, &tb
);
523 f
= PySys_GetObject("stderr");
525 PyFile_WriteString("Exception ", f
);
527 PyFile_WriteObject(t
, f
, Py_PRINT_RAW
);
528 if (v
&& v
!= Py_None
) {
529 PyFile_WriteString(": ", f
);
530 PyFile_WriteObject(v
, f
, 0);
533 PyFile_WriteString(" in ", f
);
534 PyFile_WriteObject(del
, f
, 0);
535 PyFile_WriteString(" ignored\n", f
);
536 PyErr_Clear(); /* Just in case */
546 /* Restore the saved exception and undo the temporary revival */
547 PyErr_Restore(error_type
, error_value
, error_traceback
);
548 /* Can't use DECREF here, it would cause a recursive call */
549 if (--inst
->ob_refcnt
> 0) {
551 inst
->ob_type
->tp_free
--;
553 return; /* __del__ added a reference; don't delete now */
557 inst
->ob_type
->tp_free
--; /* compensate for increment in UNREF */
559 _Py_ForgetReference((PyObject
*)inst
);
560 inst
->ob_type
= NULL
;
561 #endif /* Py_TRACE_REFS */
562 Py_DECREF(inst
->in_class
);
563 Py_XDECREF(inst
->in_dict
);
568 instance_getattr1(inst
, name
)
569 register PyInstanceObject
*inst
;
572 register PyObject
*v
;
573 register char *sname
= PyString_AsString(name
);
574 PyClassObject
*class;
575 if (sname
[0] == '_' && sname
[1] == '_') {
576 if (strcmp(sname
, "__dict__") == 0) {
577 if (PyEval_GetRestricted()) {
578 PyErr_SetString(PyExc_RuntimeError
,
579 "instance.__dict__ not accessible in restricted mode");
582 Py_INCREF(inst
->in_dict
);
583 return inst
->in_dict
;
585 if (strcmp(sname
, "__class__") == 0) {
586 Py_INCREF(inst
->in_class
);
587 return (PyObject
*)inst
->in_class
;
591 v
= PyDict_GetItem(inst
->in_dict
, name
);
593 v
= class_lookup(inst
->in_class
, name
, &class);
595 PyErr_SetObject(PyExc_AttributeError
, name
);
601 if (PyFunction_Check(v
)) {
602 PyObject
*w
= PyMethod_New(v
, (PyObject
*)inst
,
607 else if (PyMethod_Check(v
)) {
608 PyObject
*im_class
= PyMethod_Class(v
);
609 /* Only if classes are compatible */
610 if (PyClass_IsSubclass((PyObject
*)class, im_class
)) {
611 PyObject
*im_func
= PyMethod_Function(v
);
612 PyObject
*w
= PyMethod_New(im_func
,
613 (PyObject
*)inst
, im_class
);
623 instance_getattr(inst
, name
)
624 register PyInstanceObject
*inst
;
627 register PyObject
*func
, *res
;
628 res
= instance_getattr1(inst
, name
);
629 if (res
== NULL
&& (func
= inst
->in_class
->cl_getattr
) != NULL
) {
632 args
= Py_BuildValue("(OO)", inst
, name
);
635 res
= PyEval_CallObject(func
, args
);
642 instance_setattr1(inst
, name
, v
)
643 PyInstanceObject
*inst
;
648 int rv
= PyDict_DelItem(inst
->in_dict
, name
);
650 PyErr_SetString(PyExc_AttributeError
,
651 "delete non-existing instance attribute");
655 return PyDict_SetItem(inst
->in_dict
, name
, v
);
659 instance_setattr(inst
, name
, v
)
660 PyInstanceObject
*inst
;
664 PyObject
*func
, *args
, *res
, *tmp
;
665 char *sname
= PyString_AsString(name
);
666 if (sname
[0] == '_' && sname
[1] == '_') {
667 int n
= PyString_Size(name
);
668 if (sname
[n
-1] == '_' && sname
[n
-2] == '_') {
669 if (strcmp(sname
, "__dict__") == 0) {
670 if (PyEval_GetRestricted()) {
671 PyErr_SetString(PyExc_RuntimeError
,
672 "__dict__ not accessible in restricted mode");
675 if (v
== NULL
|| !PyDict_Check(v
)) {
676 PyErr_SetString(PyExc_TypeError
,
677 "__dict__ must be set to a dictionary");
686 if (strcmp(sname
, "__class__") == 0) {
687 if (PyEval_GetRestricted()) {
688 PyErr_SetString(PyExc_RuntimeError
,
689 "__class__ not accessible in restricted mode");
692 if (v
== NULL
|| !PyClass_Check(v
)) {
693 PyErr_SetString(PyExc_TypeError
,
694 "__class__ must be set to a class");
697 tmp
= (PyObject
*)(inst
->in_class
);
699 inst
->in_class
= (PyClassObject
*)v
;
706 func
= inst
->in_class
->cl_delattr
;
708 func
= inst
->in_class
->cl_setattr
;
710 return instance_setattr1(inst
, name
, v
);
712 args
= Py_BuildValue("(OO)", inst
, name
);
714 args
= Py_BuildValue("(OOO)", inst
, name
, v
);
717 res
= PyEval_CallObject(func
, args
);
727 PyInstanceObject
*inst
;
731 static PyObject
*reprstr
;
734 reprstr
= PyString_InternFromString("__repr__");
735 func
= instance_getattr(inst
, reprstr
);
738 PyObject
*classname
= inst
->in_class
->cl_name
;
739 PyObject
*mod
= PyDict_GetItemString(
740 inst
->in_class
->cl_dict
, "__module__");
742 if (classname
!= NULL
&& PyString_Check(classname
))
743 cname
= PyString_AsString(classname
);
747 if (mod
== NULL
|| !PyString_Check(mod
))
748 sprintf(buf
, "<?.%.100s instance at %lx>",
751 sprintf(buf
, "<%.50s.%.50s instance at %lx>",
752 PyString_AsString(mod
),
754 return PyString_FromString(buf
);
756 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
762 instance_compare1(inst
, other
)
763 PyObject
*inst
, *other
;
765 return PyInstance_DoBinOp(inst
, other
, "__cmp__", "__rcmp__",
770 instance_compare(inst
, other
)
771 PyObject
*inst
, *other
;
775 result
= instance_compare1(inst
, other
);
778 if (!PyInt_Check(result
)) {
780 PyErr_SetString(PyExc_TypeError
,
781 "comparison did not return an int");
784 outcome
= PyInt_AsLong(result
);
788 else if (outcome
> 0)
795 PyInstanceObject
*inst
;
800 static PyObject
*hashstr
, *cmpstr
;
803 hashstr
= PyString_InternFromString("__hash__");
804 func
= instance_getattr(inst
, hashstr
);
806 /* If there is no __cmp__ method, we hash on the address.
807 If a __cmp__ method exists, there must be a __hash__. */
810 cmpstr
= PyString_InternFromString("__cmp__");
811 func
= instance_getattr(inst
, cmpstr
);
814 outcome
= (long)inst
;
819 PyErr_SetString(PyExc_TypeError
, "unhashable instance");
822 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
826 if (PyInt_Check(res
)) {
827 outcome
= PyInt_AsLong(res
);
832 PyErr_SetString(PyExc_TypeError
,
833 "__hash__() should return an int");
840 static PyObject
*getitemstr
, *setitemstr
, *delitemstr
, *lenstr
;
843 instance_length(inst
)
844 PyInstanceObject
*inst
;
851 lenstr
= PyString_InternFromString("__len__");
852 func
= instance_getattr(inst
, lenstr
);
855 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
859 if (PyInt_Check(res
)) {
860 outcome
= PyInt_AsLong(res
);
862 PyErr_SetString(PyExc_ValueError
,
863 "__len__() should return >= 0");
866 PyErr_SetString(PyExc_TypeError
,
867 "__len__() should return an int");
875 instance_subscript(inst
, key
)
876 PyInstanceObject
*inst
;
883 if (getitemstr
== NULL
)
884 getitemstr
= PyString_InternFromString("__getitem__");
885 func
= instance_getattr(inst
, getitemstr
);
888 arg
= Py_BuildValue("(O)", key
);
893 res
= PyEval_CallObject(func
, arg
);
900 instance_ass_subscript(inst
, key
, value
)
901 PyInstanceObject
*inst
;
910 if (delitemstr
== NULL
)
911 delitemstr
= PyString_InternFromString("__delitem__");
912 func
= instance_getattr(inst
, delitemstr
);
915 if (setitemstr
== NULL
)
916 setitemstr
= PyString_InternFromString("__setitem__");
917 func
= instance_getattr(inst
, setitemstr
);
922 arg
= Py_BuildValue("(O)", key
);
924 arg
= Py_BuildValue("(OO)", key
, value
);
929 res
= PyEval_CallObject(func
, arg
);
938 static PyMappingMethods instance_as_mapping
= {
939 (inquiry
)instance_length
, /*mp_length*/
940 (binaryfunc
)instance_subscript
, /*mp_subscript*/
941 (objobjargproc
)instance_ass_subscript
, /*mp_ass_subscript*/
945 instance_item(inst
, i
)
946 PyInstanceObject
*inst
;
949 PyObject
*func
, *arg
, *res
;
951 if (getitemstr
== NULL
)
952 getitemstr
= PyString_InternFromString("__getitem__");
953 func
= instance_getattr(inst
, getitemstr
);
956 arg
= Py_BuildValue("(i)", i
);
961 res
= PyEval_CallObject(func
, arg
);
968 instance_slice(inst
, i
, j
)
969 PyInstanceObject
*inst
;
972 PyObject
*func
, *arg
, *res
;
973 static PyObject
*getslicestr
;
975 if (getslicestr
== NULL
)
976 getslicestr
= PyString_InternFromString("__getslice__");
977 func
= instance_getattr(inst
, getslicestr
);
980 arg
= Py_BuildValue("(ii)", i
, j
);
985 res
= PyEval_CallObject(func
, arg
);
992 instance_ass_item(inst
, i
, item
)
993 PyInstanceObject
*inst
;
997 PyObject
*func
, *arg
, *res
;
1000 if (delitemstr
== NULL
)
1001 delitemstr
= PyString_InternFromString("__delitem__");
1002 func
= instance_getattr(inst
, delitemstr
);
1005 if (setitemstr
== NULL
)
1006 setitemstr
= PyString_InternFromString("__setitem__");
1007 func
= instance_getattr(inst
, setitemstr
);
1012 arg
= Py_BuildValue("i", i
);
1014 arg
= Py_BuildValue("(iO)", i
, item
);
1019 res
= PyEval_CallObject(func
, arg
);
1029 instance_ass_slice(inst
, i
, j
, value
)
1030 PyInstanceObject
*inst
;
1034 PyObject
*func
, *arg
, *res
;
1035 static PyObject
*setslicestr
, *delslicestr
;
1037 if (value
== NULL
) {
1038 if (delslicestr
== NULL
)
1040 PyString_InternFromString("__delslice__");
1041 func
= instance_getattr(inst
, delslicestr
);
1044 if (setslicestr
== NULL
)
1046 PyString_InternFromString("__setslice__");
1047 func
= instance_getattr(inst
, setslicestr
);
1052 arg
= Py_BuildValue("(ii)", i
, j
);
1054 arg
= Py_BuildValue("(iiO)", i
, j
, value
);
1059 res
= PyEval_CallObject(func
, arg
);
1068 static PySequenceMethods instance_as_sequence
= {
1069 (inquiry
)instance_length
, /*sq_length*/
1072 (intargfunc
)instance_item
, /*sq_item*/
1073 (intintargfunc
)instance_slice
, /*sq_slice*/
1074 (intobjargproc
)instance_ass_item
, /*sq_ass_item*/
1075 (intintobjargproc
)instance_ass_slice
, /*sq_ass_slice*/
1079 generic_unary_op(self
, methodname
)
1080 PyInstanceObject
*self
;
1081 PyObject
*methodname
;
1083 PyObject
*func
, *res
;
1085 if ((func
= instance_getattr(self
, methodname
)) == NULL
)
1087 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1094 static int halfbinop
Py_PROTO((PyObject
*, PyObject
*, char *, PyObject
**,
1095 PyObject
* (*) Py_PROTO((PyObject
*, PyObject
*)), int ));
1098 /* Implement a binary operator involving at least one class instance. */
1101 PyInstance_DoBinOp(v
, w
, opname
, ropname
, thisfunc
)
1106 PyObject
* (*thisfunc
) Py_PROTO((PyObject
*, PyObject
*));
1109 PyObject
*result
= NULL
;
1110 if (halfbinop(v
, w
, opname
, &result
, thisfunc
, 0) <= 0)
1112 if (halfbinop(w
, v
, ropname
, &result
, thisfunc
, 1) <= 0)
1114 /* Sigh -- special case for comnparisons */
1115 if (strcmp(opname
, "__cmp__") == 0) {
1116 long c
= (v
< w
) ? -1 : (v
> w
) ? 1 : 0;
1117 return PyInt_FromLong(c
);
1119 sprintf(buf
, "%s nor %s defined for these operands", opname
, ropname
);
1120 PyErr_SetString(PyExc_TypeError
, buf
);
1125 /* Try one half of a binary operator involving a class instance.
1127 -1 if an exception is to be reported right away
1128 0 if we have a valid result
1129 1 if we could try another operation
1132 static PyObject
*coerce_obj
;
1135 halfbinop(v
, w
, opname
, r_result
, thisfunc
, swapped
)
1139 PyObject
**r_result
;
1140 PyObject
* (*thisfunc
) Py_PROTO((PyObject
*, PyObject
*));
1145 PyObject
*coercefunc
;
1146 PyObject
*coerced
= NULL
;
1149 if (!PyInstance_Check(v
))
1151 if (coerce_obj
== NULL
) {
1152 coerce_obj
= PyString_InternFromString("__coerce__");
1153 if (coerce_obj
== NULL
)
1156 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1157 if (coercefunc
== NULL
) {
1161 args
= Py_BuildValue("(O)", w
);
1165 coerced
= PyEval_CallObject(coercefunc
, args
);
1167 Py_DECREF(coercefunc
);
1168 if (coerced
== NULL
) {
1171 if (coerced
== Py_None
) {
1175 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1177 PyErr_SetString(PyExc_TypeError
,
1178 "coercion should return None or 2-tuple");
1181 v1
= PyTuple_GetItem(coerced
, 0);
1182 w
= PyTuple_GetItem(coerced
, 1);
1185 if (!PyInstance_Check(v
) && !PyInstance_Check(w
)) {
1187 *r_result
= (*thisfunc
)(w
, v
);
1189 *r_result
= (*thisfunc
)(v
, w
);
1191 return *r_result
== NULL
? -1 : 0;
1195 func
= PyObject_GetAttrString(v
, opname
);
1197 Py_XDECREF(coerced
);
1198 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
1203 args
= Py_BuildValue("(O)", w
);
1206 Py_XDECREF(coerced
);
1209 *r_result
= PyEval_CallObject(func
, args
);
1212 Py_XDECREF(coerced
);
1213 return *r_result
== NULL
? -1 : 0;
1217 instance_coerce(pv
, pw
)
1223 PyObject
*coercefunc
;
1227 if (coerce_obj
== NULL
) {
1228 coerce_obj
= PyString_InternFromString("__coerce__");
1229 if (coerce_obj
== NULL
)
1232 coercefunc
= PyObject_GetAttr(v
, coerce_obj
);
1233 if (coercefunc
== NULL
) {
1234 /* No __coerce__ method: always OK */
1240 /* Has __coerce__ method: call it */
1241 args
= Py_BuildValue("(O)", w
);
1245 coerced
= PyEval_CallObject(coercefunc
, args
);
1247 Py_DECREF(coercefunc
);
1248 if (coerced
== NULL
) {
1249 /* __coerce__ call raised an exception */
1252 if (coerced
== Py_None
) {
1253 /* __coerce__ says "I can't do it" */
1257 if (!PyTuple_Check(coerced
) || PyTuple_Size(coerced
) != 2) {
1258 /* __coerce__ return value is malformed */
1260 PyErr_SetString(PyExc_TypeError
,
1261 "coercion should return None or 2-tuple");
1264 /* __coerce__ returned two new values */
1265 *pv
= PyTuple_GetItem(coerced
, 0);
1266 *pw
= PyTuple_GetItem(coerced
, 1);
1274 #define UNARY(funcname, methodname) \
1275 static PyObject *funcname(self) PyInstanceObject *self; { \
1276 static PyObject *o; \
1277 if (o == NULL) o = PyString_InternFromString(methodname); \
1278 return generic_unary_op(self, o); \
1281 UNARY(instance_neg
, "__neg__")
1282 UNARY(instance_pos
, "__pos__")
1283 UNARY(instance_abs
, "__abs__")
1286 instance_nonzero(self
)
1287 PyInstanceObject
*self
;
1289 PyObject
*func
, *res
;
1291 static PyObject
*nonzerostr
;
1293 if (nonzerostr
== NULL
)
1294 nonzerostr
= PyString_InternFromString("__nonzero__");
1295 if ((func
= instance_getattr(self
, nonzerostr
)) == NULL
) {
1298 lenstr
= PyString_InternFromString("__len__");
1299 if ((func
= instance_getattr(self
, lenstr
)) == NULL
) {
1301 /* Fall back to the default behavior:
1302 all instances are nonzero */
1306 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
1310 if (!PyInt_Check(res
)) {
1312 PyErr_SetString(PyExc_TypeError
,
1313 "__nonzero__ should return an int");
1316 outcome
= PyInt_AsLong(res
);
1319 PyErr_SetString(PyExc_ValueError
,
1320 "__nonzero__ should return >= 0");
1326 UNARY(instance_invert
, "__invert__")
1327 UNARY(instance_int
, "__int__")
1328 UNARY(instance_long
, "__long__")
1329 UNARY(instance_float
, "__float__")
1330 UNARY(instance_oct
, "__oct__")
1331 UNARY(instance_hex
, "__hex__")
1333 /* This version is for ternary calls only (z != None) */
1335 instance_pow(v
, w
, z
)
1340 /* XXX Doesn't do coercions... */
1344 static PyObject
*powstr
;
1347 powstr
= PyString_InternFromString("__pow__");
1348 func
= PyObject_GetAttr(v
, powstr
);
1351 args
= Py_BuildValue("(OO)", w
, z
);
1356 result
= PyEval_CallObject(func
, args
);
1362 static PyNumberMethods instance_as_number
= {
1369 (ternaryfunc
)instance_pow
, /*nb_power*/
1370 (unaryfunc
)instance_neg
, /*nb_negative*/
1371 (unaryfunc
)instance_pos
, /*nb_positive*/
1372 (unaryfunc
)instance_abs
, /*nb_absolute*/
1373 (inquiry
)instance_nonzero
, /*nb_nonzero*/
1374 (unaryfunc
)instance_invert
, /*nb_invert*/
1380 (coercion
)instance_coerce
, /*nb_coerce*/
1381 (unaryfunc
)instance_int
, /*nb_int*/
1382 (unaryfunc
)instance_long
, /*nb_long*/
1383 (unaryfunc
)instance_float
, /*nb_float*/
1384 (unaryfunc
)instance_oct
, /*nb_oct*/
1385 (unaryfunc
)instance_hex
, /*nb_hex*/
1388 PyTypeObject PyInstance_Type
= {
1389 PyObject_HEAD_INIT(&PyType_Type
)
1392 sizeof(PyInstanceObject
),
1394 (destructor
)instance_dealloc
, /*tp_dealloc*/
1398 instance_compare
, /*tp_compare*/
1399 (reprfunc
)instance_repr
, /*tp_repr*/
1400 &instance_as_number
, /*tp_as_number*/
1401 &instance_as_sequence
, /*tp_as_sequence*/
1402 &instance_as_mapping
, /*tp_as_mapping*/
1403 (hashfunc
)instance_hash
, /*tp_hash*/
1406 (getattrofunc
)instance_getattr
, /*tp_getattro*/
1407 (setattrofunc
)instance_setattr
, /*tp_setattro*/
1411 /* Instance method objects are used for two purposes:
1412 (a) as bound instance methods (returned by instancename.methodname)
1413 (b) as unbound methods (returned by ClassName.methodname)
1414 In case (b), im_self is NULL
1417 static PyMethodObject
*free_list
;
1420 PyMethod_New(func
, self
, class)
1425 register PyMethodObject
*im
;
1426 if (!PyCallable_Check(func
)) {
1427 PyErr_BadInternalCall();
1432 free_list
= (PyMethodObject
*)(im
->im_self
);
1433 im
->ob_type
= &PyMethod_Type
;
1434 _Py_NewReference((PyObject
*)im
);
1437 im
= PyObject_NEW(PyMethodObject
, &PyMethod_Type
);
1446 im
->im_class
= class;
1447 return (PyObject
*)im
;
1451 PyMethod_Function(im
)
1452 register PyObject
*im
;
1454 if (!PyMethod_Check(im
)) {
1455 PyErr_BadInternalCall();
1458 return ((PyMethodObject
*)im
)->im_func
;
1463 register PyObject
*im
;
1465 if (!PyMethod_Check(im
)) {
1466 PyErr_BadInternalCall();
1469 return ((PyMethodObject
*)im
)->im_self
;
1474 register PyObject
*im
;
1476 if (!PyMethod_Check(im
)) {
1477 PyErr_BadInternalCall();
1480 return ((PyMethodObject
*)im
)->im_class
;
1483 /* Class method methods */
1485 #define OFF(x) offsetof(PyMethodObject, x)
1487 static struct memberlist instancemethod_memberlist
[] = {
1488 {"im_func", T_OBJECT
, OFF(im_func
)},
1489 {"im_self", T_OBJECT
, OFF(im_self
)},
1490 {"im_class", T_OBJECT
, OFF(im_class
)},
1491 /* Dummies that are not handled by getattr() except for __members__ */
1492 {"__doc__", T_INT
, 0},
1493 {"__name__", T_INT
, 0},
1494 {NULL
} /* Sentinel */
1498 instancemethod_getattr(im
, name
)
1499 register PyMethodObject
*im
;
1502 char *sname
= PyString_AsString(name
);
1503 if (sname
[0] == '_') {
1504 /* Inherit __name__ and __doc__ from the callable object
1505 implementing the method */
1506 if (strcmp(sname
, "__name__") == 0 ||
1507 strcmp(sname
, "__doc__") == 0)
1508 return PyObject_GetAttr(im
->im_func
, name
);
1510 if (PyEval_GetRestricted()) {
1511 PyErr_SetString(PyExc_RuntimeError
,
1512 "instance-method attributes not accessible in restricted mode");
1515 return PyMember_Get((char *)im
, instancemethod_memberlist
, sname
);
1519 instancemethod_dealloc(im
)
1520 register PyMethodObject
*im
;
1522 Py_DECREF(im
->im_func
);
1523 Py_XDECREF(im
->im_self
);
1524 Py_DECREF(im
->im_class
);
1525 im
->im_self
= (PyObject
*)free_list
;
1530 instancemethod_compare(a
, b
)
1531 PyMethodObject
*a
, *b
;
1533 if (a
->im_self
!= b
->im_self
)
1534 return (a
->im_self
< b
->im_self
) ? -1 : 1;
1535 return PyObject_Compare(a
->im_func
, b
->im_func
);
1539 instancemethod_repr(a
)
1543 PyInstanceObject
*self
= (PyInstanceObject
*)(a
->im_self
);
1544 PyObject
*func
= a
->im_func
;
1545 PyClassObject
*class = (PyClassObject
*)(a
->im_class
);
1546 PyObject
*fclassname
, *iclassname
, *funcname
;
1547 char *fcname
, *icname
, *fname
;
1548 fclassname
= class->cl_name
;
1549 if (PyFunction_Check(func
)) {
1550 funcname
= ((PyFunctionObject
*)func
)->func_name
;
1551 Py_INCREF(funcname
);
1554 funcname
= PyObject_GetAttrString(func
,"__name__");
1555 if (funcname
== NULL
)
1558 if (funcname
!= NULL
&& PyString_Check(funcname
))
1559 fname
= PyString_AS_STRING(funcname
);
1562 if (fclassname
!= NULL
&& PyString_Check(fclassname
))
1563 fcname
= PyString_AsString(fclassname
);
1567 sprintf(buf
, "<unbound method %.100s.%.100s>", fcname
, fname
);
1569 iclassname
= self
->in_class
->cl_name
;
1570 if (iclassname
!= NULL
&& PyString_Check(iclassname
))
1571 icname
= PyString_AsString(iclassname
);
1574 sprintf(buf
, "<method %.60s.%.60s of %.60s instance at %lx>",
1575 fcname
, fname
, icname
, (long)self
);
1577 Py_XDECREF(funcname
);
1578 return PyString_FromString(buf
);
1582 instancemethod_hash(a
)
1586 if (a
->im_self
== NULL
)
1587 x
= PyObject_Hash(Py_None
);
1589 x
= PyObject_Hash(a
->im_self
);
1592 y
= PyObject_Hash(a
->im_func
);
1598 PyTypeObject PyMethod_Type
= {
1599 PyObject_HEAD_INIT(&PyType_Type
)
1602 sizeof(PyMethodObject
),
1604 (destructor
)instancemethod_dealloc
, /*tp_dealloc*/
1608 (cmpfunc
)instancemethod_compare
, /*tp_compare*/
1609 (reprfunc
)instancemethod_repr
, /*tp_repr*/
1611 0, /*tp_as_sequence*/
1612 0, /*tp_as_mapping*/
1613 (hashfunc
)instancemethod_hash
, /*tp_hash*/
1616 (getattrofunc
)instancemethod_getattr
, /*tp_getattro*/
1620 /* Clear out the free list */
1626 PyMethodObject
*v
= free_list
;
1627 free_list
= (PyMethodObject
*)(v
->im_self
);