2 /* Type object implementation */
5 #include "structmember.h"
7 static PyMemberDef type_members
[] = {
8 {"__basicsize__", T_INT
, offsetof(PyTypeObject
,tp_basicsize
),READONLY
},
9 {"__itemsize__", T_INT
, offsetof(PyTypeObject
, tp_itemsize
), READONLY
},
10 {"__flags__", T_LONG
, offsetof(PyTypeObject
, tp_flags
), READONLY
},
11 {"__weakrefoffset__", T_LONG
,
12 offsetof(PyTypeObject
, tp_weaklistoffset
), READONLY
},
13 {"__base__", T_OBJECT
, offsetof(PyTypeObject
, tp_base
), READONLY
},
14 {"__dictoffset__", T_LONG
,
15 offsetof(PyTypeObject
, tp_dictoffset
), READONLY
},
16 {"__bases__", T_OBJECT
, offsetof(PyTypeObject
, tp_bases
), READONLY
},
17 {"__mro__", T_OBJECT
, offsetof(PyTypeObject
, tp_mro
), READONLY
},
22 type_name(PyTypeObject
*type
, void *context
)
26 s
= strrchr(type
->tp_name
, '.');
31 return PyString_FromString(s
);
35 type_module(PyTypeObject
*type
, void *context
)
40 s
= strrchr(type
->tp_name
, '.');
42 return PyString_FromStringAndSize(type
->tp_name
,
43 (int)(s
- type
->tp_name
));
44 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
45 return PyString_FromString("__builtin__");
46 mod
= PyDict_GetItemString(type
->tp_dict
, "__module__");
47 if (mod
!= NULL
&& PyString_Check(mod
)) {
51 PyErr_SetString(PyExc_AttributeError
, "__module__");
56 type_set_module(PyTypeObject
*type
, PyObject
*value
, void *context
)
58 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) ||
59 strrchr(type
->tp_name
, '.')) {
60 PyErr_Format(PyExc_TypeError
,
61 "can't set %s.__module__", type
->tp_name
);
65 PyErr_Format(PyExc_TypeError
,
66 "can't delete %s.__module__", type
->tp_name
);
69 return PyDict_SetItemString(type
->tp_dict
, "__module__", value
);
73 type_dict(PyTypeObject
*type
, void *context
)
75 if (type
->tp_dict
== NULL
) {
79 return PyDictProxy_New(type
->tp_dict
);
83 type_get_doc(PyTypeObject
*type
, void *context
)
86 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
87 if (type
->tp_doc
== NULL
) {
91 return PyString_FromString(type
->tp_doc
);
93 result
= PyDict_GetItemString(type
->tp_dict
, "__doc__");
98 static PyGetSetDef type_getsets
[] = {
99 {"__name__", (getter
)type_name
, NULL
, NULL
},
100 {"__module__", (getter
)type_module
, (setter
)type_set_module
, NULL
},
101 {"__dict__", (getter
)type_dict
, NULL
, NULL
},
102 {"__doc__", (getter
)type_get_doc
, NULL
, NULL
},
107 type_compare(PyObject
*v
, PyObject
*w
)
109 /* This is called with type objects only. So we
110 can just compare the addresses. */
111 Py_uintptr_t vv
= (Py_uintptr_t
)v
;
112 Py_uintptr_t ww
= (Py_uintptr_t
)w
;
113 return (vv
< ww
) ? -1 : (vv
> ww
) ? 1 : 0;
117 type_repr(PyTypeObject
*type
)
119 PyObject
*mod
, *name
, *rtn
;
122 mod
= type_module(type
, NULL
);
125 else if (!PyString_Check(mod
)) {
129 name
= type_name(type
, NULL
);
133 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
138 if (mod
!= NULL
&& strcmp(PyString_AS_STRING(mod
), "__builtin__")) {
139 rtn
= PyString_FromFormat("<%s '%s.%s'>",
141 PyString_AS_STRING(mod
),
142 PyString_AS_STRING(name
));
145 rtn
= PyString_FromFormat("<%s '%s'>", kind
, type
->tp_name
);
153 type_call(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
157 if (type
->tp_new
== NULL
) {
158 PyErr_Format(PyExc_TypeError
,
159 "cannot create '%.100s' instances",
164 obj
= type
->tp_new(type
, args
, kwds
);
166 /* Ugly exception: when the call was type(something),
167 don't call tp_init on the result. */
168 if (type
== &PyType_Type
&&
169 PyTuple_Check(args
) && PyTuple_GET_SIZE(args
) == 1 &&
171 (PyDict_Check(kwds
) && PyDict_Size(kwds
) == 0)))
174 if (type
->tp_init
!= NULL
&&
175 type
->tp_init(obj
, args
, kwds
) < 0) {
184 PyType_GenericAlloc(PyTypeObject
*type
, int nitems
)
187 const size_t size
= _PyObject_VAR_SIZE(type
, nitems
);
189 if (PyType_IS_GC(type
))
190 obj
= _PyObject_GC_Malloc(type
, nitems
);
192 obj
= PyObject_MALLOC(size
);
195 return PyErr_NoMemory();
197 memset(obj
, '\0', size
);
199 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
202 if (type
->tp_itemsize
== 0)
203 PyObject_INIT(obj
, type
);
205 (void) PyObject_INIT_VAR((PyVarObject
*)obj
, type
, nitems
);
207 if (PyType_IS_GC(type
))
208 _PyObject_GC_TRACK(obj
);
213 PyType_GenericNew(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
215 return type
->tp_alloc(type
, 0);
218 /* Helpers for subtyping */
221 subtype_traverse(PyObject
*self
, visitproc visit
, void *arg
)
223 PyTypeObject
*type
, *base
;
227 /* Find the nearest base with a different tp_traverse */
228 type
= self
->ob_type
;
229 base
= type
->tp_base
;
230 while ((f
= base
->tp_traverse
) == subtype_traverse
) {
231 base
= base
->tp_base
;
235 if (type
->tp_dictoffset
!= base
->tp_dictoffset
) {
236 PyObject
**dictptr
= _PyObject_GetDictPtr(self
);
237 if (dictptr
&& *dictptr
) {
238 err
= visit(*dictptr
, arg
);
245 return f(self
, visit
, arg
);
249 staticforward PyObject
*lookup_maybe(PyObject
*, char *, PyObject
**);
252 call_finalizer(PyObject
*self
)
254 static PyObject
*del_str
= NULL
;
256 PyObject
*error_type
, *error_value
, *error_traceback
;
258 /* Temporarily resurrect the object. */
261 # error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
263 /* much too complicated if Py_TRACE_REFS defined */
264 _Py_NewReference((PyObject
*)self
);
266 /* compensate for boost in _Py_NewReference; note that
267 * _Py_RefTotal was also boosted; we'll knock that down later.
269 self
->ob_type
->tp_allocs
--;
271 #else /* !Py_TRACE_REFS */
272 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
274 #endif /* !Py_TRACE_REFS */
276 /* Save the current exception, if any. */
277 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
279 /* Execute __del__ method, if any. */
280 del
= lookup_maybe(self
, "__del__", &del_str
);
282 res
= PyEval_CallObject(del
, NULL
);
284 PyErr_WriteUnraisable(del
);
290 /* Restore the saved exception. */
291 PyErr_Restore(error_type
, error_value
, error_traceback
);
293 /* Undo the temporary resurrection; can't use DECREF here, it would
294 * cause a recursive call.
297 /* _Py_RefTotal was boosted either by _Py_NewReference or
302 if (--self
->ob_refcnt
> 0) {
304 self
->ob_type
->tp_frees
--;
306 _PyObject_GC_TRACK(self
);
307 return -1; /* __del__ added a reference; don't delete now */
310 _Py_ForgetReference((PyObject
*)self
);
312 /* compensate for increment in _Py_ForgetReference */
313 self
->ob_type
->tp_frees
--;
321 subtype_dealloc(PyObject
*self
)
323 PyTypeObject
*type
, *base
;
326 /* This exists so we can DECREF self->ob_type */
328 if (call_finalizer(self
) < 0)
331 /* Find the nearest base with a different tp_dealloc */
332 type
= self
->ob_type
;
333 base
= type
->tp_base
;
334 while ((f
= base
->tp_dealloc
) == subtype_dealloc
) {
335 base
= base
->tp_base
;
339 /* Clear __slots__ variables */
340 if (type
->tp_basicsize
!= base
->tp_basicsize
&&
341 type
->tp_itemsize
== 0)
343 char *addr
= ((char *)self
);
344 char *p
= addr
+ base
->tp_basicsize
;
345 char *q
= addr
+ type
->tp_basicsize
;
346 for (; p
< q
; p
+= sizeof(PyObject
*)) {
348 if (p
== addr
+ type
->tp_dictoffset
||
349 p
== addr
+ type
->tp_weaklistoffset
)
359 /* If we added a dict, DECREF it */
360 if (type
->tp_dictoffset
&& !base
->tp_dictoffset
) {
361 PyObject
**dictptr
= _PyObject_GetDictPtr(self
);
362 if (dictptr
!= NULL
) {
363 PyObject
*dict
= *dictptr
;
371 /* If we added weaklist, we clear it */
372 if (type
->tp_weaklistoffset
&& !base
->tp_weaklistoffset
)
373 PyObject_ClearWeakRefs(self
);
375 /* Finalize GC if the base doesn't do GC and we do */
376 if (PyType_IS_GC(type
) && !PyType_IS_GC(base
))
377 _PyObject_GC_UNTRACK(self
);
379 /* Call the base tp_dealloc() */
383 /* Can't reference self beyond this point */
384 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
389 staticforward PyTypeObject
*solid_base(PyTypeObject
*type
);
393 PyNumberMethods as_number
;
394 PySequenceMethods as_sequence
;
395 PyMappingMethods as_mapping
;
396 PyBufferProcs as_buffer
;
397 PyObject
*name
, *slots
;
398 PyMemberDef members
[1];
401 /* type test with subclassing support */
404 PyType_IsSubtype(PyTypeObject
*a
, PyTypeObject
*b
)
408 if (!(a
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
))
409 return b
== a
|| b
== &PyBaseObject_Type
;
413 /* Deal with multiple inheritance without recursion
414 by walking the MRO tuple */
416 assert(PyTuple_Check(mro
));
417 n
= PyTuple_GET_SIZE(mro
);
418 for (i
= 0; i
< n
; i
++) {
419 if (PyTuple_GET_ITEM(mro
, i
) == (PyObject
*)b
)
425 /* a is not completely initilized yet; follow tp_base */
431 return b
== &PyBaseObject_Type
;
435 /* Internal routines to do a method lookup in the type
436 without looking in the instance dictionary
437 (so we can't use PyObject_GetAttr) but still binding
438 it to the instance. The arguments are the object,
439 the method name as a C string, and the address of a
440 static variable used to cache the interned Python string.
444 - lookup_maybe() returns NULL without raising an exception
445 when the _PyType_Lookup() call fails;
447 - lookup_method() always raises an exception upon errors.
451 lookup_maybe(PyObject
*self
, char *attrstr
, PyObject
**attrobj
)
455 if (*attrobj
== NULL
) {
456 *attrobj
= PyString_InternFromString(attrstr
);
457 if (*attrobj
== NULL
)
460 res
= _PyType_Lookup(self
->ob_type
, *attrobj
);
463 if ((f
= res
->ob_type
->tp_descr_get
) == NULL
)
466 res
= f(res
, self
, (PyObject
*)(self
->ob_type
));
472 lookup_method(PyObject
*self
, char *attrstr
, PyObject
**attrobj
)
474 PyObject
*res
= lookup_maybe(self
, attrstr
, attrobj
);
475 if (res
== NULL
&& !PyErr_Occurred())
476 PyErr_SetObject(PyExc_AttributeError
, *attrobj
);
480 /* A variation of PyObject_CallMethod that uses lookup_method()
481 instead of PyObject_GetAttrString(). This uses the same convention
482 as lookup_method to cache the interned name string object. */
485 call_method(PyObject
*o
, char *name
, PyObject
**nameobj
, char *format
, ...)
488 PyObject
*args
, *func
= 0, *retval
;
489 va_start(va
, format
);
491 func
= lookup_maybe(o
, name
, nameobj
);
494 if (!PyErr_Occurred())
495 PyErr_SetObject(PyExc_AttributeError
, *nameobj
);
499 if (format
&& *format
)
500 args
= Py_VaBuildValue(format
, va
);
502 args
= PyTuple_New(0);
509 assert(PyTuple_Check(args
));
510 retval
= PyObject_Call(func
, args
, NULL
);
518 /* Clone of call_method() that returns NotImplemented when the lookup fails. */
521 call_maybe(PyObject
*o
, char *name
, PyObject
**nameobj
, char *format
, ...)
524 PyObject
*args
, *func
= 0, *retval
;
525 va_start(va
, format
);
527 func
= lookup_maybe(o
, name
, nameobj
);
530 if (!PyErr_Occurred()) {
531 Py_INCREF(Py_NotImplemented
);
532 return Py_NotImplemented
;
537 if (format
&& *format
)
538 args
= Py_VaBuildValue(format
, va
);
540 args
= PyTuple_New(0);
547 assert(PyTuple_Check(args
));
548 retval
= PyObject_Call(func
, args
, NULL
);
556 /* Method resolution order algorithm from "Putting Metaclasses to Work"
557 by Forman and Danforth (Addison-Wesley 1999). */
560 conservative_merge(PyObject
*left
, PyObject
*right
)
567 assert(PyList_Check(left
));
568 assert(PyList_Check(right
));
571 left_size
= PyList_GET_SIZE(left
);
572 right_size
= PyList_GET_SIZE(right
);
573 for (i
= 0; i
< left_size
; i
++) {
574 for (j
= 0; j
< right_size
; j
++) {
575 if (PyList_GET_ITEM(left
, i
) ==
576 PyList_GET_ITEM(right
, j
)) {
577 /* found a merge point */
578 temp
= PyList_New(0);
581 for (r
= 0; r
< j
; r
++) {
582 rr
= PyList_GET_ITEM(right
, r
);
583 ok
= PySequence_Contains(left
, rr
);
589 ok
= PyList_Append(temp
, rr
);
596 ok
= PyList_SetSlice(left
, i
, i
, temp
);
600 ok
= PyList_SetSlice(right
, 0, j
+1, NULL
);
607 return PyList_SetSlice(left
, left_size
, left_size
, right
);
611 serious_order_disagreements(PyObject
*left
, PyObject
*right
)
613 return 0; /* XXX later -- for now, we cheat: "don't do that" */
617 fill_classic_mro(PyObject
*mro
, PyObject
*cls
)
619 PyObject
*bases
, *base
;
622 assert(PyList_Check(mro
));
623 assert(PyClass_Check(cls
));
624 i
= PySequence_Contains(mro
, cls
);
628 if (PyList_Append(mro
, cls
) < 0)
631 bases
= ((PyClassObject
*)cls
)->cl_bases
;
632 assert(bases
&& PyTuple_Check(bases
));
633 n
= PyTuple_GET_SIZE(bases
);
634 for (i
= 0; i
< n
; i
++) {
635 base
= PyTuple_GET_ITEM(bases
, i
);
636 if (fill_classic_mro(mro
, base
) < 0)
643 classic_mro(PyObject
*cls
)
647 assert(PyClass_Check(cls
));
650 if (fill_classic_mro(mro
, cls
) == 0)
658 mro_implementation(PyTypeObject
*type
)
661 PyObject
*bases
, *result
;
663 bases
= type
->tp_bases
;
664 n
= PyTuple_GET_SIZE(bases
);
665 result
= Py_BuildValue("[O]", (PyObject
*)type
);
668 for (i
= 0; i
< n
; i
++) {
669 PyObject
*base
= PyTuple_GET_ITEM(bases
, i
);
671 if (PyType_Check(base
))
672 parentMRO
= PySequence_List(
673 ((PyTypeObject
*)base
)->tp_mro
);
675 parentMRO
= classic_mro(base
);
676 if (parentMRO
== NULL
) {
680 if (serious_order_disagreements(result
, parentMRO
)) {
684 ok
= conservative_merge(result
, parentMRO
);
685 Py_DECREF(parentMRO
);
695 mro_external(PyObject
*self
)
697 PyTypeObject
*type
= (PyTypeObject
*)self
;
699 return mro_implementation(type
);
703 mro_internal(PyTypeObject
*type
)
705 PyObject
*mro
, *result
, *tuple
;
707 if (type
->ob_type
== &PyType_Type
) {
708 result
= mro_implementation(type
);
711 static PyObject
*mro_str
;
712 mro
= lookup_method((PyObject
*)type
, "mro", &mro_str
);
715 result
= PyObject_CallObject(mro
, NULL
);
720 tuple
= PySequence_Tuple(result
);
722 type
->tp_mro
= tuple
;
727 /* Calculate the best base amongst multiple base classes.
728 This is the first one that's on the path to the "solid base". */
730 static PyTypeObject
*
731 best_base(PyObject
*bases
)
734 PyTypeObject
*base
, *winner
, *candidate
, *base_i
;
735 PyObject
*base_proto
;
737 assert(PyTuple_Check(bases
));
738 n
= PyTuple_GET_SIZE(bases
);
742 for (i
= 0; i
< n
; i
++) {
743 base_proto
= PyTuple_GET_ITEM(bases
, i
);
744 if (PyClass_Check(base_proto
))
746 if (!PyType_Check(base_proto
)) {
749 "bases must be types");
752 base_i
= (PyTypeObject
*)base_proto
;
753 if (base_i
->tp_dict
== NULL
) {
754 if (PyType_Ready(base_i
) < 0)
757 candidate
= solid_base(base_i
);
758 if (winner
== NULL
) {
762 else if (PyType_IsSubtype(winner
, candidate
))
764 else if (PyType_IsSubtype(candidate
, winner
)) {
771 "multiple bases have "
772 "instance lay-out conflict");
777 PyErr_SetString(PyExc_TypeError
,
778 "a new-style class can't have only classic bases");
783 extra_ivars(PyTypeObject
*type
, PyTypeObject
*base
)
785 size_t t_size
= type
->tp_basicsize
;
786 size_t b_size
= base
->tp_basicsize
;
788 assert(t_size
>= b_size
); /* Else type smaller than base! */
789 if (type
->tp_itemsize
|| base
->tp_itemsize
) {
790 /* If itemsize is involved, stricter rules */
791 return t_size
!= b_size
||
792 type
->tp_itemsize
!= base
->tp_itemsize
;
794 if (type
->tp_weaklistoffset
&& base
->tp_weaklistoffset
== 0 &&
795 type
->tp_weaklistoffset
+ sizeof(PyObject
*) == t_size
)
796 t_size
-= sizeof(PyObject
*);
797 if (type
->tp_dictoffset
&& base
->tp_dictoffset
== 0 &&
798 type
->tp_dictoffset
+ sizeof(PyObject
*) == t_size
)
799 t_size
-= sizeof(PyObject
*);
801 return t_size
!= b_size
;
804 static PyTypeObject
*
805 solid_base(PyTypeObject
*type
)
810 base
= solid_base(type
->tp_base
);
812 base
= &PyBaseObject_Type
;
813 if (extra_ivars(type
, base
))
819 staticforward
void object_dealloc(PyObject
*);
820 staticforward
int object_init(PyObject
*, PyObject
*, PyObject
*);
821 staticforward
int update_slot(PyTypeObject
*, PyObject
*);
822 staticforward
void fixup_slot_dispatchers(PyTypeObject
*);
825 subtype_dict(PyObject
*obj
, void *context
)
827 PyObject
**dictptr
= _PyObject_GetDictPtr(obj
);
830 if (dictptr
== NULL
) {
831 PyErr_SetString(PyExc_AttributeError
,
832 "This object has no __dict__");
837 *dictptr
= dict
= PyDict_New();
843 subtype_setdict(PyObject
*obj
, PyObject
*value
, void *context
)
845 PyObject
**dictptr
= _PyObject_GetDictPtr(obj
);
848 if (dictptr
== NULL
) {
849 PyErr_SetString(PyExc_AttributeError
,
850 "This object has no __dict__");
853 if (value
!= NULL
&& !PyDict_Check(value
)) {
854 PyErr_SetString(PyExc_TypeError
,
855 "__dict__ must be set to a dictionary");
865 static PyGetSetDef subtype_getsets
[] = {
866 {"__dict__", subtype_dict
, subtype_setdict
, NULL
},
870 /* bozo: __getstate__ that raises TypeError */
873 bozo_func(PyObject
*self
, PyObject
*args
)
875 PyErr_SetString(PyExc_TypeError
,
876 "a class that defines __slots__ without "
877 "defining __getstate__ cannot be pickled");
881 static PyMethodDef bozo_ml
= {"__getstate__", bozo_func
};
883 static PyObject
*bozo_obj
= NULL
;
886 type_new(PyTypeObject
*metatype
, PyObject
*args
, PyObject
*kwds
)
888 PyObject
*name
, *bases
, *dict
;
889 static char *kwlist
[] = {"name", "bases", "dict", 0};
890 PyObject
*slots
, *tmp
;
891 PyTypeObject
*type
, *base
, *tmptype
, *winner
;
894 int i
, nbases
, nslots
, slotoffset
, add_dict
, add_weak
;
896 assert(args
!= NULL
&& PyTuple_Check(args
));
897 assert(kwds
== NULL
|| PyDict_Check(kwds
));
899 /* Special case: type(x) should return x->ob_type */
901 const int nargs
= PyTuple_GET_SIZE(args
);
902 const int nkwds
= kwds
== NULL
? 0 : PyDict_Size(kwds
);
904 if (PyType_CheckExact(metatype
) && nargs
== 1 && nkwds
== 0) {
905 PyObject
*x
= PyTuple_GET_ITEM(args
, 0);
906 Py_INCREF(x
->ob_type
);
907 return (PyObject
*) x
->ob_type
;
910 /* SF bug 475327 -- if that didn't trigger, we need 3
911 arguments. but PyArg_ParseTupleAndKeywords below may give
912 a msg saying type() needs exactly 3. */
913 if (nargs
+ nkwds
!= 3) {
914 PyErr_SetString(PyExc_TypeError
,
915 "type() takes 1 or 3 arguments");
920 /* Check arguments: (name, bases, dict) */
921 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "SO!O!:type", kwlist
,
923 &PyTuple_Type
, &bases
,
924 &PyDict_Type
, &dict
))
927 /* Determine the proper metatype to deal with this,
928 and check for metatype conflicts while we're at it.
929 Note that if some other metatype wins to contract,
930 it's possible that its instances are not types. */
931 nbases
= PyTuple_GET_SIZE(bases
);
933 for (i
= 0; i
< nbases
; i
++) {
934 tmp
= PyTuple_GET_ITEM(bases
, i
);
935 tmptype
= tmp
->ob_type
;
936 if (tmptype
== &PyClass_Type
)
937 continue; /* Special case classic classes */
938 if (PyType_IsSubtype(winner
, tmptype
))
940 if (PyType_IsSubtype(tmptype
, winner
)) {
944 PyErr_SetString(PyExc_TypeError
,
945 "metatype conflict among bases");
948 if (winner
!= metatype
) {
949 if (winner
->tp_new
!= type_new
) /* Pass it to the winner */
950 return winner
->tp_new(winner
, args
, kwds
);
954 /* Adjust for empty tuple bases */
956 bases
= Py_BuildValue("(O)", &PyBaseObject_Type
);
964 /* XXX From here until type is allocated, "return NULL" leaks bases! */
966 /* Calculate best base, and check that all bases are type objects */
967 base
= best_base(bases
);
970 if (!PyType_HasFeature(base
, Py_TPFLAGS_BASETYPE
)) {
971 PyErr_Format(PyExc_TypeError
,
972 "type '%.100s' is not an acceptable base type",
977 /* Check for a __slots__ sequence variable in dict, and count it */
978 slots
= PyDict_GetItemString(dict
, "__slots__");
983 /* Make it into a tuple */
984 if (PyString_Check(slots
))
985 slots
= Py_BuildValue("(O)", slots
);
987 slots
= PySequence_Tuple(slots
);
990 nslots
= PyTuple_GET_SIZE(slots
);
991 if (nslots
> 0 && base
->tp_itemsize
!= 0) {
992 PyErr_Format(PyExc_TypeError
,
993 "nonempty __slots__ "
994 "not supported for subtype of '%s'",
998 for (i
= 0; i
< nslots
; i
++) {
999 if (!PyString_Check(PyTuple_GET_ITEM(slots
, i
))) {
1000 PyErr_SetString(PyExc_TypeError
,
1001 "__slots__ must be a sequence of strings");
1005 /* XXX Check against null bytes in name */
1008 if (slots
!= NULL
) {
1009 /* See if *this* class defines __getstate__ */
1010 PyObject
*getstate
= PyDict_GetItemString(dict
,
1012 if (getstate
== NULL
) {
1013 /* If not, provide a bozo that raises TypeError */
1014 if (bozo_obj
== NULL
) {
1015 bozo_obj
= PyCFunction_New(&bozo_ml
, NULL
);
1016 if (bozo_obj
== NULL
) {
1017 /* XXX decref various things */
1021 if (PyDict_SetItemString(dict
,
1024 /* XXX decref various things */
1029 if (slots
== NULL
&& base
->tp_dictoffset
== 0 &&
1030 (base
->tp_setattro
== PyObject_GenericSetAttr
||
1031 base
->tp_setattro
== NULL
)) {
1034 if (slots
== NULL
&& base
->tp_weaklistoffset
== 0 &&
1035 base
->tp_itemsize
== 0) {
1040 /* XXX From here until type is safely allocated,
1041 "return NULL" may leak slots! */
1043 /* Allocate the type object */
1044 type
= (PyTypeObject
*)metatype
->tp_alloc(metatype
, nslots
);
1048 /* Keep name and slots alive in the extended type object */
1054 /* Initialize tp_flags */
1055 type
->tp_flags
= Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HEAPTYPE
|
1056 Py_TPFLAGS_BASETYPE
;
1057 if (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
)
1058 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
1060 /* It's a new-style number unless it specifically inherits any
1061 old-style numeric behavior */
1062 if ((base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) ||
1063 (base
->tp_as_number
== NULL
))
1064 type
->tp_flags
|= Py_TPFLAGS_CHECKTYPES
;
1066 /* Initialize essential fields */
1067 type
->tp_as_number
= &et
->as_number
;
1068 type
->tp_as_sequence
= &et
->as_sequence
;
1069 type
->tp_as_mapping
= &et
->as_mapping
;
1070 type
->tp_as_buffer
= &et
->as_buffer
;
1071 type
->tp_name
= PyString_AS_STRING(name
);
1073 /* Set tp_base and tp_bases */
1074 type
->tp_bases
= bases
;
1076 type
->tp_base
= base
;
1078 /* Initialize tp_dict from passed-in dict */
1079 type
->tp_dict
= dict
= PyDict_Copy(dict
);
1085 /* Set __module__ in the dict */
1086 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
1087 tmp
= PyEval_GetGlobals();
1089 tmp
= PyDict_GetItemString(tmp
, "__name__");
1091 if (PyDict_SetItemString(dict
, "__module__",
1098 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
1099 and is a string. The __doc__ accessor will first look for tp_doc;
1100 if that fails, it will still look into __dict__.
1103 PyObject
*doc
= PyDict_GetItemString(dict
, "__doc__");
1104 if (doc
!= NULL
&& PyString_Check(doc
)) {
1105 const size_t n
= (size_t)PyString_GET_SIZE(doc
);
1106 type
->tp_doc
= (char *)PyObject_MALLOC(n
+1);
1107 if (type
->tp_doc
== NULL
) {
1111 memcpy(type
->tp_doc
, PyString_AS_STRING(doc
), n
+1);
1115 /* Special-case __new__: if it's a plain function,
1116 make it a static function */
1117 tmp
= PyDict_GetItemString(dict
, "__new__");
1118 if (tmp
!= NULL
&& PyFunction_Check(tmp
)) {
1119 tmp
= PyStaticMethod_New(tmp
);
1124 PyDict_SetItemString(dict
, "__new__", tmp
);
1128 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1130 slotoffset
= base
->tp_basicsize
;
1131 if (slots
!= NULL
) {
1132 for (i
= 0; i
< nslots
; i
++, mp
++) {
1133 mp
->name
= PyString_AS_STRING(
1134 PyTuple_GET_ITEM(slots
, i
));
1135 mp
->type
= T_OBJECT_EX
;
1136 mp
->offset
= slotoffset
;
1137 if (base
->tp_weaklistoffset
== 0 &&
1138 strcmp(mp
->name
, "__weakref__") == 0) {
1139 mp
->type
= T_OBJECT
;
1140 type
->tp_weaklistoffset
= slotoffset
;
1142 slotoffset
+= sizeof(PyObject
*);
1147 if (base
->tp_itemsize
)
1148 type
->tp_dictoffset
=
1149 -(long)sizeof(PyObject
*);
1151 type
->tp_dictoffset
= slotoffset
;
1152 slotoffset
+= sizeof(PyObject
*);
1153 type
->tp_getset
= subtype_getsets
;
1156 assert(!base
->tp_itemsize
);
1157 type
->tp_weaklistoffset
= slotoffset
;
1158 mp
->name
= "__weakref__";
1159 mp
->type
= T_OBJECT
;
1160 mp
->offset
= slotoffset
;
1161 mp
->flags
= READONLY
;
1163 slotoffset
+= sizeof(PyObject
*);
1166 type
->tp_basicsize
= slotoffset
;
1167 type
->tp_itemsize
= base
->tp_itemsize
;
1168 type
->tp_members
= et
->members
;
1170 /* Special case some slots */
1171 if (type
->tp_dictoffset
!= 0 || nslots
> 0) {
1172 if (base
->tp_getattr
== NULL
&& base
->tp_getattro
== NULL
)
1173 type
->tp_getattro
= PyObject_GenericGetAttr
;
1174 if (base
->tp_setattr
== NULL
&& base
->tp_setattro
== NULL
)
1175 type
->tp_setattro
= PyObject_GenericSetAttr
;
1177 type
->tp_dealloc
= subtype_dealloc
;
1179 /* Enable GC unless there are really no instance variables possible */
1180 if (!(type
->tp_basicsize
== sizeof(PyObject
) &&
1181 type
->tp_itemsize
== 0))
1182 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
1184 /* Always override allocation strategy to use regular heap */
1185 type
->tp_alloc
= PyType_GenericAlloc
;
1186 if (type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) {
1187 type
->tp_free
= _PyObject_GC_Del
;
1188 type
->tp_traverse
= subtype_traverse
;
1189 type
->tp_clear
= base
->tp_clear
;
1192 type
->tp_free
= _PyObject_Del
;
1194 /* Initialize the rest */
1195 if (PyType_Ready(type
) < 0) {
1200 /* Put the proper slots in place */
1201 fixup_slot_dispatchers(type
);
1203 return (PyObject
*)type
;
1206 /* Internal API to look for a name through the MRO.
1207 This returns a borrowed reference, and doesn't set an exception! */
1209 _PyType_Lookup(PyTypeObject
*type
, PyObject
*name
)
1212 PyObject
*mro
, *res
, *base
, *dict
;
1214 /* Look in tp_dict of types in MRO */
1216 assert(PyTuple_Check(mro
));
1217 n
= PyTuple_GET_SIZE(mro
);
1218 for (i
= 0; i
< n
; i
++) {
1219 base
= PyTuple_GET_ITEM(mro
, i
);
1220 if (PyClass_Check(base
))
1221 dict
= ((PyClassObject
*)base
)->cl_dict
;
1223 assert(PyType_Check(base
));
1224 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1226 assert(dict
&& PyDict_Check(dict
));
1227 res
= PyDict_GetItem(dict
, name
);
1234 /* This is similar to PyObject_GenericGetAttr(),
1235 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1237 type_getattro(PyTypeObject
*type
, PyObject
*name
)
1239 PyTypeObject
*metatype
= type
->ob_type
;
1240 PyObject
*descr
, *res
;
1243 /* Initialize this type (we'll assume the metatype is initialized) */
1244 if (type
->tp_dict
== NULL
) {
1245 if (PyType_Ready(type
) < 0)
1249 /* Get a descriptor from the metatype */
1250 descr
= _PyType_Lookup(metatype
, name
);
1252 if (descr
!= NULL
) {
1253 f
= descr
->ob_type
->tp_descr_get
;
1254 if (f
!= NULL
&& PyDescr_IsData(descr
))
1256 (PyObject
*)type
, (PyObject
*)metatype
);
1259 /* Look in tp_dict of this type and its bases */
1260 res
= _PyType_Lookup(type
, name
);
1262 f
= res
->ob_type
->tp_descr_get
;
1264 return f(res
, (PyObject
*)NULL
, (PyObject
*)type
);
1269 /* Use the descriptor from the metatype */
1271 res
= f(descr
, (PyObject
*)type
, (PyObject
*)metatype
);
1274 if (descr
!= NULL
) {
1280 PyErr_Format(PyExc_AttributeError
,
1281 "type object '%.50s' has no attribute '%.400s'",
1282 type
->tp_name
, PyString_AS_STRING(name
));
1287 type_setattro(PyTypeObject
*type
, PyObject
*name
, PyObject
*value
)
1289 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
1292 "can't set attributes of built-in/extension type '%s'",
1296 if (PyObject_GenericSetAttr((PyObject
*)type
, name
, value
) < 0)
1298 return update_slot(type
, name
);
1302 type_dealloc(PyTypeObject
*type
)
1306 /* Assert this is a heap-allocated type object */
1307 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
1308 _PyObject_GC_UNTRACK(type
);
1309 PyObject_ClearWeakRefs((PyObject
*)type
);
1311 Py_XDECREF(type
->tp_base
);
1312 Py_XDECREF(type
->tp_dict
);
1313 Py_XDECREF(type
->tp_bases
);
1314 Py_XDECREF(type
->tp_mro
);
1315 Py_XDECREF(type
->tp_cache
);
1316 Py_XDECREF(type
->tp_subclasses
);
1317 Py_XDECREF(et
->name
);
1318 Py_XDECREF(et
->slots
);
1319 type
->ob_type
->tp_free((PyObject
*)type
);
1323 type_subclasses(PyTypeObject
*type
, PyObject
*args_ignored
)
1325 PyObject
*list
, *raw
, *ref
;
1328 list
= PyList_New(0);
1331 raw
= type
->tp_subclasses
;
1334 assert(PyList_Check(raw
));
1335 n
= PyList_GET_SIZE(raw
);
1336 for (i
= 0; i
< n
; i
++) {
1337 ref
= PyList_GET_ITEM(raw
, i
);
1338 assert(PyWeakref_CheckRef(ref
));
1339 ref
= PyWeakref_GET_OBJECT(ref
);
1340 if (ref
!= Py_None
) {
1341 if (PyList_Append(list
, ref
) < 0) {
1350 static PyMethodDef type_methods
[] = {
1351 {"mro", (PyCFunction
)mro_external
, METH_NOARGS
,
1352 "mro() -> list\nreturn a type's method resolution order"},
1353 {"__subclasses__", (PyCFunction
)type_subclasses
, METH_NOARGS
,
1354 "__subclasses__() -> list of immediate subclasses"},
1358 static char type_doc
[] =
1359 "type(object) -> the object's type\n"
1360 "type(name, bases, dict) -> a new type";
1363 type_traverse(PyTypeObject
*type
, visitproc visit
, void *arg
)
1368 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
1373 #define VISIT(SLOT) \
1375 err = visit((PyObject *)(SLOT), arg); \
1380 VISIT(type
->tp_dict
);
1381 VISIT(type
->tp_cache
);
1382 VISIT(type
->tp_mro
);
1383 VISIT(type
->tp_bases
);
1384 VISIT(type
->tp_base
);
1385 VISIT(type
->tp_subclasses
);
1394 type_clear(PyTypeObject
*type
)
1399 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
1404 #define CLEAR(SLOT) \
1406 tmp = (PyObject *)(SLOT); \
1411 CLEAR(type
->tp_dict
);
1412 CLEAR(type
->tp_cache
);
1413 CLEAR(type
->tp_mro
);
1414 CLEAR(type
->tp_bases
);
1415 CLEAR(type
->tp_base
);
1416 CLEAR(type
->tp_subclasses
);
1419 if (type
->tp_doc
!= NULL
) {
1420 PyObject_FREE(type
->tp_doc
);
1421 type
->tp_doc
= NULL
;
1430 type_is_gc(PyTypeObject
*type
)
1432 return type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
;
1435 PyTypeObject PyType_Type
= {
1436 PyObject_HEAD_INIT(&PyType_Type
)
1438 "type", /* tp_name */
1439 sizeof(etype
), /* tp_basicsize */
1440 sizeof(PyMemberDef
), /* tp_itemsize */
1441 (destructor
)type_dealloc
, /* tp_dealloc */
1445 type_compare
, /* tp_compare */
1446 (reprfunc
)type_repr
, /* tp_repr */
1447 0, /* tp_as_number */
1448 0, /* tp_as_sequence */
1449 0, /* tp_as_mapping */
1450 (hashfunc
)_Py_HashPointer
, /* tp_hash */
1451 (ternaryfunc
)type_call
, /* tp_call */
1453 (getattrofunc
)type_getattro
, /* tp_getattro */
1454 (setattrofunc
)type_setattro
, /* tp_setattro */
1455 0, /* tp_as_buffer */
1456 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
1457 Py_TPFLAGS_BASETYPE
, /* tp_flags */
1458 type_doc
, /* tp_doc */
1459 (traverseproc
)type_traverse
, /* tp_traverse */
1460 (inquiry
)type_clear
, /* tp_clear */
1461 0, /* tp_richcompare */
1462 offsetof(PyTypeObject
, tp_weaklist
), /* tp_weaklistoffset */
1464 0, /* tp_iternext */
1465 type_methods
, /* tp_methods */
1466 type_members
, /* tp_members */
1467 type_getsets
, /* tp_getset */
1470 0, /* tp_descr_get */
1471 0, /* tp_descr_set */
1472 offsetof(PyTypeObject
, tp_dict
), /* tp_dictoffset */
1475 type_new
, /* tp_new */
1476 _PyObject_GC_Del
, /* tp_free */
1477 (inquiry
)type_is_gc
, /* tp_is_gc */
1481 /* The base type of all types (eventually)... except itself. */
1484 object_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1490 object_dealloc(PyObject
*self
)
1492 self
->ob_type
->tp_free(self
);
1496 object_repr(PyObject
*self
)
1499 PyObject
*mod
, *name
, *rtn
;
1501 type
= self
->ob_type
;
1502 mod
= type_module(type
, NULL
);
1505 else if (!PyString_Check(mod
)) {
1509 name
= type_name(type
, NULL
);
1512 if (mod
!= NULL
&& strcmp(PyString_AS_STRING(mod
), "__builtin__"))
1513 rtn
= PyString_FromFormat("<%s.%s object at %p>",
1514 PyString_AS_STRING(mod
),
1515 PyString_AS_STRING(name
),
1518 rtn
= PyString_FromFormat("<%s object at %p>",
1519 type
->tp_name
, self
);
1526 object_str(PyObject
*self
)
1530 f
= self
->ob_type
->tp_repr
;
1537 object_hash(PyObject
*self
)
1539 return _Py_HashPointer(self
);
1543 object_get_class(PyObject
*self
, void *closure
)
1545 Py_INCREF(self
->ob_type
);
1546 return (PyObject
*)(self
->ob_type
);
1550 equiv_structs(PyTypeObject
*a
, PyTypeObject
*b
)
1555 a
->tp_basicsize
== b
->tp_basicsize
&&
1556 a
->tp_itemsize
== b
->tp_itemsize
&&
1557 a
->tp_dictoffset
== b
->tp_dictoffset
&&
1558 a
->tp_weaklistoffset
== b
->tp_weaklistoffset
&&
1559 ((a
->tp_flags
& Py_TPFLAGS_HAVE_GC
) ==
1560 (b
->tp_flags
& Py_TPFLAGS_HAVE_GC
)));
1564 same_slots_added(PyTypeObject
*a
, PyTypeObject
*b
)
1566 PyTypeObject
*base
= a
->tp_base
;
1569 if (base
!= b
->tp_base
)
1571 if (equiv_structs(a
, base
) && equiv_structs(b
, base
))
1573 size
= base
->tp_basicsize
;
1574 if (a
->tp_dictoffset
== size
&& b
->tp_dictoffset
== size
)
1575 size
+= sizeof(PyObject
*);
1576 if (a
->tp_weaklistoffset
== size
&& b
->tp_weaklistoffset
== size
)
1577 size
+= sizeof(PyObject
*);
1578 return size
== a
->tp_basicsize
&& size
== b
->tp_basicsize
;
1582 object_set_class(PyObject
*self
, PyObject
*value
, void *closure
)
1584 PyTypeObject
*old
= self
->ob_type
;
1585 PyTypeObject
*new, *newbase
, *oldbase
;
1587 if (!PyType_Check(value
)) {
1588 PyErr_Format(PyExc_TypeError
,
1589 "__class__ must be set to new-style class, not '%s' object",
1590 value
->ob_type
->tp_name
);
1593 new = (PyTypeObject
*)value
;
1596 while (equiv_structs(newbase
, newbase
->tp_base
))
1597 newbase
= newbase
->tp_base
;
1598 while (equiv_structs(oldbase
, oldbase
->tp_base
))
1599 oldbase
= oldbase
->tp_base
;
1600 if (newbase
!= oldbase
&&
1601 (newbase
->tp_base
!= oldbase
->tp_base
||
1602 !same_slots_added(newbase
, oldbase
))) {
1603 PyErr_Format(PyExc_TypeError
,
1604 "__class__ assignment: "
1605 "'%s' object layout differs from '%s'",
1610 if (new->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
1613 self
->ob_type
= new;
1614 if (old
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
1620 static PyGetSetDef object_getsets
[] = {
1621 {"__class__", object_get_class
, object_set_class
,
1622 "the object's class"},
1627 object_reduce(PyObject
*self
, PyObject
*args
)
1629 /* Call copy_reg._reduce(self) */
1630 static PyObject
*copy_reg_str
;
1631 PyObject
*copy_reg
, *res
;
1633 if (!copy_reg_str
) {
1634 copy_reg_str
= PyString_InternFromString("copy_reg");
1635 if (copy_reg_str
== NULL
)
1638 copy_reg
= PyImport_Import(copy_reg_str
);
1641 res
= PyEval_CallMethod(copy_reg
, "_reduce", "(O)", self
);
1642 Py_DECREF(copy_reg
);
1646 static PyMethodDef object_methods
[] = {
1647 {"__reduce__", object_reduce
, METH_NOARGS
, "helper for pickle"},
1651 PyTypeObject PyBaseObject_Type
= {
1652 PyObject_HEAD_INIT(&PyType_Type
)
1654 "object", /* tp_name */
1655 sizeof(PyObject
), /* tp_basicsize */
1656 0, /* tp_itemsize */
1657 (destructor
)object_dealloc
, /* tp_dealloc */
1662 object_repr
, /* tp_repr */
1663 0, /* tp_as_number */
1664 0, /* tp_as_sequence */
1665 0, /* tp_as_mapping */
1666 object_hash
, /* tp_hash */
1668 object_str
, /* tp_str */
1669 PyObject_GenericGetAttr
, /* tp_getattro */
1670 PyObject_GenericSetAttr
, /* tp_setattro */
1671 0, /* tp_as_buffer */
1672 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
1673 "The most base type", /* tp_doc */
1674 0, /* tp_traverse */
1676 0, /* tp_richcompare */
1677 0, /* tp_weaklistoffset */
1679 0, /* tp_iternext */
1680 object_methods
, /* tp_methods */
1682 object_getsets
, /* tp_getset */
1685 0, /* tp_descr_get */
1686 0, /* tp_descr_set */
1687 0, /* tp_dictoffset */
1688 object_init
, /* tp_init */
1689 PyType_GenericAlloc
, /* tp_alloc */
1690 PyType_GenericNew
, /* tp_new */
1691 _PyObject_Del
, /* tp_free */
1695 /* Initialize the __dict__ in a type object */
1698 add_methods(PyTypeObject
*type
, PyMethodDef
*meth
)
1700 PyObject
*dict
= type
->tp_dict
;
1702 for (; meth
->ml_name
!= NULL
; meth
++) {
1704 if (PyDict_GetItemString(dict
, meth
->ml_name
))
1706 descr
= PyDescr_NewMethod(type
, meth
);
1709 if (PyDict_SetItemString(dict
,meth
->ml_name
, descr
) < 0)
1717 add_members(PyTypeObject
*type
, PyMemberDef
*memb
)
1719 PyObject
*dict
= type
->tp_dict
;
1721 for (; memb
->name
!= NULL
; memb
++) {
1723 if (PyDict_GetItemString(dict
, memb
->name
))
1725 descr
= PyDescr_NewMember(type
, memb
);
1728 if (PyDict_SetItemString(dict
, memb
->name
, descr
) < 0)
1736 add_getset(PyTypeObject
*type
, PyGetSetDef
*gsp
)
1738 PyObject
*dict
= type
->tp_dict
;
1740 for (; gsp
->name
!= NULL
; gsp
++) {
1742 if (PyDict_GetItemString(dict
, gsp
->name
))
1744 descr
= PyDescr_NewGetSet(type
, gsp
);
1748 if (PyDict_SetItemString(dict
, gsp
->name
, descr
) < 0)
1756 inherit_special(PyTypeObject
*type
, PyTypeObject
*base
)
1758 int oldsize
, newsize
;
1760 /* Special flag magic */
1761 if (!type
->tp_as_buffer
&& base
->tp_as_buffer
) {
1762 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_GETCHARBUFFER
;
1764 base
->tp_flags
& Py_TPFLAGS_HAVE_GETCHARBUFFER
;
1766 if (!type
->tp_as_sequence
&& base
->tp_as_sequence
) {
1767 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_SEQUENCE_IN
;
1768 type
->tp_flags
|= base
->tp_flags
& Py_TPFLAGS_HAVE_SEQUENCE_IN
;
1770 if ((type
->tp_flags
& Py_TPFLAGS_HAVE_INPLACEOPS
) !=
1771 (base
->tp_flags
& Py_TPFLAGS_HAVE_INPLACEOPS
)) {
1772 if ((!type
->tp_as_number
&& base
->tp_as_number
) ||
1773 (!type
->tp_as_sequence
&& base
->tp_as_sequence
)) {
1774 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_INPLACEOPS
;
1775 if (!type
->tp_as_number
&& !type
->tp_as_sequence
) {
1776 type
->tp_flags
|= base
->tp_flags
&
1777 Py_TPFLAGS_HAVE_INPLACEOPS
;
1782 if (!type
->tp_as_number
&& base
->tp_as_number
) {
1783 type
->tp_flags
&= ~Py_TPFLAGS_CHECKTYPES
;
1784 type
->tp_flags
|= base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
;
1787 /* Copying basicsize is connected to the GC flags */
1788 oldsize
= base
->tp_basicsize
;
1789 newsize
= type
->tp_basicsize
? type
->tp_basicsize
: oldsize
;
1790 if (!(type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
1791 (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
1792 (type
->tp_flags
& Py_TPFLAGS_HAVE_RICHCOMPARE
/*GC slots exist*/) &&
1793 (!type
->tp_traverse
&& !type
->tp_clear
)) {
1794 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
1795 if (type
->tp_traverse
== NULL
)
1796 type
->tp_traverse
= base
->tp_traverse
;
1797 if (type
->tp_clear
== NULL
)
1798 type
->tp_clear
= base
->tp_clear
;
1800 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
1801 /* The condition below could use some explanation.
1802 It appears that tp_new is not inherited for static types
1803 whose base class is 'object'; this seems to be a precaution
1804 so that old extension types don't suddenly become
1805 callable (object.__new__ wouldn't insure the invariants
1806 that the extension type's own factory function ensures).
1807 Heap types, of course, are under our control, so they do
1808 inherit tp_new; static extension types that specify some
1809 other built-in type as the default are considered
1810 new-style-aware so they also inherit object.__new__. */
1811 if (base
!= &PyBaseObject_Type
||
1812 (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
1813 if (type
->tp_new
== NULL
)
1814 type
->tp_new
= base
->tp_new
;
1817 type
->tp_basicsize
= newsize
;
1819 /* Copy other non-function slots */
1822 #define COPYVAL(SLOT) \
1823 if (type->SLOT == 0) type->SLOT = base->SLOT
1825 COPYVAL(tp_itemsize
);
1826 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_WEAKREFS
) {
1827 COPYVAL(tp_weaklistoffset
);
1829 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
1830 COPYVAL(tp_dictoffset
);
1835 inherit_slots(PyTypeObject
*type
, PyTypeObject
*base
)
1837 PyTypeObject
*basebase
;
1846 #define SLOTDEFINED(SLOT) \
1847 (base->SLOT != 0 && \
1848 (basebase == NULL || base->SLOT != basebase->SLOT))
1850 #define COPYSLOT(SLOT) \
1851 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
1853 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1854 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1855 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1856 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
1858 /* This won't inherit indirect slots (from tp_as_number etc.)
1859 if type doesn't provide the space. */
1861 if (type
->tp_as_number
!= NULL
&& base
->tp_as_number
!= NULL
) {
1862 basebase
= base
->tp_base
;
1863 if (basebase
->tp_as_number
== NULL
)
1866 COPYNUM(nb_subtract
);
1867 COPYNUM(nb_multiply
);
1869 COPYNUM(nb_remainder
);
1872 COPYNUM(nb_negative
);
1873 COPYNUM(nb_positive
);
1874 COPYNUM(nb_absolute
);
1875 COPYNUM(nb_nonzero
);
1888 COPYNUM(nb_inplace_add
);
1889 COPYNUM(nb_inplace_subtract
);
1890 COPYNUM(nb_inplace_multiply
);
1891 COPYNUM(nb_inplace_divide
);
1892 COPYNUM(nb_inplace_remainder
);
1893 COPYNUM(nb_inplace_power
);
1894 COPYNUM(nb_inplace_lshift
);
1895 COPYNUM(nb_inplace_rshift
);
1896 COPYNUM(nb_inplace_and
);
1897 COPYNUM(nb_inplace_xor
);
1898 COPYNUM(nb_inplace_or
);
1899 if (base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) {
1900 COPYNUM(nb_true_divide
);
1901 COPYNUM(nb_floor_divide
);
1902 COPYNUM(nb_inplace_true_divide
);
1903 COPYNUM(nb_inplace_floor_divide
);
1907 if (type
->tp_as_sequence
!= NULL
&& base
->tp_as_sequence
!= NULL
) {
1908 basebase
= base
->tp_base
;
1909 if (basebase
->tp_as_sequence
== NULL
)
1916 COPYSEQ(sq_ass_item
);
1917 COPYSEQ(sq_ass_slice
);
1918 COPYSEQ(sq_contains
);
1919 COPYSEQ(sq_inplace_concat
);
1920 COPYSEQ(sq_inplace_repeat
);
1923 if (type
->tp_as_mapping
!= NULL
&& base
->tp_as_mapping
!= NULL
) {
1924 basebase
= base
->tp_base
;
1925 if (basebase
->tp_as_mapping
== NULL
)
1928 COPYMAP(mp_subscript
);
1929 COPYMAP(mp_ass_subscript
);
1932 if (type
->tp_as_buffer
!= NULL
&& base
->tp_as_buffer
!= NULL
) {
1933 basebase
= base
->tp_base
;
1934 if (basebase
->tp_as_buffer
== NULL
)
1936 COPYBUF(bf_getreadbuffer
);
1937 COPYBUF(bf_getwritebuffer
);
1938 COPYBUF(bf_getsegcount
);
1939 COPYBUF(bf_getcharbuffer
);
1942 basebase
= base
->tp_base
;
1944 COPYSLOT(tp_dealloc
);
1946 if (type
->tp_getattr
== NULL
&& type
->tp_getattro
== NULL
) {
1947 type
->tp_getattr
= base
->tp_getattr
;
1948 type
->tp_getattro
= base
->tp_getattro
;
1950 if (type
->tp_setattr
== NULL
&& type
->tp_setattro
== NULL
) {
1951 type
->tp_setattr
= base
->tp_setattr
;
1952 type
->tp_setattro
= base
->tp_setattro
;
1954 /* tp_compare see tp_richcompare */
1956 /* tp_hash see tp_richcompare */
1959 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_RICHCOMPARE
) {
1960 if (type
->tp_compare
== NULL
&&
1961 type
->tp_richcompare
== NULL
&&
1962 type
->tp_hash
== NULL
)
1964 type
->tp_compare
= base
->tp_compare
;
1965 type
->tp_richcompare
= base
->tp_richcompare
;
1966 type
->tp_hash
= base
->tp_hash
;
1970 COPYSLOT(tp_compare
);
1972 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_ITER
) {
1974 COPYSLOT(tp_iternext
);
1976 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
1977 COPYSLOT(tp_descr_get
);
1978 COPYSLOT(tp_descr_set
);
1979 COPYSLOT(tp_dictoffset
);
1987 staticforward
int add_operators(PyTypeObject
*);
1988 staticforward
int add_subclass(PyTypeObject
*base
, PyTypeObject
*type
);
1991 PyType_Ready(PyTypeObject
*type
)
1993 PyObject
*dict
, *bases
;
1997 if (type
->tp_flags
& Py_TPFLAGS_READY
) {
1998 assert(type
->tp_dict
!= NULL
);
2001 assert((type
->tp_flags
& Py_TPFLAGS_READYING
) == 0);
2003 type
->tp_flags
|= Py_TPFLAGS_READYING
;
2005 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2006 base
= type
->tp_base
;
2007 if (base
== NULL
&& type
!= &PyBaseObject_Type
)
2008 base
= type
->tp_base
= &PyBaseObject_Type
;
2010 /* Initialize ob_type if NULL. This means extensions that want to be
2011 compilable separately on Windows can call PyType_Ready() instead of
2012 initializing the ob_type field of their type objects. */
2013 if (type
->ob_type
== NULL
)
2014 type
->ob_type
= base
->ob_type
;
2016 /* Initialize tp_bases */
2017 bases
= type
->tp_bases
;
2018 if (bases
== NULL
) {
2020 bases
= PyTuple_New(0);
2022 bases
= Py_BuildValue("(O)", base
);
2025 type
->tp_bases
= bases
;
2028 /* Initialize the base class */
2029 if (base
&& base
->tp_dict
== NULL
) {
2030 if (PyType_Ready(base
) < 0)
2034 /* Initialize tp_dict */
2035 dict
= type
->tp_dict
;
2037 dict
= PyDict_New();
2040 type
->tp_dict
= dict
;
2043 /* Add type-specific descriptors to tp_dict */
2044 if (add_operators(type
) < 0)
2046 if (type
->tp_methods
!= NULL
) {
2047 if (add_methods(type
, type
->tp_methods
) < 0)
2050 if (type
->tp_members
!= NULL
) {
2051 if (add_members(type
, type
->tp_members
) < 0)
2054 if (type
->tp_getset
!= NULL
) {
2055 if (add_getset(type
, type
->tp_getset
) < 0)
2059 /* Calculate method resolution order */
2060 if (mro_internal(type
) < 0) {
2064 /* Inherit special flags from dominant base */
2065 if (type
->tp_base
!= NULL
)
2066 inherit_special(type
, type
->tp_base
);
2068 /* Initialize tp_dict properly */
2069 bases
= type
->tp_mro
;
2070 assert(bases
!= NULL
);
2071 assert(PyTuple_Check(bases
));
2072 n
= PyTuple_GET_SIZE(bases
);
2073 for (i
= 1; i
< n
; i
++) {
2074 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
2075 if (PyType_Check(b
))
2076 inherit_slots(type
, (PyTypeObject
*)b
);
2079 /* if the type dictionary doesn't contain a __doc__, set it from
2082 if (PyDict_GetItemString(type
->tp_dict
, "__doc__") == NULL
) {
2083 if (type
->tp_doc
!= NULL
) {
2084 PyObject
*doc
= PyString_FromString(type
->tp_doc
);
2085 PyDict_SetItemString(type
->tp_dict
, "__doc__", doc
);
2088 PyDict_SetItemString(type
->tp_dict
, "__doc__", Py_None
);
2092 /* Some more special stuff */
2093 base
= type
->tp_base
;
2095 if (type
->tp_as_number
== NULL
)
2096 type
->tp_as_number
= base
->tp_as_number
;
2097 if (type
->tp_as_sequence
== NULL
)
2098 type
->tp_as_sequence
= base
->tp_as_sequence
;
2099 if (type
->tp_as_mapping
== NULL
)
2100 type
->tp_as_mapping
= base
->tp_as_mapping
;
2103 /* Link into each base class's list of subclasses */
2104 bases
= type
->tp_bases
;
2105 n
= PyTuple_GET_SIZE(bases
);
2106 for (i
= 0; i
< n
; i
++) {
2107 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
2108 if (PyType_Check(b
) &&
2109 add_subclass((PyTypeObject
*)b
, type
) < 0)
2113 /* All done -- set the ready flag */
2114 assert(type
->tp_dict
!= NULL
);
2116 (type
->tp_flags
& ~Py_TPFLAGS_READYING
) | Py_TPFLAGS_READY
;
2120 type
->tp_flags
&= ~Py_TPFLAGS_READYING
;
2125 add_subclass(PyTypeObject
*base
, PyTypeObject
*type
)
2128 PyObject
*list
, *ref
, *new;
2130 list
= base
->tp_subclasses
;
2132 base
->tp_subclasses
= list
= PyList_New(0);
2136 assert(PyList_Check(list
));
2137 new = PyWeakref_NewRef((PyObject
*)type
, NULL
);
2138 i
= PyList_GET_SIZE(list
);
2140 ref
= PyList_GET_ITEM(list
, i
);
2141 assert(PyWeakref_CheckRef(ref
));
2142 if (PyWeakref_GET_OBJECT(ref
) == Py_None
)
2143 return PyList_SetItem(list
, i
, new);
2145 i
= PyList_Append(list
, new);
2151 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
2153 /* There's a wrapper *function* for each distinct function typedef used
2154 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2155 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2156 Most tables have only one entry; the tables for binary operators have two
2157 entries, one regular and one with reversed arguments. */
2160 wrap_inquiry(PyObject
*self
, PyObject
*args
, void *wrapped
)
2162 inquiry func
= (inquiry
)wrapped
;
2165 if (!PyArg_ParseTuple(args
, ""))
2167 res
= (*func
)(self
);
2168 if (res
== -1 && PyErr_Occurred())
2170 return PyInt_FromLong((long)res
);
2174 wrap_binaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2176 binaryfunc func
= (binaryfunc
)wrapped
;
2179 if (!PyArg_ParseTuple(args
, "O", &other
))
2181 return (*func
)(self
, other
);
2185 wrap_binaryfunc_l(PyObject
*self
, PyObject
*args
, void *wrapped
)
2187 binaryfunc func
= (binaryfunc
)wrapped
;
2190 if (!PyArg_ParseTuple(args
, "O", &other
))
2192 if (!(self
->ob_type
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) &&
2193 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
2194 Py_INCREF(Py_NotImplemented
);
2195 return Py_NotImplemented
;
2197 return (*func
)(self
, other
);
2201 wrap_binaryfunc_r(PyObject
*self
, PyObject
*args
, void *wrapped
)
2203 binaryfunc func
= (binaryfunc
)wrapped
;
2206 if (!PyArg_ParseTuple(args
, "O", &other
))
2208 if (!(self
->ob_type
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) &&
2209 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
2210 Py_INCREF(Py_NotImplemented
);
2211 return Py_NotImplemented
;
2213 return (*func
)(other
, self
);
2217 wrap_coercefunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2219 coercion func
= (coercion
)wrapped
;
2220 PyObject
*other
, *res
;
2223 if (!PyArg_ParseTuple(args
, "O", &other
))
2225 ok
= func(&self
, &other
);
2229 Py_INCREF(Py_NotImplemented
);
2230 return Py_NotImplemented
;
2232 res
= PyTuple_New(2);
2238 PyTuple_SET_ITEM(res
, 0, self
);
2239 PyTuple_SET_ITEM(res
, 1, other
);
2244 wrap_ternaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2246 ternaryfunc func
= (ternaryfunc
)wrapped
;
2248 PyObject
*third
= Py_None
;
2250 /* Note: This wrapper only works for __pow__() */
2252 if (!PyArg_ParseTuple(args
, "O|O", &other
, &third
))
2254 return (*func
)(self
, other
, third
);
2258 wrap_ternaryfunc_r(PyObject
*self
, PyObject
*args
, void *wrapped
)
2260 ternaryfunc func
= (ternaryfunc
)wrapped
;
2262 PyObject
*third
= Py_None
;
2264 /* Note: This wrapper only works for __pow__() */
2266 if (!PyArg_ParseTuple(args
, "O|O", &other
, &third
))
2268 return (*func
)(other
, self
, third
);
2272 wrap_unaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2274 unaryfunc func
= (unaryfunc
)wrapped
;
2276 if (!PyArg_ParseTuple(args
, ""))
2278 return (*func
)(self
);
2282 wrap_intargfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2284 intargfunc func
= (intargfunc
)wrapped
;
2287 if (!PyArg_ParseTuple(args
, "i", &i
))
2289 return (*func
)(self
, i
);
2293 getindex(PyObject
*self
, PyObject
*arg
)
2297 i
= PyInt_AsLong(arg
);
2298 if (i
== -1 && PyErr_Occurred())
2301 PySequenceMethods
*sq
= self
->ob_type
->tp_as_sequence
;
2302 if (sq
&& sq
->sq_length
) {
2303 int n
= (*sq
->sq_length
)(self
);
2313 wrap_sq_item(PyObject
*self
, PyObject
*args
, void *wrapped
)
2315 intargfunc func
= (intargfunc
)wrapped
;
2319 if (PyTuple_GET_SIZE(args
) == 1) {
2320 arg
= PyTuple_GET_ITEM(args
, 0);
2321 i
= getindex(self
, arg
);
2322 if (i
== -1 && PyErr_Occurred())
2324 return (*func
)(self
, i
);
2326 PyArg_ParseTuple(args
, "O", &arg
);
2327 assert(PyErr_Occurred());
2332 wrap_intintargfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2334 intintargfunc func
= (intintargfunc
)wrapped
;
2337 if (!PyArg_ParseTuple(args
, "ii", &i
, &j
))
2339 return (*func
)(self
, i
, j
);
2343 wrap_sq_setitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
2345 intobjargproc func
= (intobjargproc
)wrapped
;
2347 PyObject
*arg
, *value
;
2349 if (!PyArg_ParseTuple(args
, "OO", &arg
, &value
))
2351 i
= getindex(self
, arg
);
2352 if (i
== -1 && PyErr_Occurred())
2354 res
= (*func
)(self
, i
, value
);
2355 if (res
== -1 && PyErr_Occurred())
2362 wrap_sq_delitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
2364 intobjargproc func
= (intobjargproc
)wrapped
;
2368 if (!PyArg_ParseTuple(args
, "O", &arg
))
2370 i
= getindex(self
, arg
);
2371 if (i
== -1 && PyErr_Occurred())
2373 res
= (*func
)(self
, i
, NULL
);
2374 if (res
== -1 && PyErr_Occurred())
2381 wrap_intintobjargproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2383 intintobjargproc func
= (intintobjargproc
)wrapped
;
2387 if (!PyArg_ParseTuple(args
, "iiO", &i
, &j
, &value
))
2389 res
= (*func
)(self
, i
, j
, value
);
2390 if (res
== -1 && PyErr_Occurred())
2397 wrap_delslice(PyObject
*self
, PyObject
*args
, void *wrapped
)
2399 intintobjargproc func
= (intintobjargproc
)wrapped
;
2402 if (!PyArg_ParseTuple(args
, "ii", &i
, &j
))
2404 res
= (*func
)(self
, i
, j
, NULL
);
2405 if (res
== -1 && PyErr_Occurred())
2411 /* XXX objobjproc is a misnomer; should be objargpred */
2413 wrap_objobjproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2415 objobjproc func
= (objobjproc
)wrapped
;
2419 if (!PyArg_ParseTuple(args
, "O", &value
))
2421 res
= (*func
)(self
, value
);
2422 if (res
== -1 && PyErr_Occurred())
2424 return PyInt_FromLong((long)res
);
2428 wrap_objobjargproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2430 objobjargproc func
= (objobjargproc
)wrapped
;
2432 PyObject
*key
, *value
;
2434 if (!PyArg_ParseTuple(args
, "OO", &key
, &value
))
2436 res
= (*func
)(self
, key
, value
);
2437 if (res
== -1 && PyErr_Occurred())
2444 wrap_delitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
2446 objobjargproc func
= (objobjargproc
)wrapped
;
2450 if (!PyArg_ParseTuple(args
, "O", &key
))
2452 res
= (*func
)(self
, key
, NULL
);
2453 if (res
== -1 && PyErr_Occurred())
2460 wrap_cmpfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2462 cmpfunc func
= (cmpfunc
)wrapped
;
2466 if (!PyArg_ParseTuple(args
, "O", &other
))
2468 if (other
->ob_type
->tp_compare
!= func
&&
2469 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
2472 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2473 self
->ob_type
->tp_name
,
2474 self
->ob_type
->tp_name
,
2475 other
->ob_type
->tp_name
);
2478 res
= (*func
)(self
, other
);
2479 if (PyErr_Occurred())
2481 return PyInt_FromLong((long)res
);
2485 wrap_setattr(PyObject
*self
, PyObject
*args
, void *wrapped
)
2487 setattrofunc func
= (setattrofunc
)wrapped
;
2489 PyObject
*name
, *value
;
2491 if (!PyArg_ParseTuple(args
, "OO", &name
, &value
))
2493 res
= (*func
)(self
, name
, value
);
2501 wrap_delattr(PyObject
*self
, PyObject
*args
, void *wrapped
)
2503 setattrofunc func
= (setattrofunc
)wrapped
;
2507 if (!PyArg_ParseTuple(args
, "O", &name
))
2509 res
= (*func
)(self
, name
, NULL
);
2517 wrap_hashfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
2519 hashfunc func
= (hashfunc
)wrapped
;
2522 if (!PyArg_ParseTuple(args
, ""))
2524 res
= (*func
)(self
);
2525 if (res
== -1 && PyErr_Occurred())
2527 return PyInt_FromLong(res
);
2531 wrap_call(PyObject
*self
, PyObject
*args
, void *wrapped
, PyObject
*kwds
)
2533 ternaryfunc func
= (ternaryfunc
)wrapped
;
2535 return (*func
)(self
, args
, kwds
);
2539 wrap_richcmpfunc(PyObject
*self
, PyObject
*args
, void *wrapped
, int op
)
2541 richcmpfunc func
= (richcmpfunc
)wrapped
;
2544 if (!PyArg_ParseTuple(args
, "O", &other
))
2546 return (*func
)(self
, other
, op
);
2549 #undef RICHCMP_WRAPPER
2550 #define RICHCMP_WRAPPER(NAME, OP) \
2552 richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2554 return wrap_richcmpfunc(self, args, wrapped, OP); \
2557 RICHCMP_WRAPPER(lt
, Py_LT
)
2558 RICHCMP_WRAPPER(le
, Py_LE
)
2559 RICHCMP_WRAPPER(eq
, Py_EQ
)
2560 RICHCMP_WRAPPER(ne
, Py_NE
)
2561 RICHCMP_WRAPPER(gt
, Py_GT
)
2562 RICHCMP_WRAPPER(ge
, Py_GE
)
2565 wrap_next(PyObject
*self
, PyObject
*args
, void *wrapped
)
2567 unaryfunc func
= (unaryfunc
)wrapped
;
2570 if (!PyArg_ParseTuple(args
, ""))
2572 res
= (*func
)(self
);
2573 if (res
== NULL
&& !PyErr_Occurred())
2574 PyErr_SetNone(PyExc_StopIteration
);
2579 wrap_descr_get(PyObject
*self
, PyObject
*args
, void *wrapped
)
2581 descrgetfunc func
= (descrgetfunc
)wrapped
;
2583 PyObject
*type
= NULL
;
2585 if (!PyArg_ParseTuple(args
, "O|O", &obj
, &type
))
2587 return (*func
)(self
, obj
, type
);
2591 wrap_descr_set(PyObject
*self
, PyObject
*args
, void *wrapped
)
2593 descrsetfunc func
= (descrsetfunc
)wrapped
;
2594 PyObject
*obj
, *value
;
2597 if (!PyArg_ParseTuple(args
, "OO", &obj
, &value
))
2599 ret
= (*func
)(self
, obj
, value
);
2607 wrap_init(PyObject
*self
, PyObject
*args
, void *wrapped
, PyObject
*kwds
)
2609 initproc func
= (initproc
)wrapped
;
2611 if (func(self
, args
, kwds
) < 0)
2618 tp_new_wrapper(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2620 PyTypeObject
*type
, *subtype
, *staticbase
;
2621 PyObject
*arg0
, *res
;
2623 if (self
== NULL
|| !PyType_Check(self
))
2624 Py_FatalError("__new__() called with non-type 'self'");
2625 type
= (PyTypeObject
*)self
;
2626 if (!PyTuple_Check(args
) || PyTuple_GET_SIZE(args
) < 1) {
2627 PyErr_Format(PyExc_TypeError
,
2628 "%s.__new__(): not enough arguments",
2632 arg0
= PyTuple_GET_ITEM(args
, 0);
2633 if (!PyType_Check(arg0
)) {
2634 PyErr_Format(PyExc_TypeError
,
2635 "%s.__new__(X): X is not a type object (%s)",
2637 arg0
->ob_type
->tp_name
);
2640 subtype
= (PyTypeObject
*)arg0
;
2641 if (!PyType_IsSubtype(subtype
, type
)) {
2642 PyErr_Format(PyExc_TypeError
,
2643 "%s.__new__(%s): %s is not a subtype of %s",
2651 /* Check that the use doesn't do something silly and unsafe like
2652 object.__new__(dict). To do this, we check that the
2653 most derived base that's not a heap type is this type. */
2654 staticbase
= subtype
;
2655 while (staticbase
&& (staticbase
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
2656 staticbase
= staticbase
->tp_base
;
2657 if (staticbase
->tp_new
!= type
->tp_new
) {
2658 PyErr_Format(PyExc_TypeError
,
2659 "%s.__new__(%s) is not safe, use %s.__new__()",
2662 staticbase
== NULL
? "?" : staticbase
->tp_name
);
2666 args
= PyTuple_GetSlice(args
, 1, PyTuple_GET_SIZE(args
));
2669 res
= type
->tp_new(subtype
, args
, kwds
);
2674 static struct PyMethodDef tp_new_methoddef
[] = {
2675 {"__new__", (PyCFunction
)tp_new_wrapper
, METH_KEYWORDS
,
2676 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
2681 add_tp_new_wrapper(PyTypeObject
*type
)
2685 if (PyDict_GetItemString(type
->tp_dict
, "__new__") != NULL
)
2687 func
= PyCFunction_New(tp_new_methoddef
, (PyObject
*)type
);
2690 return PyDict_SetItemString(type
->tp_dict
, "__new__", func
);
2693 /* Slot wrappers that call the corresponding __foo__ slot. See comments
2694 below at override_slots() for more explanation. */
2696 #define SLOT0(FUNCNAME, OPSTR) \
2698 FUNCNAME(PyObject *self) \
2700 static PyObject *cache_str; \
2701 return call_method(self, OPSTR, &cache_str, "()"); \
2704 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
2706 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
2708 static PyObject *cache_str; \
2709 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
2713 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
2715 FUNCNAME(PyObject *self, PyObject *other) \
2717 static PyObject *cache_str, *rcache_str; \
2718 int do_other = self->ob_type != other->ob_type && \
2719 other->ob_type->tp_as_number != NULL && \
2720 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
2721 if (self->ob_type->tp_as_number != NULL && \
2722 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2725 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2727 other, ROPSTR, &rcache_str, "(O)", self); \
2728 if (r != Py_NotImplemented) \
2734 self, OPSTR, &cache_str, "(O)", other); \
2735 if (r != Py_NotImplemented || \
2736 other->ob_type == self->ob_type) \
2741 return call_maybe( \
2742 other, ROPSTR, &rcache_str, "(O)", self); \
2744 Py_INCREF(Py_NotImplemented); \
2745 return Py_NotImplemented; \
2748 #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2749 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2751 #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2753 FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2755 static PyObject *cache_str; \
2756 return call_method(self, OPSTR, &cache_str, \
2757 "(" ARGCODES ")", arg1, arg2); \
2761 slot_sq_length(PyObject
*self
)
2763 static PyObject
*len_str
;
2764 PyObject
*res
= call_method(self
, "__len__", &len_str
, "()");
2769 len
= (int)PyInt_AsLong(res
);
2774 SLOT1(slot_sq_concat
, "__add__", PyObject
*, "O")
2775 SLOT1(slot_sq_repeat
, "__mul__", int, "i")
2777 /* Super-optimized version of slot_sq_item.
2778 Other slots could do the same... */
2780 slot_sq_item(PyObject
*self
, int i
)
2782 static PyObject
*getitem_str
;
2783 PyObject
*func
, *args
= NULL
, *ival
= NULL
, *retval
= NULL
;
2786 if (getitem_str
== NULL
) {
2787 getitem_str
= PyString_InternFromString("__getitem__");
2788 if (getitem_str
== NULL
)
2791 func
= _PyType_Lookup(self
->ob_type
, getitem_str
);
2793 if ((f
= func
->ob_type
->tp_descr_get
) == NULL
)
2796 func
= f(func
, self
, (PyObject
*)(self
->ob_type
));
2797 ival
= PyInt_FromLong(i
);
2799 args
= PyTuple_New(1);
2801 PyTuple_SET_ITEM(args
, 0, ival
);
2802 retval
= PyObject_Call(func
, args
, NULL
);
2810 PyErr_SetObject(PyExc_AttributeError
, getitem_str
);
2818 SLOT2(slot_sq_slice
, "__getslice__", int, int, "ii")
2821 slot_sq_ass_item(PyObject
*self
, int index
, PyObject
*value
)
2824 static PyObject
*delitem_str
, *setitem_str
;
2827 res
= call_method(self
, "__delitem__", &delitem_str
,
2830 res
= call_method(self
, "__setitem__", &setitem_str
,
2831 "(iO)", index
, value
);
2839 slot_sq_ass_slice(PyObject
*self
, int i
, int j
, PyObject
*value
)
2842 static PyObject
*delslice_str
, *setslice_str
;
2845 res
= call_method(self
, "__delslice__", &delslice_str
,
2848 res
= call_method(self
, "__setslice__", &setslice_str
,
2849 "(iiO)", i
, j
, value
);
2857 slot_sq_contains(PyObject
*self
, PyObject
*value
)
2859 PyObject
*func
, *res
, *args
;
2860 static PyObject
*contains_str
;
2862 func
= lookup_maybe(self
, "__contains__", &contains_str
);
2865 args
= Py_BuildValue("(O)", value
);
2869 res
= PyObject_Call(func
, args
, NULL
);
2875 return PyObject_IsTrue(res
);
2877 else if (PyErr_Occurred())
2880 return _PySequence_IterSearch(self
, value
,
2881 PY_ITERSEARCH_CONTAINS
);
2885 SLOT1(slot_sq_inplace_concat
, "__iadd__", PyObject
*, "O")
2886 SLOT1(slot_sq_inplace_repeat
, "__imul__", int, "i")
2888 #define slot_mp_length slot_sq_length
2890 SLOT1(slot_mp_subscript
, "__getitem__", PyObject
*, "O")
2893 slot_mp_ass_subscript(PyObject
*self
, PyObject
*key
, PyObject
*value
)
2896 static PyObject
*delitem_str
, *setitem_str
;
2899 res
= call_method(self
, "__delitem__", &delitem_str
,
2902 res
= call_method(self
, "__setitem__", &setitem_str
,
2903 "(OO)", key
, value
);
2910 SLOT1BIN(slot_nb_add
, nb_add
, "__add__", "__radd__")
2911 SLOT1BIN(slot_nb_subtract
, nb_subtract
, "__sub__", "__rsub__")
2912 SLOT1BIN(slot_nb_multiply
, nb_multiply
, "__mul__", "__rmul__")
2913 SLOT1BIN(slot_nb_divide
, nb_divide
, "__div__", "__rdiv__")
2914 SLOT1BIN(slot_nb_remainder
, nb_remainder
, "__mod__", "__rmod__")
2915 SLOT1BIN(slot_nb_divmod
, nb_divmod
, "__divmod__", "__rdivmod__")
2917 staticforward PyObject
*slot_nb_power(PyObject
*, PyObject
*, PyObject
*);
2919 SLOT1BINFULL(slot_nb_power_binary
, slot_nb_power
,
2920 nb_power
, "__pow__", "__rpow__")
2923 slot_nb_power(PyObject
*self
, PyObject
*other
, PyObject
*modulus
)
2925 static PyObject
*pow_str
;
2927 if (modulus
== Py_None
)
2928 return slot_nb_power_binary(self
, other
);
2929 /* Three-arg power doesn't use __rpow__ */
2930 return call_method(self
, "__pow__", &pow_str
,
2931 "(OO)", other
, modulus
);
2934 SLOT0(slot_nb_negative
, "__neg__")
2935 SLOT0(slot_nb_positive
, "__pos__")
2936 SLOT0(slot_nb_absolute
, "__abs__")
2939 slot_nb_nonzero(PyObject
*self
)
2941 PyObject
*func
, *res
;
2942 static PyObject
*nonzero_str
, *len_str
;
2944 func
= lookup_maybe(self
, "__nonzero__", &nonzero_str
);
2946 if (PyErr_Occurred())
2948 func
= lookup_maybe(self
, "__len__", &len_str
);
2950 if (PyErr_Occurred())
2956 res
= PyObject_CallObject(func
, NULL
);
2960 return PyObject_IsTrue(res
);
2963 SLOT0(slot_nb_invert
, "__invert__")
2964 SLOT1BIN(slot_nb_lshift
, nb_lshift
, "__lshift__", "__rlshift__")
2965 SLOT1BIN(slot_nb_rshift
, nb_rshift
, "__rshift__", "__rrshift__")
2966 SLOT1BIN(slot_nb_and
, nb_and
, "__and__", "__rand__")
2967 SLOT1BIN(slot_nb_xor
, nb_xor
, "__xor__", "__rxor__")
2968 SLOT1BIN(slot_nb_or
, nb_or
, "__or__", "__ror__")
2971 slot_nb_coerce(PyObject
**a
, PyObject
**b
)
2973 static PyObject
*coerce_str
;
2974 PyObject
*self
= *a
, *other
= *b
;
2976 if (self
->ob_type
->tp_as_number
!= NULL
&&
2977 self
->ob_type
->tp_as_number
->nb_coerce
== slot_nb_coerce
) {
2980 self
, "__coerce__", &coerce_str
, "(O)", other
);
2983 if (r
== Py_NotImplemented
) {
2987 if (!PyTuple_Check(r
) || PyTuple_GET_SIZE(r
) != 2) {
2988 PyErr_SetString(PyExc_TypeError
,
2989 "__coerce__ didn't return a 2-tuple");
2993 *a
= PyTuple_GET_ITEM(r
, 0);
2995 *b
= PyTuple_GET_ITEM(r
, 1);
3001 if (other
->ob_type
->tp_as_number
!= NULL
&&
3002 other
->ob_type
->tp_as_number
->nb_coerce
== slot_nb_coerce
) {
3005 other
, "__coerce__", &coerce_str
, "(O)", self
);
3008 if (r
== Py_NotImplemented
) {
3012 if (!PyTuple_Check(r
) || PyTuple_GET_SIZE(r
) != 2) {
3013 PyErr_SetString(PyExc_TypeError
,
3014 "__coerce__ didn't return a 2-tuple");
3018 *a
= PyTuple_GET_ITEM(r
, 1);
3020 *b
= PyTuple_GET_ITEM(r
, 0);
3028 SLOT0(slot_nb_int
, "__int__")
3029 SLOT0(slot_nb_long
, "__long__")
3030 SLOT0(slot_nb_float
, "__float__")
3031 SLOT0(slot_nb_oct
, "__oct__")
3032 SLOT0(slot_nb_hex
, "__hex__")
3033 SLOT1(slot_nb_inplace_add
, "__iadd__", PyObject
*, "O")
3034 SLOT1(slot_nb_inplace_subtract
, "__isub__", PyObject
*, "O")
3035 SLOT1(slot_nb_inplace_multiply
, "__imul__", PyObject
*, "O")
3036 SLOT1(slot_nb_inplace_divide
, "__idiv__", PyObject
*, "O")
3037 SLOT1(slot_nb_inplace_remainder
, "__imod__", PyObject
*, "O")
3038 SLOT2(slot_nb_inplace_power
, "__ipow__", PyObject
*, PyObject
*, "OO")
3039 SLOT1(slot_nb_inplace_lshift
, "__ilshift__", PyObject
*, "O")
3040 SLOT1(slot_nb_inplace_rshift
, "__irshift__", PyObject
*, "O")
3041 SLOT1(slot_nb_inplace_and
, "__iand__", PyObject
*, "O")
3042 SLOT1(slot_nb_inplace_xor
, "__ixor__", PyObject
*, "O")
3043 SLOT1(slot_nb_inplace_or
, "__ior__", PyObject
*, "O")
3044 SLOT1BIN(slot_nb_floor_divide
, nb_floor_divide
,
3045 "__floordiv__", "__rfloordiv__")
3046 SLOT1BIN(slot_nb_true_divide
, nb_true_divide
, "__truediv__", "__rtruediv__")
3047 SLOT1(slot_nb_inplace_floor_divide
, "__ifloordiv__", PyObject
*, "O")
3048 SLOT1(slot_nb_inplace_true_divide
, "__itruediv__", PyObject
*, "O")
3051 half_compare(PyObject
*self
, PyObject
*other
)
3053 PyObject
*func
, *args
, *res
;
3054 static PyObject
*cmp_str
;
3057 func
= lookup_method(self
, "__cmp__", &cmp_str
);
3062 args
= Py_BuildValue("(O)", other
);
3066 res
= PyObject_Call(func
, args
, NULL
);
3069 if (res
!= Py_NotImplemented
) {
3072 c
= PyInt_AsLong(res
);
3074 if (c
== -1 && PyErr_Occurred())
3076 return (c
< 0) ? -1 : (c
> 0) ? 1 : 0;
3083 /* This slot is published for the benefit of try_3way_compare in object.c */
3085 _PyObject_SlotCompare(PyObject
*self
, PyObject
*other
)
3089 if (self
->ob_type
->tp_compare
== _PyObject_SlotCompare
) {
3090 c
= half_compare(self
, other
);
3094 if (other
->ob_type
->tp_compare
== _PyObject_SlotCompare
) {
3095 c
= half_compare(other
, self
);
3101 return (void *)self
< (void *)other
? -1 :
3102 (void *)self
> (void *)other
? 1 : 0;
3106 slot_tp_repr(PyObject
*self
)
3108 PyObject
*func
, *res
;
3109 static PyObject
*repr_str
;
3111 func
= lookup_method(self
, "__repr__", &repr_str
);
3113 res
= PyEval_CallObject(func
, NULL
);
3118 return PyString_FromFormat("<%s object at %p>",
3119 self
->ob_type
->tp_name
, self
);
3123 slot_tp_str(PyObject
*self
)
3125 PyObject
*func
, *res
;
3126 static PyObject
*str_str
;
3128 func
= lookup_method(self
, "__str__", &str_str
);
3130 res
= PyEval_CallObject(func
, NULL
);
3136 return slot_tp_repr(self
);
3141 slot_tp_hash(PyObject
*self
)
3143 PyObject
*func
, *res
;
3144 static PyObject
*hash_str
, *eq_str
, *cmp_str
;
3148 func
= lookup_method(self
, "__hash__", &hash_str
);
3151 res
= PyEval_CallObject(func
, NULL
);
3155 h
= PyInt_AsLong(res
);
3159 func
= lookup_method(self
, "__eq__", &eq_str
);
3162 func
= lookup_method(self
, "__cmp__", &cmp_str
);
3166 PyErr_SetString(PyExc_TypeError
, "unhashable type");
3170 h
= _Py_HashPointer((void *)self
);
3172 if (h
== -1 && !PyErr_Occurred())
3178 slot_tp_call(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
3180 static PyObject
*call_str
;
3181 PyObject
*meth
= lookup_method(self
, "__call__", &call_str
);
3186 res
= PyObject_Call(meth
, args
, kwds
);
3191 /* There are two slot dispatch functions for tp_getattro.
3193 - slot_tp_getattro() is used when __getattribute__ is overridden
3194 but no __getattr__ hook is present;
3196 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3198 The code in update_slot() and fixup_slot_dispatchers() always installs
3199 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3200 installs the simpler slot if necessary. */
3203 slot_tp_getattro(PyObject
*self
, PyObject
*name
)
3205 static PyObject
*getattribute_str
= NULL
;
3206 return call_method(self
, "__getattribute__", &getattribute_str
,
3211 slot_tp_getattr_hook(PyObject
*self
, PyObject
*name
)
3213 PyTypeObject
*tp
= self
->ob_type
;
3214 PyObject
*getattr
, *getattribute
, *res
;
3215 static PyObject
*getattribute_str
= NULL
;
3216 static PyObject
*getattr_str
= NULL
;
3218 if (getattr_str
== NULL
) {
3219 getattr_str
= PyString_InternFromString("__getattr__");
3220 if (getattr_str
== NULL
)
3223 if (getattribute_str
== NULL
) {
3225 PyString_InternFromString("__getattribute__");
3226 if (getattribute_str
== NULL
)
3229 getattr
= _PyType_Lookup(tp
, getattr_str
);
3230 if (getattr
== NULL
) {
3231 /* No __getattr__ hook: use a simpler dispatcher */
3232 tp
->tp_getattro
= slot_tp_getattro
;
3233 return slot_tp_getattro(self
, name
);
3235 getattribute
= _PyType_Lookup(tp
, getattribute_str
);
3236 if (getattribute
== NULL
||
3237 (getattribute
->ob_type
== &PyWrapperDescr_Type
&&
3238 ((PyWrapperDescrObject
*)getattribute
)->d_wrapped
==
3239 (void *)PyObject_GenericGetAttr
))
3240 res
= PyObject_GenericGetAttr(self
, name
);
3242 res
= PyObject_CallFunction(getattribute
, "OO", self
, name
);
3243 if (res
== NULL
&& PyErr_ExceptionMatches(PyExc_AttributeError
)) {
3245 res
= PyObject_CallFunction(getattr
, "OO", self
, name
);
3251 slot_tp_setattro(PyObject
*self
, PyObject
*name
, PyObject
*value
)
3254 static PyObject
*delattr_str
, *setattr_str
;
3257 res
= call_method(self
, "__delattr__", &delattr_str
,
3260 res
= call_method(self
, "__setattr__", &setattr_str
,
3261 "(OO)", name
, value
);
3268 /* Map rich comparison operators to their __xx__ namesakes */
3269 static char *name_op
[] = {
3279 half_richcompare(PyObject
*self
, PyObject
*other
, int op
)
3281 PyObject
*func
, *args
, *res
;
3282 static PyObject
*op_str
[6];
3284 func
= lookup_method(self
, name_op
[op
], &op_str
[op
]);
3287 Py_INCREF(Py_NotImplemented
);
3288 return Py_NotImplemented
;
3290 args
= Py_BuildValue("(O)", other
);
3294 res
= PyObject_Call(func
, args
, NULL
);
3301 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3302 static int swapped_op
[] = {Py_GT
, Py_GE
, Py_EQ
, Py_NE
, Py_LT
, Py_LE
};
3305 slot_tp_richcompare(PyObject
*self
, PyObject
*other
, int op
)
3309 if (self
->ob_type
->tp_richcompare
== slot_tp_richcompare
) {
3310 res
= half_richcompare(self
, other
, op
);
3311 if (res
!= Py_NotImplemented
)
3315 if (other
->ob_type
->tp_richcompare
== slot_tp_richcompare
) {
3316 res
= half_richcompare(other
, self
, swapped_op
[op
]);
3317 if (res
!= Py_NotImplemented
) {
3322 Py_INCREF(Py_NotImplemented
);
3323 return Py_NotImplemented
;
3327 slot_tp_iter(PyObject
*self
)
3329 PyObject
*func
, *res
;
3330 static PyObject
*iter_str
, *getitem_str
;
3332 func
= lookup_method(self
, "__iter__", &iter_str
);
3334 res
= PyObject_CallObject(func
, NULL
);
3339 func
= lookup_method(self
, "__getitem__", &getitem_str
);
3341 PyErr_SetString(PyExc_TypeError
, "iteration over non-sequence");
3345 return PySeqIter_New(self
);
3349 slot_tp_iternext(PyObject
*self
)
3351 static PyObject
*next_str
;
3352 return call_method(self
, "next", &next_str
, "()");
3356 slot_tp_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
3358 PyTypeObject
*tp
= self
->ob_type
;
3360 static PyObject
*get_str
= NULL
;
3362 if (get_str
== NULL
) {
3363 get_str
= PyString_InternFromString("__get__");
3364 if (get_str
== NULL
)
3367 get
= _PyType_Lookup(tp
, get_str
);
3369 /* Avoid further slowdowns */
3370 if (tp
->tp_descr_get
== slot_tp_descr_get
)
3371 tp
->tp_descr_get
= NULL
;
3379 return PyObject_CallFunction(get
, "OOO", self
, obj
, type
);
3383 slot_tp_descr_set(PyObject
*self
, PyObject
*target
, PyObject
*value
)
3386 static PyObject
*del_str
, *set_str
;
3389 res
= call_method(self
, "__delete__", &del_str
,
3392 res
= call_method(self
, "__set__", &set_str
,
3393 "(OO)", target
, value
);
3401 slot_tp_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
3403 static PyObject
*init_str
;
3404 PyObject
*meth
= lookup_method(self
, "__init__", &init_str
);
3409 res
= PyObject_Call(meth
, args
, kwds
);
3418 slot_tp_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3420 PyObject
*func
= PyObject_GetAttrString((PyObject
*)type
, "__new__");
3421 PyObject
*newargs
, *x
;
3426 assert(PyTuple_Check(args
));
3427 n
= PyTuple_GET_SIZE(args
);
3428 newargs
= PyTuple_New(n
+1);
3429 if (newargs
== NULL
)
3432 PyTuple_SET_ITEM(newargs
, 0, (PyObject
*)type
);
3433 for (i
= 0; i
< n
; i
++) {
3434 x
= PyTuple_GET_ITEM(args
, i
);
3436 PyTuple_SET_ITEM(newargs
, i
+1, x
);
3438 x
= PyObject_Call(func
, newargs
, kwds
);
3445 /* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3446 functions. The offsets here are relative to the 'etype' structure, which
3447 incorporates the additional structures used for numbers, sequences and
3448 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3449 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3450 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3452 typedef struct wrapperbase slotdef
;
3465 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3466 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3467 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3468 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3470 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3471 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3472 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3473 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3474 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3475 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3476 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3477 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3478 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3479 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3480 "x." NAME "() <==> " DOC)
3481 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3482 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3483 "x." NAME "(y) <==> x" DOC "y")
3484 #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3485 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3486 "x." NAME "(y) <==> x" DOC "y")
3487 #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3488 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3489 "x." NAME "(y) <==> y" DOC "x")
3491 static slotdef slotdefs
[] = {
3492 SQSLOT("__len__", sq_length
, slot_sq_length
, wrap_inquiry
,
3493 "x.__len__() <==> len(x)"),
3494 SQSLOT("__add__", sq_concat
, slot_sq_concat
, wrap_binaryfunc
,
3495 "x.__add__(y) <==> x+y"),
3496 SQSLOT("__mul__", sq_repeat
, slot_sq_repeat
, wrap_intargfunc
,
3497 "x.__mul__(n) <==> x*n"),
3498 SQSLOT("__rmul__", sq_repeat
, slot_sq_repeat
, wrap_intargfunc
,
3499 "x.__rmul__(n) <==> n*x"),
3500 SQSLOT("__getitem__", sq_item
, slot_sq_item
, wrap_sq_item
,
3501 "x.__getitem__(y) <==> x[y]"),
3502 SQSLOT("__getslice__", sq_slice
, slot_sq_slice
, wrap_intintargfunc
,
3503 "x.__getslice__(i, j) <==> x[i:j]"),
3504 SQSLOT("__setitem__", sq_ass_item
, slot_sq_ass_item
, wrap_sq_setitem
,
3505 "x.__setitem__(i, y) <==> x[i]=y"),
3506 SQSLOT("__delitem__", sq_ass_item
, slot_sq_ass_item
, wrap_sq_delitem
,
3507 "x.__delitem__(y) <==> del x[y]"),
3508 SQSLOT("__setslice__", sq_ass_slice
, slot_sq_ass_slice
,
3509 wrap_intintobjargproc
,
3510 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3511 SQSLOT("__delslice__", sq_ass_slice
, slot_sq_ass_slice
, wrap_delslice
,
3512 "x.__delslice__(i, j) <==> del x[i:j]"),
3513 SQSLOT("__contains__", sq_contains
, slot_sq_contains
, wrap_objobjproc
,
3514 "x.__contains__(y) <==> y in x"),
3515 SQSLOT("__iadd__", sq_inplace_concat
, slot_sq_inplace_concat
,
3516 wrap_binaryfunc
, "x.__iadd__(y) <==> x+=y"),
3517 SQSLOT("__imul__", sq_inplace_repeat
, slot_sq_inplace_repeat
,
3518 wrap_intargfunc
, "x.__imul__(y) <==> x*=y"),
3520 MPSLOT("__len__", mp_length
, slot_mp_length
, wrap_inquiry
,
3521 "x.__len__() <==> len(x)"),
3522 MPSLOT("__getitem__", mp_subscript
, slot_mp_subscript
,
3524 "x.__getitem__(y) <==> x[y]"),
3525 MPSLOT("__setitem__", mp_ass_subscript
, slot_mp_ass_subscript
,
3527 "x.__setitem__(i, y) <==> x[i]=y"),
3528 MPSLOT("__delitem__", mp_ass_subscript
, slot_mp_ass_subscript
,
3530 "x.__delitem__(y) <==> del x[y]"),
3532 BINSLOT("__add__", nb_add
, slot_nb_add
,
3534 RBINSLOT("__radd__", nb_add
, slot_nb_add
,
3536 BINSLOT("__sub__", nb_subtract
, slot_nb_subtract
,
3538 RBINSLOT("__rsub__", nb_subtract
, slot_nb_subtract
,
3540 BINSLOT("__mul__", nb_multiply
, slot_nb_multiply
,
3542 RBINSLOT("__rmul__", nb_multiply
, slot_nb_multiply
,
3544 BINSLOT("__div__", nb_divide
, slot_nb_divide
,
3546 RBINSLOT("__rdiv__", nb_divide
, slot_nb_divide
,
3548 BINSLOT("__mod__", nb_remainder
, slot_nb_remainder
,
3550 RBINSLOT("__rmod__", nb_remainder
, slot_nb_remainder
,
3552 BINSLOT("__divmod__", nb_divmod
, slot_nb_divmod
,
3554 RBINSLOT("__rdivmod__", nb_divmod
, slot_nb_divmod
,
3556 NBSLOT("__pow__", nb_power
, slot_nb_power
, wrap_ternaryfunc
,
3557 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3558 NBSLOT("__rpow__", nb_power
, slot_nb_power
, wrap_ternaryfunc_r
,
3559 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3560 UNSLOT("__neg__", nb_negative
, slot_nb_negative
, wrap_unaryfunc
, "-x"),
3561 UNSLOT("__pos__", nb_positive
, slot_nb_positive
, wrap_unaryfunc
, "+x"),
3562 UNSLOT("__abs__", nb_absolute
, slot_nb_absolute
, wrap_unaryfunc
,
3564 UNSLOT("__nonzero__", nb_nonzero
, slot_nb_nonzero
, wrap_inquiry
,
3566 UNSLOT("__invert__", nb_invert
, slot_nb_invert
, wrap_unaryfunc
, "~x"),
3567 BINSLOT("__lshift__", nb_lshift
, slot_nb_lshift
, "<<"),
3568 RBINSLOT("__rlshift__", nb_lshift
, slot_nb_lshift
, "<<"),
3569 BINSLOT("__rshift__", nb_rshift
, slot_nb_rshift
, ">>"),
3570 RBINSLOT("__rrshift__", nb_rshift
, slot_nb_rshift
, ">>"),
3571 BINSLOT("__and__", nb_and
, slot_nb_and
, "&"),
3572 RBINSLOT("__rand__", nb_and
, slot_nb_and
, "&"),
3573 BINSLOT("__xor__", nb_xor
, slot_nb_xor
, "^"),
3574 RBINSLOT("__rxor__", nb_xor
, slot_nb_xor
, "^"),
3575 BINSLOT("__or__", nb_or
, slot_nb_or
, "|"),
3576 RBINSLOT("__ror__", nb_or
, slot_nb_or
, "|"),
3577 NBSLOT("__coerce__", nb_coerce
, slot_nb_coerce
, wrap_coercefunc
,
3578 "x.__coerce__(y) <==> coerce(x, y)"),
3579 UNSLOT("__int__", nb_int
, slot_nb_int
, wrap_unaryfunc
,
3581 UNSLOT("__long__", nb_long
, slot_nb_long
, wrap_unaryfunc
,
3583 UNSLOT("__float__", nb_float
, slot_nb_float
, wrap_unaryfunc
,
3585 UNSLOT("__oct__", nb_oct
, slot_nb_oct
, wrap_unaryfunc
,
3587 UNSLOT("__hex__", nb_hex
, slot_nb_hex
, wrap_unaryfunc
,
3589 IBSLOT("__iadd__", nb_inplace_add
, slot_nb_inplace_add
,
3590 wrap_binaryfunc
, "+"),
3591 IBSLOT("__isub__", nb_inplace_subtract
, slot_nb_inplace_subtract
,
3592 wrap_binaryfunc
, "-"),
3593 IBSLOT("__imul__", nb_inplace_multiply
, slot_nb_inplace_multiply
,
3594 wrap_binaryfunc
, "*"),
3595 IBSLOT("__idiv__", nb_inplace_divide
, slot_nb_inplace_divide
,
3596 wrap_binaryfunc
, "/"),
3597 IBSLOT("__imod__", nb_inplace_remainder
, slot_nb_inplace_remainder
,
3598 wrap_binaryfunc
, "%"),
3599 IBSLOT("__ipow__", nb_inplace_power
, slot_nb_inplace_power
,
3600 wrap_ternaryfunc
, "**"),
3601 IBSLOT("__ilshift__", nb_inplace_lshift
, slot_nb_inplace_lshift
,
3602 wrap_binaryfunc
, "<<"),
3603 IBSLOT("__irshift__", nb_inplace_rshift
, slot_nb_inplace_rshift
,
3604 wrap_binaryfunc
, ">>"),
3605 IBSLOT("__iand__", nb_inplace_and
, slot_nb_inplace_and
,
3606 wrap_binaryfunc
, "&"),
3607 IBSLOT("__ixor__", nb_inplace_xor
, slot_nb_inplace_xor
,
3608 wrap_binaryfunc
, "^"),
3609 IBSLOT("__ior__", nb_inplace_or
, slot_nb_inplace_or
,
3610 wrap_binaryfunc
, "|"),
3611 BINSLOT("__floordiv__", nb_floor_divide
, slot_nb_floor_divide
, "//"),
3612 RBINSLOT("__rfloordiv__", nb_floor_divide
, slot_nb_floor_divide
, "//"),
3613 BINSLOT("__truediv__", nb_true_divide
, slot_nb_true_divide
, "/"),
3614 RBINSLOT("__rtruediv__", nb_true_divide
, slot_nb_true_divide
, "/"),
3615 IBSLOT("__ifloordiv__", nb_inplace_floor_divide
,
3616 slot_nb_inplace_floor_divide
, wrap_binaryfunc
, "//"),
3617 IBSLOT("__itruediv__", nb_inplace_true_divide
,
3618 slot_nb_inplace_true_divide
, wrap_binaryfunc
, "/"),
3620 TPSLOT("__str__", tp_str
, slot_tp_str
, wrap_unaryfunc
,
3621 "x.__str__() <==> str(x)"),
3622 TPSLOT("__str__", tp_print
, NULL
, NULL
, ""),
3623 TPSLOT("__repr__", tp_repr
, slot_tp_repr
, wrap_unaryfunc
,
3624 "x.__repr__() <==> repr(x)"),
3625 TPSLOT("__repr__", tp_print
, NULL
, NULL
, ""),
3626 TPSLOT("__cmp__", tp_compare
, _PyObject_SlotCompare
, wrap_cmpfunc
,
3627 "x.__cmp__(y) <==> cmp(x,y)"),
3628 TPSLOT("__hash__", tp_hash
, slot_tp_hash
, wrap_hashfunc
,
3629 "x.__hash__() <==> hash(x)"),
3630 FLSLOT("__call__", tp_call
, slot_tp_call
, (wrapperfunc
)wrap_call
,
3631 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS
),
3632 TPSLOT("__getattribute__", tp_getattro
, slot_tp_getattr_hook
,
3633 wrap_binaryfunc
, "x.__getattribute__('name') <==> x.name"),
3634 TPSLOT("__getattribute__", tp_getattr
, NULL
, NULL
, ""),
3635 TPSLOT("__getattr__", tp_getattro
, slot_tp_getattr_hook
, NULL
, ""),
3636 TPSLOT("__getattr__", tp_getattr
, NULL
, NULL
, ""),
3637 TPSLOT("__setattr__", tp_setattro
, slot_tp_setattro
, wrap_setattr
,
3638 "x.__setattr__('name', value) <==> x.name = value"),
3639 TPSLOT("__setattr__", tp_setattr
, NULL
, NULL
, ""),
3640 TPSLOT("__delattr__", tp_setattro
, slot_tp_setattro
, wrap_delattr
,
3641 "x.__delattr__('name') <==> del x.name"),
3642 TPSLOT("__delattr__", tp_setattr
, NULL
, NULL
, ""),
3643 TPSLOT("__lt__", tp_richcompare
, slot_tp_richcompare
, richcmp_lt
,
3644 "x.__lt__(y) <==> x<y"),
3645 TPSLOT("__le__", tp_richcompare
, slot_tp_richcompare
, richcmp_le
,
3646 "x.__le__(y) <==> x<=y"),
3647 TPSLOT("__eq__", tp_richcompare
, slot_tp_richcompare
, richcmp_eq
,
3648 "x.__eq__(y) <==> x==y"),
3649 TPSLOT("__ne__", tp_richcompare
, slot_tp_richcompare
, richcmp_ne
,
3650 "x.__ne__(y) <==> x!=y"),
3651 TPSLOT("__gt__", tp_richcompare
, slot_tp_richcompare
, richcmp_gt
,
3652 "x.__gt__(y) <==> x>y"),
3653 TPSLOT("__ge__", tp_richcompare
, slot_tp_richcompare
, richcmp_ge
,
3654 "x.__ge__(y) <==> x>=y"),
3655 TPSLOT("__iter__", tp_iter
, slot_tp_iter
, wrap_unaryfunc
,
3656 "x.__iter__() <==> iter(x)"),
3657 TPSLOT("next", tp_iternext
, slot_tp_iternext
, wrap_next
,
3658 "x.next() -> the next value, or raise StopIteration"),
3659 TPSLOT("__get__", tp_descr_get
, slot_tp_descr_get
, wrap_descr_get
,
3660 "descr.__get__(obj[, type]) -> value"),
3661 TPSLOT("__set__", tp_descr_set
, slot_tp_descr_set
, wrap_descr_set
,
3662 "descr.__set__(obj, value)"),
3663 FLSLOT("__init__", tp_init
, slot_tp_init
, (wrapperfunc
)wrap_init
,
3664 "x.__init__(...) initializes x; "
3665 "see x.__class__.__doc__ for signature",
3666 PyWrapperFlag_KEYWORDS
),
3667 TPSLOT("__new__", tp_new
, slot_tp_new
, NULL
, ""),
3672 slotptr(PyTypeObject
*type
, int offset
)
3676 assert(offset
>= 0);
3677 assert(offset
< offsetof(etype
, as_buffer
));
3678 if (offset
>= offsetof(etype
, as_mapping
)) {
3679 ptr
= (void *)type
->tp_as_mapping
;
3680 offset
-= offsetof(etype
, as_mapping
);
3682 else if (offset
>= offsetof(etype
, as_sequence
)) {
3683 ptr
= (void *)type
->tp_as_sequence
;
3684 offset
-= offsetof(etype
, as_sequence
);
3686 else if (offset
>= offsetof(etype
, as_number
)) {
3687 ptr
= (void *)type
->tp_as_number
;
3688 offset
-= offsetof(etype
, as_number
);
3695 return (void **)ptr
;
3698 staticforward
int recurse_down_subclasses(PyTypeObject
*type
,
3699 slotdef
**pp
, PyObject
*name
);
3702 update_these_slots(PyTypeObject
*type
, slotdef
**pp0
, PyObject
*name
)
3706 for (pp
= pp0
; *pp
; pp
++) {
3709 PyWrapperDescrObject
*d
;
3710 void *generic
= NULL
, *specific
= NULL
;
3711 int use_generic
= 0;
3712 int offset
= p
->offset
;
3713 void **ptr
= slotptr(type
, offset
);
3717 descr
= _PyType_Lookup(type
, p
->name_strobj
);
3720 generic
= p
->function
;
3721 if (descr
->ob_type
== &PyWrapperDescr_Type
) {
3722 d
= (PyWrapperDescrObject
*)descr
;
3723 if (d
->d_base
->wrapper
== p
->wrapper
&&
3724 PyType_IsSubtype(type
, d
->d_type
)) {
3725 if (specific
== NULL
||
3726 specific
== d
->d_wrapped
)
3727 specific
= d
->d_wrapped
;
3734 } while ((++p
)->offset
== offset
);
3735 if (specific
&& !use_generic
)
3740 return recurse_down_subclasses(type
, pp0
, name
);
3744 recurse_down_subclasses(PyTypeObject
*type
, slotdef
**pp
, PyObject
*name
)
3746 PyTypeObject
*subclass
;
3747 PyObject
*ref
, *subclasses
, *dict
;
3750 subclasses
= type
->tp_subclasses
;
3751 if (subclasses
== NULL
)
3753 assert(PyList_Check(subclasses
));
3754 n
= PyList_GET_SIZE(subclasses
);
3755 for (i
= 0; i
< n
; i
++) {
3756 ref
= PyList_GET_ITEM(subclasses
, i
);
3757 assert(PyWeakref_CheckRef(ref
));
3758 subclass
= (PyTypeObject
*)PyWeakref_GET_OBJECT(ref
);
3759 if (subclass
== NULL
)
3761 assert(PyType_Check(subclass
));
3762 /* Avoid recursing down into unaffected classes */
3763 dict
= subclass
->tp_dict
;
3764 if (dict
!= NULL
&& PyDict_Check(dict
) &&
3765 PyDict_GetItem(dict
, name
) != NULL
)
3767 if (update_these_slots(subclass
, pp
, name
) < 0)
3774 slotdef_cmp(const void *aa
, const void *bb
)
3776 const slotdef
*a
= (const slotdef
*)aa
, *b
= (const slotdef
*)bb
;
3777 int c
= a
->offset
- b
->offset
;
3788 static int initialized
= 0;
3792 for (p
= slotdefs
; p
->name
; p
++) {
3793 p
->name_strobj
= PyString_InternFromString(p
->name
);
3794 if (!p
->name_strobj
)
3795 Py_FatalError("XXX ouch");
3797 qsort((void *)slotdefs
, (size_t)(p
-slotdefs
), sizeof(slotdef
),
3803 update_slot(PyTypeObject
*type
, PyObject
*name
)
3812 for (p
= slotdefs
; p
->name
; p
++) {
3813 /* XXX assume name is interned! */
3814 if (p
->name_strobj
== name
)
3818 for (pp
= ptrs
; *pp
; pp
++) {
3821 while (p
> slotdefs
&& (p
-1)->offset
== offset
)
3825 return update_these_slots(type
, ptrs
, name
);
3829 fixup_slot_dispatchers(PyTypeObject
*type
)
3832 PyObject
*mro
, *descr
;
3833 PyWrapperDescrObject
*d
;
3836 void *generic
, *specific
;
3841 assert(PyTuple_Check(mro
));
3842 n
= PyTuple_GET_SIZE(mro
);
3843 for (p
= slotdefs
; p
->name
; ) {
3845 ptr
= slotptr(type
, offset
);
3849 } while (p
->offset
== offset
);
3852 generic
= specific
= NULL
;
3856 for (i
= 0; i
< n
; i
++) {
3857 PyObject
*b
= PyTuple_GET_ITEM(mro
, i
);
3858 PyObject
*dict
= NULL
;
3859 if (PyType_Check(b
))
3860 dict
= ((PyTypeObject
*)b
)->tp_dict
;
3861 else if (PyClass_Check(b
))
3862 dict
= ((PyClassObject
*)b
)->cl_dict
;
3864 descr
= PyDict_GetItem(
3865 dict
, p
->name_strobj
);
3872 generic
= p
->function
;
3873 if (descr
->ob_type
== &PyWrapperDescr_Type
) {
3874 d
= (PyWrapperDescrObject
*)descr
;
3875 if (d
->d_base
->wrapper
== p
->wrapper
&&
3876 PyType_IsSubtype(type
, d
->d_type
))
3878 if (specific
== NULL
||
3879 specific
== d
->d_wrapped
)
3880 specific
= d
->d_wrapped
;
3887 } while ((++p
)->offset
== offset
);
3888 if (specific
&& !use_generic
)
3895 /* This function is called by PyType_Ready() to populate the type's
3896 dictionary with method descriptors for function slots. For each
3897 function slot (like tp_repr) that's defined in the type, one or
3898 more corresponding descriptors are added in the type's tp_dict
3899 dictionary under the appropriate name (like __repr__). Some
3900 function slots cause more than one descriptor to be added (for
3901 example, the nb_add slot adds both __add__ and __radd__
3902 descriptors) and some function slots compete for the same
3903 descriptor (for example both sq_item and mp_subscript generate a
3904 __getitem__ descriptor). This only adds new descriptors and
3905 doesn't overwrite entries in tp_dict that were previously
3906 defined. The descriptors contain a reference to the C function
3907 they must call, so that it's safe if they are copied into a
3908 subtype's __dict__ and the subtype has a different C function in
3909 its slot -- calling the method defined by the descriptor will call
3910 the C function that was used to create it, rather than the C
3911 function present in the slot when it is called. (This is important
3912 because a subtype may have a C function in the slot that calls the
3913 method from the dictionary, and we want to avoid infinite recursion
3917 add_operators(PyTypeObject
*type
)
3919 PyObject
*dict
= type
->tp_dict
;
3925 for (p
= slotdefs
; p
->name
; p
++) {
3926 if (p
->wrapper
== NULL
)
3928 ptr
= slotptr(type
, p
->offset
);
3931 if (PyDict_GetItem(dict
, p
->name_strobj
))
3933 descr
= PyDescr_NewWrapper(type
, p
, *ptr
);
3936 if (PyDict_SetItem(dict
, p
->name_strobj
, descr
) < 0)
3940 if (type
->tp_new
!= NULL
) {
3941 if (add_tp_new_wrapper(type
) < 0)
3948 /* Cooperative 'super' */
3956 static PyMemberDef super_members
[] = {
3957 {"__thisclass__", T_OBJECT
, offsetof(superobject
, type
), READONLY
,
3958 "the class invoking super()"},
3959 {"__self__", T_OBJECT
, offsetof(superobject
, obj
), READONLY
,
3960 "the instance invoking super(); may be None"},
3965 super_dealloc(PyObject
*self
)
3967 superobject
*su
= (superobject
*)self
;
3969 _PyObject_GC_UNTRACK(self
);
3970 Py_XDECREF(su
->obj
);
3971 Py_XDECREF(su
->type
);
3972 self
->ob_type
->tp_free(self
);
3976 super_repr(PyObject
*self
)
3978 superobject
*su
= (superobject
*)self
;
3981 return PyString_FromFormat(
3982 "<super: <class '%s'>, <%s object>>",
3983 su
->type
? su
->type
->tp_name
: "NULL",
3984 su
->obj
->ob_type
->tp_name
);
3986 return PyString_FromFormat(
3987 "<super: <class '%s'>, NULL>",
3988 su
->type
? su
->type
->tp_name
: "NULL");
3992 super_getattro(PyObject
*self
, PyObject
*name
)
3994 superobject
*su
= (superobject
*)self
;
3996 if (su
->obj
!= NULL
) {
3997 PyObject
*mro
, *res
, *tmp
, *dict
;
3998 PyTypeObject
*starttype
;
4002 starttype
= su
->obj
->ob_type
;
4003 mro
= starttype
->tp_mro
;
4008 assert(PyTuple_Check(mro
));
4009 n
= PyTuple_GET_SIZE(mro
);
4011 for (i
= 0; i
< n
; i
++) {
4012 if ((PyObject
*)(su
->type
) == PyTuple_GET_ITEM(mro
, i
))
4015 if (i
>= n
&& PyType_Check(su
->obj
)) {
4016 starttype
= (PyTypeObject
*)(su
->obj
);
4017 mro
= starttype
->tp_mro
;
4021 assert(PyTuple_Check(mro
));
4022 n
= PyTuple_GET_SIZE(mro
);
4024 for (i
= 0; i
< n
; i
++) {
4025 if ((PyObject
*)(su
->type
) ==
4026 PyTuple_GET_ITEM(mro
, i
))
4032 for (; i
< n
; i
++) {
4033 tmp
= PyTuple_GET_ITEM(mro
, i
);
4034 if (PyType_Check(tmp
))
4035 dict
= ((PyTypeObject
*)tmp
)->tp_dict
;
4036 else if (PyClass_Check(tmp
))
4037 dict
= ((PyClassObject
*)tmp
)->cl_dict
;
4040 res
= PyDict_GetItem(dict
, name
);
4041 if (res
!= NULL
&& !PyDescr_IsData(res
)) {
4043 f
= res
->ob_type
->tp_descr_get
;
4045 tmp
= f(res
, su
->obj
, (PyObject
*)starttype
);
4053 return PyObject_GenericGetAttr(self
, name
);
4057 supercheck(PyTypeObject
*type
, PyObject
*obj
)
4059 if (!PyType_IsSubtype(obj
->ob_type
, type
) &&
4060 !(PyType_Check(obj
) &&
4061 PyType_IsSubtype((PyTypeObject
*)obj
, type
))) {
4062 PyErr_SetString(PyExc_TypeError
,
4063 "super(type, obj): "
4064 "obj must be an instance or subtype of type");
4072 super_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
4074 superobject
*su
= (superobject
*)self
;
4077 if (obj
== NULL
|| obj
== Py_None
|| su
->obj
!= NULL
) {
4078 /* Not binding to an object, or already bound */
4082 if (su
->ob_type
!= &PySuper_Type
)
4083 /* If su is an instance of a subclass of super,
4085 return PyObject_CallFunction((PyObject
*)su
->ob_type
,
4086 "OO", su
->type
, obj
);
4088 /* Inline the common case */
4089 if (supercheck(su
->type
, obj
) < 0)
4091 new = (superobject
*)PySuper_Type
.tp_new(&PySuper_Type
,
4095 Py_INCREF(su
->type
);
4097 new->type
= su
->type
;
4099 return (PyObject
*)new;
4104 super_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
4106 superobject
*su
= (superobject
*)self
;
4108 PyObject
*obj
= NULL
;
4110 if (!PyArg_ParseTuple(args
, "O!|O:super", &PyType_Type
, &type
, &obj
))
4114 if (obj
!= NULL
&& supercheck(type
, obj
) < 0)
4123 static char super_doc
[] =
4124 "super(type) -> unbound super object\n"
4125 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
4126 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
4127 "Typical use to call a cooperative superclass method:\n"
4129 " def meth(self, arg):\n"
4130 " super(C, self).meth(arg)";
4133 super_traverse(PyObject
*self
, visitproc visit
, void *arg
)
4135 superobject
*su
= (superobject
*)self
;
4138 #define VISIT(SLOT) \
4140 err = visit((PyObject *)(SLOT), arg); \
4153 PyTypeObject PySuper_Type
= {
4154 PyObject_HEAD_INIT(&PyType_Type
)
4156 "super", /* tp_name */
4157 sizeof(superobject
), /* tp_basicsize */
4158 0, /* tp_itemsize */
4160 super_dealloc
, /* tp_dealloc */
4165 super_repr
, /* tp_repr */
4166 0, /* tp_as_number */
4167 0, /* tp_as_sequence */
4168 0, /* tp_as_mapping */
4172 super_getattro
, /* tp_getattro */
4173 0, /* tp_setattro */
4174 0, /* tp_as_buffer */
4175 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
4176 Py_TPFLAGS_BASETYPE
, /* tp_flags */
4177 super_doc
, /* tp_doc */
4178 super_traverse
, /* tp_traverse */
4180 0, /* tp_richcompare */
4181 0, /* tp_weaklistoffset */
4183 0, /* tp_iternext */
4185 super_members
, /* tp_members */
4189 super_descr_get
, /* tp_descr_get */
4190 0, /* tp_descr_set */
4191 0, /* tp_dictoffset */
4192 super_init
, /* tp_init */
4193 PyType_GenericAlloc
, /* tp_alloc */
4194 PyType_GenericNew
, /* tp_new */
4195 _PyObject_GC_Del
, /* tp_free */