1 /* Type object implementation */
4 #include "structmember.h"
8 static PyMemberDef type_members
[] = {
9 {"__basicsize__", T_INT
, offsetof(PyTypeObject
,tp_basicsize
),READONLY
},
10 {"__itemsize__", T_INT
, offsetof(PyTypeObject
, tp_itemsize
), READONLY
},
11 {"__flags__", T_LONG
, offsetof(PyTypeObject
, tp_flags
), READONLY
},
12 {"__weakrefoffset__", T_LONG
,
13 offsetof(PyTypeObject
, tp_weaklistoffset
), READONLY
},
14 {"__base__", T_OBJECT
, offsetof(PyTypeObject
, tp_base
), READONLY
},
15 {"__dictoffset__", T_LONG
,
16 offsetof(PyTypeObject
, tp_dictoffset
), READONLY
},
17 {"__mro__", T_OBJECT
, offsetof(PyTypeObject
, tp_mro
), READONLY
},
22 type_name(PyTypeObject
*type
, void *context
)
26 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
27 PyHeapTypeObject
* et
= (PyHeapTypeObject
*)type
;
33 s
= strrchr(type
->tp_name
, '.');
38 return PyString_FromString(s
);
43 type_set_name(PyTypeObject
*type
, PyObject
*value
, void *context
)
47 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
48 PyErr_Format(PyExc_TypeError
,
49 "can't set %s.__name__", type
->tp_name
);
53 PyErr_Format(PyExc_TypeError
,
54 "can't delete %s.__name__", type
->tp_name
);
57 if (!PyString_Check(value
)) {
58 PyErr_Format(PyExc_TypeError
,
59 "can only assign string to %s.__name__, not '%s'",
60 type
->tp_name
, value
->ob_type
->tp_name
);
63 if (strlen(PyString_AS_STRING(value
))
64 != (size_t)PyString_GET_SIZE(value
)) {
65 PyErr_Format(PyExc_ValueError
,
66 "__name__ must not contain null bytes");
70 et
= (PyHeapTypeObject
*)type
;
77 type
->tp_name
= PyString_AS_STRING(value
);
83 type_module(PyTypeObject
*type
, void *context
)
88 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
89 mod
= PyDict_GetItemString(type
->tp_dict
, "__module__");
94 s
= strrchr(type
->tp_name
, '.');
96 return PyString_FromStringAndSize(
97 type
->tp_name
, (int)(s
- type
->tp_name
));
98 return PyString_FromString("__builtin__");
103 type_set_module(PyTypeObject
*type
, PyObject
*value
, void *context
)
105 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
106 PyErr_Format(PyExc_TypeError
,
107 "can't set %s.__module__", type
->tp_name
);
111 PyErr_Format(PyExc_TypeError
,
112 "can't delete %s.__module__", type
->tp_name
);
116 return PyDict_SetItemString(type
->tp_dict
, "__module__", value
);
120 type_get_bases(PyTypeObject
*type
, void *context
)
122 Py_INCREF(type
->tp_bases
);
123 return type
->tp_bases
;
126 static PyTypeObject
*best_base(PyObject
*);
127 static int mro_internal(PyTypeObject
*);
128 static int compatible_for_assignment(PyTypeObject
*, PyTypeObject
*, char *);
129 static int add_subclass(PyTypeObject
*, PyTypeObject
*);
130 static void remove_subclass(PyTypeObject
*, PyTypeObject
*);
131 static void update_all_slots(PyTypeObject
*);
133 typedef int (*update_callback
)(PyTypeObject
*, void *);
134 static int update_subclasses(PyTypeObject
*type
, PyObject
*name
,
135 update_callback callback
, void *data
);
136 static int recurse_down_subclasses(PyTypeObject
*type
, PyObject
*name
,
137 update_callback callback
, void *data
);
140 mro_subclasses(PyTypeObject
*type
, PyObject
* temp
)
142 PyTypeObject
*subclass
;
143 PyObject
*ref
, *subclasses
, *old_mro
;
146 subclasses
= type
->tp_subclasses
;
147 if (subclasses
== NULL
)
149 assert(PyList_Check(subclasses
));
150 n
= PyList_GET_SIZE(subclasses
);
151 for (i
= 0; i
< n
; i
++) {
152 ref
= PyList_GET_ITEM(subclasses
, i
);
153 assert(PyWeakref_CheckRef(ref
));
154 subclass
= (PyTypeObject
*)PyWeakref_GET_OBJECT(ref
);
155 assert(subclass
!= NULL
);
156 if ((PyObject
*)subclass
== Py_None
)
158 assert(PyType_Check(subclass
));
159 old_mro
= subclass
->tp_mro
;
160 if (mro_internal(subclass
) < 0) {
161 subclass
->tp_mro
= old_mro
;
166 tuple
= Py_BuildValue("OO", subclass
, old_mro
);
170 if (PyList_Append(temp
, tuple
) < 0)
174 if (mro_subclasses(subclass
, temp
) < 0)
181 type_set_bases(PyTypeObject
*type
, PyObject
*value
, void *context
)
185 PyTypeObject
*new_base
, *old_base
;
186 PyObject
*old_bases
, *old_mro
;
188 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
189 PyErr_Format(PyExc_TypeError
,
190 "can't set %s.__bases__", type
->tp_name
);
194 PyErr_Format(PyExc_TypeError
,
195 "can't delete %s.__bases__", type
->tp_name
);
198 if (!PyTuple_Check(value
)) {
199 PyErr_Format(PyExc_TypeError
,
200 "can only assign tuple to %s.__bases__, not %s",
201 type
->tp_name
, value
->ob_type
->tp_name
);
204 if (PyTuple_GET_SIZE(value
) == 0) {
205 PyErr_Format(PyExc_TypeError
,
206 "can only assign non-empty tuple to %s.__bases__, not ()",
210 for (i
= 0; i
< PyTuple_GET_SIZE(value
); i
++) {
211 ob
= PyTuple_GET_ITEM(value
, i
);
212 if (!PyClass_Check(ob
) && !PyType_Check(ob
)) {
215 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
216 type
->tp_name
, ob
->ob_type
->tp_name
);
219 if (PyType_Check(ob
)) {
220 if (PyType_IsSubtype((PyTypeObject
*)ob
, type
)) {
221 PyErr_SetString(PyExc_TypeError
,
222 "a __bases__ item causes an inheritance cycle");
228 new_base
= best_base(value
);
234 if (!compatible_for_assignment(type
->tp_base
, new_base
, "__bases__"))
240 old_bases
= type
->tp_bases
;
241 old_base
= type
->tp_base
;
242 old_mro
= type
->tp_mro
;
244 type
->tp_bases
= value
;
245 type
->tp_base
= new_base
;
247 if (mro_internal(type
) < 0) {
251 temp
= PyList_New(0);
255 r
= mro_subclasses(type
, temp
);
258 for (i
= 0; i
< PyList_Size(temp
); i
++) {
261 PyArg_ParseTuple(PyList_GET_ITEM(temp
, i
),
263 Py_DECREF(cls
->tp_mro
);
265 Py_INCREF(cls
->tp_mro
);
273 /* any base that was in __bases__ but now isn't, we
274 need to remove |type| from its tp_subclasses.
275 conversely, any class now in __bases__ that wasn't
276 needs to have |type| added to its subclasses. */
278 /* for now, sod that: just remove from all old_bases,
279 add to all new_bases */
281 for (i
= PyTuple_GET_SIZE(old_bases
) - 1; i
>= 0; i
--) {
282 ob
= PyTuple_GET_ITEM(old_bases
, i
);
283 if (PyType_Check(ob
)) {
285 (PyTypeObject
*)ob
, type
);
289 for (i
= PyTuple_GET_SIZE(value
) - 1; i
>= 0; i
--) {
290 ob
= PyTuple_GET_ITEM(value
, i
);
291 if (PyType_Check(ob
)) {
292 if (add_subclass((PyTypeObject
*)ob
, type
) < 0)
297 update_all_slots(type
);
299 Py_DECREF(old_bases
);
306 type
->tp_bases
= old_bases
;
307 type
->tp_base
= old_base
;
308 type
->tp_mro
= old_mro
;
317 type_dict(PyTypeObject
*type
, void *context
)
319 if (type
->tp_dict
== NULL
) {
323 return PyDictProxy_New(type
->tp_dict
);
327 type_get_doc(PyTypeObject
*type
, void *context
)
330 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) && type
->tp_doc
!= NULL
)
331 return PyString_FromString(type
->tp_doc
);
332 result
= PyDict_GetItemString(type
->tp_dict
, "__doc__");
333 if (result
== NULL
) {
337 else if (result
->ob_type
->tp_descr_get
) {
338 result
= result
->ob_type
->tp_descr_get(result
, NULL
,
347 static PyGetSetDef type_getsets
[] = {
348 {"__name__", (getter
)type_name
, (setter
)type_set_name
, NULL
},
349 {"__bases__", (getter
)type_get_bases
, (setter
)type_set_bases
, NULL
},
350 {"__module__", (getter
)type_module
, (setter
)type_set_module
, NULL
},
351 {"__dict__", (getter
)type_dict
, NULL
, NULL
},
352 {"__doc__", (getter
)type_get_doc
, NULL
, NULL
},
357 type_compare(PyObject
*v
, PyObject
*w
)
359 /* This is called with type objects only. So we
360 can just compare the addresses. */
361 Py_uintptr_t vv
= (Py_uintptr_t
)v
;
362 Py_uintptr_t ww
= (Py_uintptr_t
)w
;
363 return (vv
< ww
) ? -1 : (vv
> ww
) ? 1 : 0;
367 type_repr(PyTypeObject
*type
)
369 PyObject
*mod
, *name
, *rtn
;
372 mod
= type_module(type
, NULL
);
375 else if (!PyString_Check(mod
)) {
379 name
= type_name(type
, NULL
);
383 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
388 if (mod
!= NULL
&& strcmp(PyString_AS_STRING(mod
), "__builtin__")) {
389 rtn
= PyString_FromFormat("<%s '%s.%s'>",
391 PyString_AS_STRING(mod
),
392 PyString_AS_STRING(name
));
395 rtn
= PyString_FromFormat("<%s '%s'>", kind
, type
->tp_name
);
403 type_call(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
407 if (type
->tp_new
== NULL
) {
408 PyErr_Format(PyExc_TypeError
,
409 "cannot create '%.100s' instances",
414 obj
= type
->tp_new(type
, args
, kwds
);
416 /* Ugly exception: when the call was type(something),
417 don't call tp_init on the result. */
418 if (type
== &PyType_Type
&&
419 PyTuple_Check(args
) && PyTuple_GET_SIZE(args
) == 1 &&
421 (PyDict_Check(kwds
) && PyDict_Size(kwds
) == 0)))
423 /* If the returned object is not an instance of type,
424 it won't be initialized. */
425 if (!PyType_IsSubtype(obj
->ob_type
, type
))
428 if (PyType_HasFeature(type
, Py_TPFLAGS_HAVE_CLASS
) &&
429 type
->tp_init
!= NULL
&&
430 type
->tp_init(obj
, args
, kwds
) < 0) {
439 PyType_GenericAlloc(PyTypeObject
*type
, int nitems
)
442 const size_t size
= _PyObject_VAR_SIZE(type
, nitems
+1);
443 /* note that we need to add one, for the sentinel */
445 if (PyType_IS_GC(type
))
446 obj
= _PyObject_GC_Malloc(size
);
448 obj
= PyObject_MALLOC(size
);
451 return PyErr_NoMemory();
453 memset(obj
, '\0', size
);
455 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
458 if (type
->tp_itemsize
== 0)
459 PyObject_INIT(obj
, type
);
461 (void) PyObject_INIT_VAR((PyVarObject
*)obj
, type
, nitems
);
463 if (PyType_IS_GC(type
))
464 _PyObject_GC_TRACK(obj
);
469 PyType_GenericNew(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
471 return type
->tp_alloc(type
, 0);
474 /* Helpers for subtyping */
477 traverse_slots(PyTypeObject
*type
, PyObject
*self
, visitproc visit
, void *arg
)
483 mp
= PyHeapType_GET_MEMBERS((PyHeapTypeObject
*)type
);
484 for (i
= 0; i
< n
; i
++, mp
++) {
485 if (mp
->type
== T_OBJECT_EX
) {
486 char *addr
= (char *)self
+ mp
->offset
;
487 PyObject
*obj
= *(PyObject
**)addr
;
489 int err
= visit(obj
, arg
);
499 subtype_traverse(PyObject
*self
, visitproc visit
, void *arg
)
501 PyTypeObject
*type
, *base
;
502 traverseproc basetraverse
;
504 /* Find the nearest base with a different tp_traverse,
505 and traverse slots while we're at it */
506 type
= self
->ob_type
;
508 while ((basetraverse
= base
->tp_traverse
) == subtype_traverse
) {
510 int err
= traverse_slots(base
, self
, visit
, arg
);
514 base
= base
->tp_base
;
518 if (type
->tp_dictoffset
!= base
->tp_dictoffset
) {
519 PyObject
**dictptr
= _PyObject_GetDictPtr(self
);
520 if (dictptr
&& *dictptr
) {
521 int err
= visit(*dictptr
, arg
);
527 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
528 /* For a heaptype, the instances count as references
529 to the type. Traverse the type so the collector
530 can find cycles involving this link. */
531 int err
= visit((PyObject
*)type
, arg
);
537 return basetraverse(self
, visit
, arg
);
542 clear_slots(PyTypeObject
*type
, PyObject
*self
)
548 mp
= PyHeapType_GET_MEMBERS((PyHeapTypeObject
*)type
);
549 for (i
= 0; i
< n
; i
++, mp
++) {
550 if (mp
->type
== T_OBJECT_EX
&& !(mp
->flags
& READONLY
)) {
551 char *addr
= (char *)self
+ mp
->offset
;
552 PyObject
*obj
= *(PyObject
**)addr
;
555 *(PyObject
**)addr
= NULL
;
562 subtype_clear(PyObject
*self
)
564 PyTypeObject
*type
, *base
;
567 /* Find the nearest base with a different tp_clear
568 and clear slots while we're at it */
569 type
= self
->ob_type
;
571 while ((baseclear
= base
->tp_clear
) == subtype_clear
) {
573 clear_slots(base
, self
);
574 base
= base
->tp_base
;
578 /* There's no need to clear the instance dict (if any);
579 the collector will call its tp_clear handler. */
582 return baseclear(self
);
587 subtype_dealloc(PyObject
*self
)
589 PyTypeObject
*type
, *base
;
590 destructor basedealloc
;
592 /* Extract the type; we expect it to be a heap type */
593 type
= self
->ob_type
;
594 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
596 /* Test whether the type has GC exactly once */
598 if (!PyType_IS_GC(type
)) {
599 /* It's really rare to find a dynamic type that doesn't have
600 GC; it can only happen when deriving from 'object' and not
601 adding any slots or instance variables. This allows
602 certain simplifications: there's no need to call
603 clear_slots(), or DECREF the dict, or clear weakrefs. */
605 /* Maybe call finalizer; exit early if resurrected */
608 if (self
->ob_refcnt
> 0)
612 /* Find the nearest base with a different tp_dealloc */
614 while ((basedealloc
= base
->tp_dealloc
) == subtype_dealloc
) {
615 assert(base
->ob_size
== 0);
616 base
= base
->tp_base
;
620 /* Call the base tp_dealloc() */
624 /* Can't reference self beyond this point */
631 /* We get here only if the type has GC */
633 /* UnTrack and re-Track around the trashcan macro, alas */
634 /* See explanation at end of function for full disclosure */
635 PyObject_GC_UnTrack(self
);
636 ++_PyTrash_delete_nesting
;
637 Py_TRASHCAN_SAFE_BEGIN(self
);
638 --_PyTrash_delete_nesting
;
639 _PyObject_GC_TRACK(self
); /* We'll untrack for real later */
641 /* Maybe call finalizer; exit early if resurrected */
644 if (self
->ob_refcnt
> 0)
648 /* Find the nearest base with a different tp_dealloc
649 and clear slots while we're at it */
651 while ((basedealloc
= base
->tp_dealloc
) == subtype_dealloc
) {
653 clear_slots(base
, self
);
654 base
= base
->tp_base
;
658 /* If we added a dict, DECREF it */
659 if (type
->tp_dictoffset
&& !base
->tp_dictoffset
) {
660 PyObject
**dictptr
= _PyObject_GetDictPtr(self
);
661 if (dictptr
!= NULL
) {
662 PyObject
*dict
= *dictptr
;
670 /* If we added weaklist, we clear it */
671 if (type
->tp_weaklistoffset
&& !base
->tp_weaklistoffset
)
672 PyObject_ClearWeakRefs(self
);
674 /* Finalize GC if the base doesn't do GC and we do */
675 if (!PyType_IS_GC(base
))
676 _PyObject_GC_UNTRACK(self
);
678 /* Call the base tp_dealloc() */
682 /* Can't reference self beyond this point */
686 ++_PyTrash_delete_nesting
;
687 Py_TRASHCAN_SAFE_END(self
);
688 --_PyTrash_delete_nesting
;
690 /* Explanation of the weirdness around the trashcan macros:
692 Q. What do the trashcan macros do?
694 A. Read the comment titled "Trashcan mechanism" in object.h.
695 For one, this explains why there must be a call to GC-untrack
696 before the trashcan begin macro. Without understanding the
697 trashcan code, the answers to the following questions don't make
700 Q. Why do we GC-untrack before the trashcan and then immediately
701 GC-track again afterward?
703 A. In the case that the base class is GC-aware, the base class
704 probably GC-untracks the object. If it does that using the
705 UNTRACK macro, this will crash when the object is already
706 untracked. Because we don't know what the base class does, the
707 only safe thing is to make sure the object is tracked when we
708 call the base class dealloc. But... The trashcan begin macro
709 requires that the object is *untracked* before it is called. So
716 Q. Why the bizarre (net-zero) manipulation of
717 _PyTrash_delete_nesting around the trashcan macros?
719 A. Some base classes (e.g. list) also use the trashcan mechanism.
720 The following scenario used to be possible:
722 - suppose the trashcan level is one below the trashcan limit
724 - subtype_dealloc() is called
726 - the trashcan limit is not yet reached, so the trashcan level
727 is incremented and the code between trashcan begin and end is
730 - this destroys much of the object's contents, including its
733 - basedealloc() is called; this is really list_dealloc(), or
734 some other type which also uses the trashcan macros
736 - the trashcan limit is now reached, so the object is put on the
737 trashcan's to-be-deleted-later list
739 - basedealloc() returns
741 - subtype_dealloc() decrefs the object's type
743 - subtype_dealloc() returns
745 - later, the trashcan code starts deleting the objects from its
746 to-be-deleted-later list
748 - subtype_dealloc() is called *AGAIN* for the same object
750 - at the very least (if the destroyed slots and __dict__ don't
751 cause problems) the object's type gets decref'ed a second
752 time, which is *BAD*!!!
754 The remedy is to make sure that if the code between trashcan
755 begin and end in subtype_dealloc() is called, the code between
756 trashcan begin and end in basedealloc() will also be called.
757 This is done by decrementing the level after passing into the
758 trashcan block, and incrementing it just before leaving the
761 But now it's possible that a chain of objects consisting solely
762 of objects whose deallocator is subtype_dealloc() will defeat
763 the trashcan mechanism completely: the decremented level means
764 that the effective level never reaches the limit. Therefore, we
765 *increment* the level *before* entering the trashcan block, and
766 matchingly decrement it after leaving. This means the trashcan
767 code will trigger a little early, but that's no big deal.
769 Q. Are there any live examples of code in need of all this
772 A. Yes. See SF bug 668433 for code that crashed (when Python was
773 compiled in debug mode) before the trashcan level manipulations
774 were added. For more discussion, see SF patches 581742, 575073
779 static PyTypeObject
*solid_base(PyTypeObject
*type
);
781 /* type test with subclassing support */
784 PyType_IsSubtype(PyTypeObject
*a
, PyTypeObject
*b
)
788 if (!(a
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
))
789 return b
== a
|| b
== &PyBaseObject_Type
;
793 /* Deal with multiple inheritance without recursion
794 by walking the MRO tuple */
796 assert(PyTuple_Check(mro
));
797 n
= PyTuple_GET_SIZE(mro
);
798 for (i
= 0; i
< n
; i
++) {
799 if (PyTuple_GET_ITEM(mro
, i
) == (PyObject
*)b
)
805 /* a is not completely initilized yet; follow tp_base */
811 return b
== &PyBaseObject_Type
;
815 /* Internal routines to do a method lookup in the type
816 without looking in the instance dictionary
817 (so we can't use PyObject_GetAttr) but still binding
818 it to the instance. The arguments are the object,
819 the method name as a C string, and the address of a
820 static variable used to cache the interned Python string.
824 - lookup_maybe() returns NULL without raising an exception
825 when the _PyType_Lookup() call fails;
827 - lookup_method() always raises an exception upon errors.
831 lookup_maybe(PyObject
*self
, char *attrstr
, PyObject
**attrobj
)
835 if (*attrobj
== NULL
) {
836 *attrobj
= PyString_InternFromString(attrstr
);
837 if (*attrobj
== NULL
)
840 res
= _PyType_Lookup(self
->ob_type
, *attrobj
);
843 if ((f
= res
->ob_type
->tp_descr_get
) == NULL
)
846 res
= f(res
, self
, (PyObject
*)(self
->ob_type
));
852 lookup_method(PyObject
*self
, char *attrstr
, PyObject
**attrobj
)
854 PyObject
*res
= lookup_maybe(self
, attrstr
, attrobj
);
855 if (res
== NULL
&& !PyErr_Occurred())
856 PyErr_SetObject(PyExc_AttributeError
, *attrobj
);
860 /* A variation of PyObject_CallMethod that uses lookup_method()
861 instead of PyObject_GetAttrString(). This uses the same convention
862 as lookup_method to cache the interned name string object. */
865 call_method(PyObject
*o
, char *name
, PyObject
**nameobj
, char *format
, ...)
868 PyObject
*args
, *func
= 0, *retval
;
869 va_start(va
, format
);
871 func
= lookup_maybe(o
, name
, nameobj
);
874 if (!PyErr_Occurred())
875 PyErr_SetObject(PyExc_AttributeError
, *nameobj
);
879 if (format
&& *format
)
880 args
= Py_VaBuildValue(format
, va
);
882 args
= PyTuple_New(0);
889 assert(PyTuple_Check(args
));
890 retval
= PyObject_Call(func
, args
, NULL
);
898 /* Clone of call_method() that returns NotImplemented when the lookup fails. */
901 call_maybe(PyObject
*o
, char *name
, PyObject
**nameobj
, char *format
, ...)
904 PyObject
*args
, *func
= 0, *retval
;
905 va_start(va
, format
);
907 func
= lookup_maybe(o
, name
, nameobj
);
910 if (!PyErr_Occurred()) {
911 Py_INCREF(Py_NotImplemented
);
912 return Py_NotImplemented
;
917 if (format
&& *format
)
918 args
= Py_VaBuildValue(format
, va
);
920 args
= PyTuple_New(0);
927 assert(PyTuple_Check(args
));
928 retval
= PyObject_Call(func
, args
, NULL
);
937 fill_classic_mro(PyObject
*mro
, PyObject
*cls
)
939 PyObject
*bases
, *base
;
942 assert(PyList_Check(mro
));
943 assert(PyClass_Check(cls
));
944 i
= PySequence_Contains(mro
, cls
);
948 if (PyList_Append(mro
, cls
) < 0)
951 bases
= ((PyClassObject
*)cls
)->cl_bases
;
952 assert(bases
&& PyTuple_Check(bases
));
953 n
= PyTuple_GET_SIZE(bases
);
954 for (i
= 0; i
< n
; i
++) {
955 base
= PyTuple_GET_ITEM(bases
, i
);
956 if (fill_classic_mro(mro
, base
) < 0)
963 classic_mro(PyObject
*cls
)
967 assert(PyClass_Check(cls
));
970 if (fill_classic_mro(mro
, cls
) == 0)
978 Method resolution order algorithm C3 described in
979 "A Monotonic Superclass Linearization for Dylan",
980 by Kim Barrett, Bob Cassel, Paul Haahr,
981 David A. Moon, Keith Playford, and P. Tucker Withington.
984 Some notes about the rules implied by C3:
987 It isn't legal to repeat a class in a list of base classes.
989 The next three properties are the 3 constraints in "C3".
991 Local precendece order.
992 If A precedes B in C's MRO, then A will precede B in the MRO of all
996 The MRO of a class must be an extension without reordering of the
997 MRO of each of its superclasses.
999 Extended Precedence Graph (EPG).
1000 Linearization is consistent if there is a path in the EPG from
1001 each class to all its successors in the linearization. See
1002 the paper for definition of EPG.
1006 tail_contains(PyObject
*list
, int whence
, PyObject
*o
) {
1008 size
= PyList_GET_SIZE(list
);
1010 for (j
= whence
+1; j
< size
; j
++) {
1011 if (PyList_GET_ITEM(list
, j
) == o
)
1018 class_name(PyObject
*cls
)
1020 PyObject
*name
= PyObject_GetAttrString(cls
, "__name__");
1024 name
= PyObject_Repr(cls
);
1028 if (!PyString_Check(name
)) {
1036 check_duplicates(PyObject
*list
)
1039 /* Let's use a quadratic time algorithm,
1040 assuming that the bases lists is short.
1042 n
= PyList_GET_SIZE(list
);
1043 for (i
= 0; i
< n
; i
++) {
1044 PyObject
*o
= PyList_GET_ITEM(list
, i
);
1045 for (j
= i
+ 1; j
< n
; j
++) {
1046 if (PyList_GET_ITEM(list
, j
) == o
) {
1048 PyErr_Format(PyExc_TypeError
,
1049 "duplicate base class %s",
1050 o
? PyString_AS_STRING(o
) : "?");
1059 /* Raise a TypeError for an MRO order disagreement.
1061 It's hard to produce a good error message. In the absence of better
1062 insight into error reporting, report the classes that were candidates
1063 to be put next into the MRO. There is some conflict between the
1064 order in which they should be put in the MRO, but it's hard to
1065 diagnose what constraint can't be satisfied.
1069 set_mro_error(PyObject
*to_merge
, int *remain
)
1071 int i
, n
, off
, to_merge_size
;
1074 PyObject
*set
= PyDict_New();
1076 to_merge_size
= PyList_GET_SIZE(to_merge
);
1077 for (i
= 0; i
< to_merge_size
; i
++) {
1078 PyObject
*L
= PyList_GET_ITEM(to_merge
, i
);
1079 if (remain
[i
] < PyList_GET_SIZE(L
)) {
1080 PyObject
*c
= PyList_GET_ITEM(L
, remain
[i
]);
1081 if (PyDict_SetItem(set
, c
, Py_None
) < 0)
1085 n
= PyDict_Size(set
);
1087 off
= PyOS_snprintf(buf
, sizeof(buf
), "Cannot create a \
1088 consistent method resolution\norder (MRO) for bases");
1090 while (PyDict_Next(set
, &i
, &k
, &v
) && off
< sizeof(buf
)) {
1091 PyObject
*name
= class_name(k
);
1092 off
+= PyOS_snprintf(buf
+ off
, sizeof(buf
) - off
, " %s",
1093 name
? PyString_AS_STRING(name
) : "?");
1095 if (--n
&& off
+1 < sizeof(buf
)) {
1100 PyErr_SetString(PyExc_TypeError
, buf
);
1105 pmerge(PyObject
*acc
, PyObject
* to_merge
) {
1106 int i
, j
, to_merge_size
;
1110 to_merge_size
= PyList_GET_SIZE(to_merge
);
1112 /* remain stores an index into each sublist of to_merge.
1113 remain[i] is the index of the next base in to_merge[i]
1114 that is not included in acc.
1116 remain
= PyMem_MALLOC(SIZEOF_INT
*to_merge_size
);
1119 for (i
= 0; i
< to_merge_size
; i
++)
1124 for (i
= 0; i
< to_merge_size
; i
++) {
1125 PyObject
*candidate
;
1127 PyObject
*cur_list
= PyList_GET_ITEM(to_merge
, i
);
1129 if (remain
[i
] >= PyList_GET_SIZE(cur_list
)) {
1134 /* Choose next candidate for MRO.
1136 The input sequences alone can determine the choice.
1137 If not, choose the class which appears in the MRO
1138 of the earliest direct superclass of the new class.
1141 candidate
= PyList_GET_ITEM(cur_list
, remain
[i
]);
1142 for (j
= 0; j
< to_merge_size
; j
++) {
1143 PyObject
*j_lst
= PyList_GET_ITEM(to_merge
, j
);
1144 if (tail_contains(j_lst
, remain
[j
], candidate
)) {
1145 goto skip
; /* continue outer loop */
1148 ok
= PyList_Append(acc
, candidate
);
1153 for (j
= 0; j
< to_merge_size
; j
++) {
1154 PyObject
*j_lst
= PyList_GET_ITEM(to_merge
, j
);
1155 if (remain
[j
] < PyList_GET_SIZE(j_lst
) &&
1156 PyList_GET_ITEM(j_lst
, remain
[j
]) == candidate
) {
1164 if (empty_cnt
== to_merge_size
) {
1168 set_mro_error(to_merge
, remain
);
1174 mro_implementation(PyTypeObject
*type
)
1177 PyObject
*bases
, *result
;
1178 PyObject
*to_merge
, *bases_aslist
;
1180 if(type
->tp_dict
== NULL
) {
1181 if(PyType_Ready(type
) < 0)
1185 /* Find a superclass linearization that honors the constraints
1186 of the explicit lists of bases and the constraints implied by
1189 to_merge is a list of lists, where each list is a superclass
1190 linearization implied by a base class. The last element of
1191 to_merge is the declared list of bases.
1194 bases
= type
->tp_bases
;
1195 n
= PyTuple_GET_SIZE(bases
);
1197 to_merge
= PyList_New(n
+1);
1198 if (to_merge
== NULL
)
1201 for (i
= 0; i
< n
; i
++) {
1202 PyObject
*base
= PyTuple_GET_ITEM(bases
, i
);
1203 PyObject
*parentMRO
;
1204 if (PyType_Check(base
))
1205 parentMRO
= PySequence_List(
1206 ((PyTypeObject
*)base
)->tp_mro
);
1208 parentMRO
= classic_mro(base
);
1209 if (parentMRO
== NULL
) {
1210 Py_DECREF(to_merge
);
1214 PyList_SET_ITEM(to_merge
, i
, parentMRO
);
1217 bases_aslist
= PySequence_List(bases
);
1218 if (bases_aslist
== NULL
) {
1219 Py_DECREF(to_merge
);
1222 /* This is just a basic sanity check. */
1223 if (check_duplicates(bases_aslist
) < 0) {
1224 Py_DECREF(to_merge
);
1225 Py_DECREF(bases_aslist
);
1228 PyList_SET_ITEM(to_merge
, n
, bases_aslist
);
1230 result
= Py_BuildValue("[O]", (PyObject
*)type
);
1231 if (result
== NULL
) {
1232 Py_DECREF(to_merge
);
1236 ok
= pmerge(result
, to_merge
);
1237 Py_DECREF(to_merge
);
1247 mro_external(PyObject
*self
)
1249 PyTypeObject
*type
= (PyTypeObject
*)self
;
1251 return mro_implementation(type
);
1255 mro_internal(PyTypeObject
*type
)
1257 PyObject
*mro
, *result
, *tuple
;
1259 if (type
->ob_type
== &PyType_Type
) {
1260 result
= mro_implementation(type
);
1263 static PyObject
*mro_str
;
1264 mro
= lookup_method((PyObject
*)type
, "mro", &mro_str
);
1267 result
= PyObject_CallObject(mro
, NULL
);
1272 tuple
= PySequence_Tuple(result
);
1274 type
->tp_mro
= tuple
;
1279 /* Calculate the best base amongst multiple base classes.
1280 This is the first one that's on the path to the "solid base". */
1282 static PyTypeObject
*
1283 best_base(PyObject
*bases
)
1286 PyTypeObject
*base
, *winner
, *candidate
, *base_i
;
1287 PyObject
*base_proto
;
1289 assert(PyTuple_Check(bases
));
1290 n
= PyTuple_GET_SIZE(bases
);
1294 for (i
= 0; i
< n
; i
++) {
1295 base_proto
= PyTuple_GET_ITEM(bases
, i
);
1296 if (PyClass_Check(base_proto
))
1298 if (!PyType_Check(base_proto
)) {
1301 "bases must be types");
1304 base_i
= (PyTypeObject
*)base_proto
;
1305 if (base_i
->tp_dict
== NULL
) {
1306 if (PyType_Ready(base_i
) < 0)
1309 candidate
= solid_base(base_i
);
1310 if (winner
== NULL
) {
1314 else if (PyType_IsSubtype(winner
, candidate
))
1316 else if (PyType_IsSubtype(candidate
, winner
)) {
1323 "multiple bases have "
1324 "instance lay-out conflict");
1329 PyErr_SetString(PyExc_TypeError
,
1330 "a new-style class can't have only classic bases");
1335 extra_ivars(PyTypeObject
*type
, PyTypeObject
*base
)
1337 size_t t_size
= type
->tp_basicsize
;
1338 size_t b_size
= base
->tp_basicsize
;
1340 assert(t_size
>= b_size
); /* Else type smaller than base! */
1341 if (type
->tp_itemsize
|| base
->tp_itemsize
) {
1342 /* If itemsize is involved, stricter rules */
1343 return t_size
!= b_size
||
1344 type
->tp_itemsize
!= base
->tp_itemsize
;
1346 if (type
->tp_weaklistoffset
&& base
->tp_weaklistoffset
== 0 &&
1347 type
->tp_weaklistoffset
+ sizeof(PyObject
*) == t_size
)
1348 t_size
-= sizeof(PyObject
*);
1349 if (type
->tp_dictoffset
&& base
->tp_dictoffset
== 0 &&
1350 type
->tp_dictoffset
+ sizeof(PyObject
*) == t_size
)
1351 t_size
-= sizeof(PyObject
*);
1353 return t_size
!= b_size
;
1356 static PyTypeObject
*
1357 solid_base(PyTypeObject
*type
)
1362 base
= solid_base(type
->tp_base
);
1364 base
= &PyBaseObject_Type
;
1365 if (extra_ivars(type
, base
))
1371 static void object_dealloc(PyObject
*);
1372 static int object_init(PyObject
*, PyObject
*, PyObject
*);
1373 static int update_slot(PyTypeObject
*, PyObject
*);
1374 static void fixup_slot_dispatchers(PyTypeObject
*);
1377 subtype_dict(PyObject
*obj
, void *context
)
1379 PyObject
**dictptr
= _PyObject_GetDictPtr(obj
);
1382 if (dictptr
== NULL
) {
1383 PyErr_SetString(PyExc_AttributeError
,
1384 "This object has no __dict__");
1389 *dictptr
= dict
= PyDict_New();
1395 subtype_setdict(PyObject
*obj
, PyObject
*value
, void *context
)
1397 PyObject
**dictptr
= _PyObject_GetDictPtr(obj
);
1400 if (dictptr
== NULL
) {
1401 PyErr_SetString(PyExc_AttributeError
,
1402 "This object has no __dict__");
1405 if (value
!= NULL
&& !PyDict_Check(value
)) {
1406 PyErr_SetString(PyExc_TypeError
,
1407 "__dict__ must be set to a dictionary");
1418 subtype_getweakref(PyObject
*obj
, void *context
)
1420 PyObject
**weaklistptr
;
1423 if (obj
->ob_type
->tp_weaklistoffset
== 0) {
1424 PyErr_SetString(PyExc_AttributeError
,
1425 "This object has no __weaklist__");
1428 assert(obj
->ob_type
->tp_weaklistoffset
> 0);
1429 assert(obj
->ob_type
->tp_weaklistoffset
+ sizeof(PyObject
*) <=
1430 (size_t)(obj
->ob_type
->tp_basicsize
));
1431 weaklistptr
= (PyObject
**)
1432 ((char *)obj
+ obj
->ob_type
->tp_weaklistoffset
);
1433 if (*weaklistptr
== NULL
)
1436 result
= *weaklistptr
;
1441 /* Three variants on the subtype_getsets list. */
1443 static PyGetSetDef subtype_getsets_full
[] = {
1444 {"__dict__", subtype_dict
, subtype_setdict
,
1445 PyDoc_STR("dictionary for instance variables (if defined)")},
1446 {"__weakref__", subtype_getweakref
, NULL
,
1447 PyDoc_STR("list of weak references to the object (if defined)")},
1451 static PyGetSetDef subtype_getsets_dict_only
[] = {
1452 {"__dict__", subtype_dict
, subtype_setdict
,
1453 PyDoc_STR("dictionary for instance variables (if defined)")},
1457 static PyGetSetDef subtype_getsets_weakref_only
[] = {
1458 {"__weakref__", subtype_getweakref
, NULL
,
1459 PyDoc_STR("list of weak references to the object (if defined)")},
1464 valid_identifier(PyObject
*s
)
1469 if (!PyString_Check(s
)) {
1470 PyErr_SetString(PyExc_TypeError
,
1471 "__slots__ must be strings");
1474 p
= (unsigned char *) PyString_AS_STRING(s
);
1475 n
= PyString_GET_SIZE(s
);
1476 /* We must reject an empty name. As a hack, we bump the
1477 length to 1 so that the loop will balk on the trailing \0. */
1480 for (i
= 0; i
< n
; i
++, p
++) {
1481 if (!(i
== 0 ? isalpha(*p
) : isalnum(*p
)) && *p
!= '_') {
1482 PyErr_SetString(PyExc_TypeError
,
1483 "__slots__ must be identifiers");
1490 #ifdef Py_USING_UNICODE
1491 /* Replace Unicode objects in slots. */
1494 _unicode_to_string(PyObject
*slots
, int nslots
)
1496 PyObject
*tmp
= slots
;
1499 intintargfunc copy
= slots
->ob_type
->tp_as_sequence
->sq_slice
;
1500 for (i
= 0; i
< nslots
; i
++) {
1501 if (PyUnicode_Check(o
= PyTuple_GET_ITEM(tmp
, i
))) {
1503 tmp
= copy(slots
, 0, PyTuple_GET_SIZE(slots
));
1507 o1
= _PyUnicode_AsDefaultEncodedString
1515 PyTuple_SET_ITEM(tmp
, i
, o1
);
1523 type_new(PyTypeObject
*metatype
, PyObject
*args
, PyObject
*kwds
)
1525 PyObject
*name
, *bases
, *dict
;
1526 static char *kwlist
[] = {"name", "bases", "dict", 0};
1527 PyObject
*slots
, *tmp
, *newslots
;
1528 PyTypeObject
*type
, *base
, *tmptype
, *winner
;
1529 PyHeapTypeObject
*et
;
1531 int i
, nbases
, nslots
, slotoffset
, add_dict
, add_weak
;
1532 int j
, may_add_dict
, may_add_weak
;
1534 assert(args
!= NULL
&& PyTuple_Check(args
));
1535 assert(kwds
== NULL
|| PyDict_Check(kwds
));
1537 /* Special case: type(x) should return x->ob_type */
1539 const int nargs
= PyTuple_GET_SIZE(args
);
1540 const int nkwds
= kwds
== NULL
? 0 : PyDict_Size(kwds
);
1542 if (PyType_CheckExact(metatype
) && nargs
== 1 && nkwds
== 0) {
1543 PyObject
*x
= PyTuple_GET_ITEM(args
, 0);
1544 Py_INCREF(x
->ob_type
);
1545 return (PyObject
*) x
->ob_type
;
1548 /* SF bug 475327 -- if that didn't trigger, we need 3
1549 arguments. but PyArg_ParseTupleAndKeywords below may give
1550 a msg saying type() needs exactly 3. */
1551 if (nargs
+ nkwds
!= 3) {
1552 PyErr_SetString(PyExc_TypeError
,
1553 "type() takes 1 or 3 arguments");
1558 /* Check arguments: (name, bases, dict) */
1559 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "SO!O!:type", kwlist
,
1561 &PyTuple_Type
, &bases
,
1562 &PyDict_Type
, &dict
))
1565 /* Determine the proper metatype to deal with this,
1566 and check for metatype conflicts while we're at it.
1567 Note that if some other metatype wins to contract,
1568 it's possible that its instances are not types. */
1569 nbases
= PyTuple_GET_SIZE(bases
);
1571 for (i
= 0; i
< nbases
; i
++) {
1572 tmp
= PyTuple_GET_ITEM(bases
, i
);
1573 tmptype
= tmp
->ob_type
;
1574 if (tmptype
== &PyClass_Type
)
1575 continue; /* Special case classic classes */
1576 if (PyType_IsSubtype(winner
, tmptype
))
1578 if (PyType_IsSubtype(tmptype
, winner
)) {
1582 PyErr_SetString(PyExc_TypeError
,
1583 "metaclass conflict: "
1584 "the metaclass of a derived class "
1585 "must be a (non-strict) subclass "
1586 "of the metaclasses of all its bases");
1589 if (winner
!= metatype
) {
1590 if (winner
->tp_new
!= type_new
) /* Pass it to the winner */
1591 return winner
->tp_new(winner
, args
, kwds
);
1595 /* Adjust for empty tuple bases */
1597 bases
= Py_BuildValue("(O)", &PyBaseObject_Type
);
1605 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1607 /* Calculate best base, and check that all bases are type objects */
1608 base
= best_base(bases
);
1611 if (!PyType_HasFeature(base
, Py_TPFLAGS_BASETYPE
)) {
1612 PyErr_Format(PyExc_TypeError
,
1613 "type '%.100s' is not an acceptable base type",
1618 /* Check for a __slots__ sequence variable in dict, and count it */
1619 slots
= PyDict_GetItemString(dict
, "__slots__");
1623 may_add_dict
= base
->tp_dictoffset
== 0;
1624 may_add_weak
= base
->tp_weaklistoffset
== 0 && base
->tp_itemsize
== 0;
1625 if (slots
== NULL
) {
1636 /* Make it into a tuple */
1637 if (PyString_Check(slots
))
1638 slots
= Py_BuildValue("(O)", slots
);
1640 slots
= PySequence_Tuple(slots
);
1643 assert(PyTuple_Check(slots
));
1645 /* Are slots allowed? */
1646 nslots
= PyTuple_GET_SIZE(slots
);
1647 if (nslots
> 0 && base
->tp_itemsize
!= 0 && !PyType_Check(base
)) {
1648 /* for the special case of meta types, allow slots */
1649 PyErr_Format(PyExc_TypeError
,
1650 "nonempty __slots__ "
1651 "not supported for subtype of '%s'",
1658 #ifdef Py_USING_UNICODE
1659 tmp
= _unicode_to_string(slots
, nslots
);
1667 /* Check for valid slot names and two special cases */
1668 for (i
= 0; i
< nslots
; i
++) {
1669 PyObject
*tmp
= PyTuple_GET_ITEM(slots
, i
);
1671 if (!valid_identifier(tmp
))
1673 assert(PyString_Check(tmp
));
1674 s
= PyString_AS_STRING(tmp
);
1675 if (strcmp(s
, "__dict__") == 0) {
1676 if (!may_add_dict
|| add_dict
) {
1677 PyErr_SetString(PyExc_TypeError
,
1678 "__dict__ slot disallowed: "
1679 "we already got one");
1684 if (strcmp(s
, "__weakref__") == 0) {
1685 if (!may_add_weak
|| add_weak
) {
1686 PyErr_SetString(PyExc_TypeError
,
1687 "__weakref__ slot disallowed: "
1688 "either we already got one, "
1689 "or __itemsize__ != 0");
1696 /* Copy slots into yet another tuple, demangling names */
1697 newslots
= PyTuple_New(nslots
- add_dict
- add_weak
);
1698 if (newslots
== NULL
)
1700 for (i
= j
= 0; i
< nslots
; i
++) {
1703 tmp
= PyTuple_GET_ITEM(slots
, i
);
1704 s
= PyString_AS_STRING(tmp
);
1705 if ((add_dict
&& strcmp(s
, "__dict__") == 0) ||
1706 (add_weak
&& strcmp(s
, "__weakref__") == 0))
1708 if (_Py_Mangle(PyString_AS_STRING(name
),
1709 PyString_AS_STRING(tmp
),
1710 buffer
, sizeof(buffer
)))
1712 tmp
= PyString_FromString(buffer
);
1716 PyTuple_SET_ITEM(newslots
, j
, tmp
);
1719 assert(j
== nslots
- add_dict
- add_weak
);
1724 /* Secondary bases may provide weakrefs or dict */
1726 ((may_add_dict
&& !add_dict
) ||
1727 (may_add_weak
&& !add_weak
))) {
1728 for (i
= 0; i
< nbases
; i
++) {
1729 tmp
= PyTuple_GET_ITEM(bases
, i
);
1730 if (tmp
== (PyObject
*)base
)
1731 continue; /* Skip primary base */
1732 if (PyClass_Check(tmp
)) {
1733 /* Classic base class provides both */
1734 if (may_add_dict
&& !add_dict
)
1736 if (may_add_weak
&& !add_weak
)
1740 assert(PyType_Check(tmp
));
1741 tmptype
= (PyTypeObject
*)tmp
;
1742 if (may_add_dict
&& !add_dict
&&
1743 tmptype
->tp_dictoffset
!= 0)
1745 if (may_add_weak
&& !add_weak
&&
1746 tmptype
->tp_weaklistoffset
!= 0)
1748 if (may_add_dict
&& !add_dict
)
1750 if (may_add_weak
&& !add_weak
)
1752 /* Nothing more to check */
1758 /* XXX From here until type is safely allocated,
1759 "return NULL" may leak slots! */
1761 /* Allocate the type object */
1762 type
= (PyTypeObject
*)metatype
->tp_alloc(metatype
, nslots
);
1768 /* Keep name and slots alive in the extended type object */
1769 et
= (PyHeapTypeObject
*)type
;
1774 /* Initialize tp_flags */
1775 type
->tp_flags
= Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HEAPTYPE
|
1776 Py_TPFLAGS_BASETYPE
;
1777 if (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
)
1778 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
1780 /* It's a new-style number unless it specifically inherits any
1781 old-style numeric behavior */
1782 if ((base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) ||
1783 (base
->tp_as_number
== NULL
))
1784 type
->tp_flags
|= Py_TPFLAGS_CHECKTYPES
;
1786 /* Initialize essential fields */
1787 type
->tp_as_number
= &et
->as_number
;
1788 type
->tp_as_sequence
= &et
->as_sequence
;
1789 type
->tp_as_mapping
= &et
->as_mapping
;
1790 type
->tp_as_buffer
= &et
->as_buffer
;
1791 type
->tp_name
= PyString_AS_STRING(name
);
1793 /* Set tp_base and tp_bases */
1794 type
->tp_bases
= bases
;
1796 type
->tp_base
= base
;
1798 /* Initialize tp_dict from passed-in dict */
1799 type
->tp_dict
= dict
= PyDict_Copy(dict
);
1805 /* Set __module__ in the dict */
1806 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
1807 tmp
= PyEval_GetGlobals();
1809 tmp
= PyDict_GetItemString(tmp
, "__name__");
1811 if (PyDict_SetItemString(dict
, "__module__",
1818 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
1819 and is a string. The __doc__ accessor will first look for tp_doc;
1820 if that fails, it will still look into __dict__.
1823 PyObject
*doc
= PyDict_GetItemString(dict
, "__doc__");
1824 if (doc
!= NULL
&& PyString_Check(doc
)) {
1825 const size_t n
= (size_t)PyString_GET_SIZE(doc
);
1826 type
->tp_doc
= (char *)PyObject_MALLOC(n
+1);
1827 if (type
->tp_doc
== NULL
) {
1831 memcpy(type
->tp_doc
, PyString_AS_STRING(doc
), n
+1);
1835 /* Special-case __new__: if it's a plain function,
1836 make it a static function */
1837 tmp
= PyDict_GetItemString(dict
, "__new__");
1838 if (tmp
!= NULL
&& PyFunction_Check(tmp
)) {
1839 tmp
= PyStaticMethod_New(tmp
);
1844 PyDict_SetItemString(dict
, "__new__", tmp
);
1848 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1849 mp
= PyHeapType_GET_MEMBERS(et
);
1850 slotoffset
= base
->tp_basicsize
;
1851 if (slots
!= NULL
) {
1852 for (i
= 0; i
< nslots
; i
++, mp
++) {
1853 mp
->name
= PyString_AS_STRING(
1854 PyTuple_GET_ITEM(slots
, i
));
1855 mp
->type
= T_OBJECT_EX
;
1856 mp
->offset
= slotoffset
;
1857 if (base
->tp_weaklistoffset
== 0 &&
1858 strcmp(mp
->name
, "__weakref__") == 0) {
1860 mp
->type
= T_OBJECT
;
1861 mp
->flags
= READONLY
;
1862 type
->tp_weaklistoffset
= slotoffset
;
1864 slotoffset
+= sizeof(PyObject
*);
1868 if (base
->tp_itemsize
)
1869 type
->tp_dictoffset
= -(long)sizeof(PyObject
*);
1871 type
->tp_dictoffset
= slotoffset
;
1872 slotoffset
+= sizeof(PyObject
*);
1875 assert(!base
->tp_itemsize
);
1876 type
->tp_weaklistoffset
= slotoffset
;
1877 slotoffset
+= sizeof(PyObject
*);
1879 type
->tp_basicsize
= slotoffset
;
1880 type
->tp_itemsize
= base
->tp_itemsize
;
1881 type
->tp_members
= PyHeapType_GET_MEMBERS(et
);
1883 if (type
->tp_weaklistoffset
&& type
->tp_dictoffset
)
1884 type
->tp_getset
= subtype_getsets_full
;
1885 else if (type
->tp_weaklistoffset
&& !type
->tp_dictoffset
)
1886 type
->tp_getset
= subtype_getsets_weakref_only
;
1887 else if (!type
->tp_weaklistoffset
&& type
->tp_dictoffset
)
1888 type
->tp_getset
= subtype_getsets_dict_only
;
1890 type
->tp_getset
= NULL
;
1892 /* Special case some slots */
1893 if (type
->tp_dictoffset
!= 0 || nslots
> 0) {
1894 if (base
->tp_getattr
== NULL
&& base
->tp_getattro
== NULL
)
1895 type
->tp_getattro
= PyObject_GenericGetAttr
;
1896 if (base
->tp_setattr
== NULL
&& base
->tp_setattro
== NULL
)
1897 type
->tp_setattro
= PyObject_GenericSetAttr
;
1899 type
->tp_dealloc
= subtype_dealloc
;
1901 /* Enable GC unless there are really no instance variables possible */
1902 if (!(type
->tp_basicsize
== sizeof(PyObject
) &&
1903 type
->tp_itemsize
== 0))
1904 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
1906 /* Always override allocation strategy to use regular heap */
1907 type
->tp_alloc
= PyType_GenericAlloc
;
1908 if (type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) {
1909 type
->tp_free
= PyObject_GC_Del
;
1910 type
->tp_traverse
= subtype_traverse
;
1911 type
->tp_clear
= subtype_clear
;
1914 type
->tp_free
= PyObject_Del
;
1916 /* Initialize the rest */
1917 if (PyType_Ready(type
) < 0) {
1922 /* Put the proper slots in place */
1923 fixup_slot_dispatchers(type
);
1925 return (PyObject
*)type
;
1928 /* Internal API to look for a name through the MRO.
1929 This returns a borrowed reference, and doesn't set an exception! */
1931 _PyType_Lookup(PyTypeObject
*type
, PyObject
*name
)
1934 PyObject
*mro
, *res
, *base
, *dict
;
1936 /* Look in tp_dict of types in MRO */
1939 /* If mro is NULL, the type is either not yet initialized
1940 by PyType_Ready(), or already cleared by type_clear().
1941 Either way the safest thing to do is to return NULL. */
1945 assert(PyTuple_Check(mro
));
1946 n
= PyTuple_GET_SIZE(mro
);
1947 for (i
= 0; i
< n
; i
++) {
1948 base
= PyTuple_GET_ITEM(mro
, i
);
1949 if (PyClass_Check(base
))
1950 dict
= ((PyClassObject
*)base
)->cl_dict
;
1952 assert(PyType_Check(base
));
1953 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1955 assert(dict
&& PyDict_Check(dict
));
1956 res
= PyDict_GetItem(dict
, name
);
1963 /* This is similar to PyObject_GenericGetAttr(),
1964 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1966 type_getattro(PyTypeObject
*type
, PyObject
*name
)
1968 PyTypeObject
*metatype
= type
->ob_type
;
1969 PyObject
*meta_attribute
, *attribute
;
1970 descrgetfunc meta_get
;
1972 /* Initialize this type (we'll assume the metatype is initialized) */
1973 if (type
->tp_dict
== NULL
) {
1974 if (PyType_Ready(type
) < 0)
1978 /* No readable descriptor found yet */
1981 /* Look for the attribute in the metatype */
1982 meta_attribute
= _PyType_Lookup(metatype
, name
);
1984 if (meta_attribute
!= NULL
) {
1985 meta_get
= meta_attribute
->ob_type
->tp_descr_get
;
1987 if (meta_get
!= NULL
&& PyDescr_IsData(meta_attribute
)) {
1988 /* Data descriptors implement tp_descr_set to intercept
1989 * writes. Assume the attribute is not overridden in
1990 * type's tp_dict (and bases): call the descriptor now.
1992 return meta_get(meta_attribute
, (PyObject
*)type
,
1993 (PyObject
*)metatype
);
1997 /* No data descriptor found on metatype. Look in tp_dict of this
1998 * type and its bases */
1999 attribute
= _PyType_Lookup(type
, name
);
2000 if (attribute
!= NULL
) {
2001 /* Implement descriptor functionality, if any */
2002 descrgetfunc local_get
= attribute
->ob_type
->tp_descr_get
;
2003 if (local_get
!= NULL
) {
2004 /* NULL 2nd argument indicates the descriptor was
2005 * found on the target object itself (or a base) */
2006 return local_get(attribute
, (PyObject
*)NULL
,
2010 Py_INCREF(attribute
);
2014 /* No attribute found in local __dict__ (or bases): use the
2015 * descriptor from the metatype, if any */
2016 if (meta_get
!= NULL
)
2017 return meta_get(meta_attribute
, (PyObject
*)type
,
2018 (PyObject
*)metatype
);
2020 /* If an ordinary attribute was found on the metatype, return it now */
2021 if (meta_attribute
!= NULL
) {
2022 Py_INCREF(meta_attribute
);
2023 return meta_attribute
;
2027 PyErr_Format(PyExc_AttributeError
,
2028 "type object '%.50s' has no attribute '%.400s'",
2029 type
->tp_name
, PyString_AS_STRING(name
));
2034 type_setattro(PyTypeObject
*type
, PyObject
*name
, PyObject
*value
)
2036 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
2039 "can't set attributes of built-in/extension type '%s'",
2043 /* XXX Example of how I expect this to be used...
2044 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2047 if (PyObject_GenericSetAttr((PyObject
*)type
, name
, value
) < 0)
2049 return update_slot(type
, name
);
2053 type_dealloc(PyTypeObject
*type
)
2055 PyHeapTypeObject
*et
;
2057 /* Assert this is a heap-allocated type object */
2058 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
2059 _PyObject_GC_UNTRACK(type
);
2060 PyObject_ClearWeakRefs((PyObject
*)type
);
2061 et
= (PyHeapTypeObject
*)type
;
2062 Py_XDECREF(type
->tp_base
);
2063 Py_XDECREF(type
->tp_dict
);
2064 Py_XDECREF(type
->tp_bases
);
2065 Py_XDECREF(type
->tp_mro
);
2066 Py_XDECREF(type
->tp_cache
);
2067 Py_XDECREF(type
->tp_subclasses
);
2068 PyObject_Free(type
->tp_doc
);
2069 Py_XDECREF(et
->name
);
2070 Py_XDECREF(et
->slots
);
2071 type
->ob_type
->tp_free((PyObject
*)type
);
2075 type_subclasses(PyTypeObject
*type
, PyObject
*args_ignored
)
2077 PyObject
*list
, *raw
, *ref
;
2080 list
= PyList_New(0);
2083 raw
= type
->tp_subclasses
;
2086 assert(PyList_Check(raw
));
2087 n
= PyList_GET_SIZE(raw
);
2088 for (i
= 0; i
< n
; i
++) {
2089 ref
= PyList_GET_ITEM(raw
, i
);
2090 assert(PyWeakref_CheckRef(ref
));
2091 ref
= PyWeakref_GET_OBJECT(ref
);
2092 if (ref
!= Py_None
) {
2093 if (PyList_Append(list
, ref
) < 0) {
2102 static PyMethodDef type_methods
[] = {
2103 {"mro", (PyCFunction
)mro_external
, METH_NOARGS
,
2104 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2105 {"__subclasses__", (PyCFunction
)type_subclasses
, METH_NOARGS
,
2106 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2110 PyDoc_STRVAR(type_doc
,
2111 "type(object) -> the object's type\n"
2112 "type(name, bases, dict) -> a new type");
2115 type_traverse(PyTypeObject
*type
, visitproc visit
, void *arg
)
2119 /* Because of type_is_gc(), the collector only calls this
2121 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
2123 #define VISIT(SLOT) \
2125 err = visit((PyObject *)(SLOT), arg); \
2130 VISIT(type
->tp_dict
);
2131 VISIT(type
->tp_cache
);
2132 VISIT(type
->tp_mro
);
2133 VISIT(type
->tp_bases
);
2134 VISIT(type
->tp_base
);
2136 /* There's no need to visit type->tp_subclasses or
2137 ((PyHeapTypeObject *)type)->slots, because they can't be involved
2138 in cycles; tp_subclasses is a list of weak references,
2139 and slots is a tuple of strings. */
2147 type_clear(PyTypeObject
*type
)
2151 /* Because of type_is_gc(), the collector only calls this
2153 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
2155 #define CLEAR(SLOT) \
2157 tmp = (PyObject *)(SLOT); \
2162 /* The only field we need to clear is tp_mro, which is part of a
2163 hard cycle (its first element is the class itself) that won't
2164 be broken otherwise (it's a tuple and tuples don't have a
2165 tp_clear handler). None of the other fields need to be
2166 cleared, and here's why:
2169 It is a dict, so the collector will call its tp_clear.
2172 Not used; if it were, it would be a dict.
2175 If these are involved in a cycle, there must be at least
2176 one other, mutable object in the cycle, e.g. a base
2177 class's dict; the cycle will be broken that way.
2180 A list of weak references can't be part of a cycle; and
2181 lists have their own tp_clear.
2183 slots (in PyHeapTypeObject):
2184 A tuple of strings can't be part of a cycle.
2187 CLEAR(type
->tp_mro
);
2195 type_is_gc(PyTypeObject
*type
)
2197 return type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
;
2200 PyTypeObject PyType_Type
= {
2201 PyObject_HEAD_INIT(&PyType_Type
)
2203 "type", /* tp_name */
2204 sizeof(PyHeapTypeObject
), /* tp_basicsize */
2205 sizeof(PyMemberDef
), /* tp_itemsize */
2206 (destructor
)type_dealloc
, /* tp_dealloc */
2210 type_compare
, /* tp_compare */
2211 (reprfunc
)type_repr
, /* tp_repr */
2212 0, /* tp_as_number */
2213 0, /* tp_as_sequence */
2214 0, /* tp_as_mapping */
2215 (hashfunc
)_Py_HashPointer
, /* tp_hash */
2216 (ternaryfunc
)type_call
, /* tp_call */
2218 (getattrofunc
)type_getattro
, /* tp_getattro */
2219 (setattrofunc
)type_setattro
, /* tp_setattro */
2220 0, /* tp_as_buffer */
2221 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
2222 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2223 type_doc
, /* tp_doc */
2224 (traverseproc
)type_traverse
, /* tp_traverse */
2225 (inquiry
)type_clear
, /* tp_clear */
2226 0, /* tp_richcompare */
2227 offsetof(PyTypeObject
, tp_weaklist
), /* tp_weaklistoffset */
2229 0, /* tp_iternext */
2230 type_methods
, /* tp_methods */
2231 type_members
, /* tp_members */
2232 type_getsets
, /* tp_getset */
2235 0, /* tp_descr_get */
2236 0, /* tp_descr_set */
2237 offsetof(PyTypeObject
, tp_dict
), /* tp_dictoffset */
2240 type_new
, /* tp_new */
2241 PyObject_GC_Del
, /* tp_free */
2242 (inquiry
)type_is_gc
, /* tp_is_gc */
2246 /* The base type of all types (eventually)... except itself. */
2249 object_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2254 /* If we don't have a tp_new for a new-style class, new will use this one.
2255 Therefore this should take no arguments/keywords. However, this new may
2256 also be inherited by objects that define a tp_init but no tp_new. These
2257 objects WILL pass argumets to tp_new, because it gets the same args as
2258 tp_init. So only allow arguments if we aren't using the default init, in
2259 which case we expect init to handle argument parsing. */
2261 object_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2263 if (type
->tp_init
== object_init
&& (PyTuple_GET_SIZE(args
) ||
2264 (kwds
&& PyDict_Check(kwds
) && PyDict_Size(kwds
)))) {
2265 PyErr_SetString(PyExc_TypeError
,
2266 "default __new__ takes no parameters");
2269 return type
->tp_alloc(type
, 0);
2273 object_dealloc(PyObject
*self
)
2275 self
->ob_type
->tp_free(self
);
2279 object_repr(PyObject
*self
)
2282 PyObject
*mod
, *name
, *rtn
;
2284 type
= self
->ob_type
;
2285 mod
= type_module(type
, NULL
);
2288 else if (!PyString_Check(mod
)) {
2292 name
= type_name(type
, NULL
);
2295 if (mod
!= NULL
&& strcmp(PyString_AS_STRING(mod
), "__builtin__"))
2296 rtn
= PyString_FromFormat("<%s.%s object at %p>",
2297 PyString_AS_STRING(mod
),
2298 PyString_AS_STRING(name
),
2301 rtn
= PyString_FromFormat("<%s object at %p>",
2302 type
->tp_name
, self
);
2309 object_str(PyObject
*self
)
2313 f
= self
->ob_type
->tp_repr
;
2320 object_hash(PyObject
*self
)
2322 return _Py_HashPointer(self
);
2326 object_get_class(PyObject
*self
, void *closure
)
2328 Py_INCREF(self
->ob_type
);
2329 return (PyObject
*)(self
->ob_type
);
2333 equiv_structs(PyTypeObject
*a
, PyTypeObject
*b
)
2338 a
->tp_basicsize
== b
->tp_basicsize
&&
2339 a
->tp_itemsize
== b
->tp_itemsize
&&
2340 a
->tp_dictoffset
== b
->tp_dictoffset
&&
2341 a
->tp_weaklistoffset
== b
->tp_weaklistoffset
&&
2342 ((a
->tp_flags
& Py_TPFLAGS_HAVE_GC
) ==
2343 (b
->tp_flags
& Py_TPFLAGS_HAVE_GC
)));
2347 same_slots_added(PyTypeObject
*a
, PyTypeObject
*b
)
2349 PyTypeObject
*base
= a
->tp_base
;
2352 if (base
!= b
->tp_base
)
2354 if (equiv_structs(a
, base
) && equiv_structs(b
, base
))
2356 size
= base
->tp_basicsize
;
2357 if (a
->tp_dictoffset
== size
&& b
->tp_dictoffset
== size
)
2358 size
+= sizeof(PyObject
*);
2359 if (a
->tp_weaklistoffset
== size
&& b
->tp_weaklistoffset
== size
)
2360 size
+= sizeof(PyObject
*);
2361 return size
== a
->tp_basicsize
&& size
== b
->tp_basicsize
;
2365 compatible_for_assignment(PyTypeObject
* old
, PyTypeObject
* new, char* attr
)
2367 PyTypeObject
*newbase
, *oldbase
;
2369 if (new->tp_dealloc
!= old
->tp_dealloc
||
2370 new->tp_free
!= old
->tp_free
)
2372 PyErr_Format(PyExc_TypeError
,
2374 "'%s' deallocator differs from '%s'",
2382 while (equiv_structs(newbase
, newbase
->tp_base
))
2383 newbase
= newbase
->tp_base
;
2384 while (equiv_structs(oldbase
, oldbase
->tp_base
))
2385 oldbase
= oldbase
->tp_base
;
2386 if (newbase
!= oldbase
&&
2387 (newbase
->tp_base
!= oldbase
->tp_base
||
2388 !same_slots_added(newbase
, oldbase
))) {
2389 PyErr_Format(PyExc_TypeError
,
2391 "'%s' object layout differs from '%s'",
2402 object_set_class(PyObject
*self
, PyObject
*value
, void *closure
)
2404 PyTypeObject
*old
= self
->ob_type
;
2407 if (value
== NULL
) {
2408 PyErr_SetString(PyExc_TypeError
,
2409 "can't delete __class__ attribute");
2412 if (!PyType_Check(value
)) {
2413 PyErr_Format(PyExc_TypeError
,
2414 "__class__ must be set to new-style class, not '%s' object",
2415 value
->ob_type
->tp_name
);
2418 new = (PyTypeObject
*)value
;
2419 if (!(new->tp_flags
& Py_TPFLAGS_HEAPTYPE
) ||
2420 !(old
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
2422 PyErr_Format(PyExc_TypeError
,
2423 "__class__ assignment: only for heap types");
2426 if (compatible_for_assignment(new, old
, "__class__")) {
2428 self
->ob_type
= new;
2437 static PyGetSetDef object_getsets
[] = {
2438 {"__class__", object_get_class
, object_set_class
,
2439 PyDoc_STR("the object's class")},
2444 /* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2445 We fall back to helpers in copy_reg for:
2446 - pickle protocols < 2
2447 - calculating the list of slot names (done only once per class)
2448 - the __newobj__ function (which is used as a token but never called)
2452 import_copy_reg(void)
2454 static PyObject
*copy_reg_str
;
2456 if (!copy_reg_str
) {
2457 copy_reg_str
= PyString_InternFromString("copy_reg");
2458 if (copy_reg_str
== NULL
)
2462 return PyImport_Import(copy_reg_str
);
2466 slotnames(PyObject
*cls
)
2470 PyObject
*slotnames
;
2472 if (!PyType_Check(cls
)) {
2477 clsdict
= ((PyTypeObject
*)cls
)->tp_dict
;
2478 slotnames
= PyDict_GetItemString(clsdict
, "__slotnames__");
2479 if (slotnames
!= NULL
) {
2480 Py_INCREF(slotnames
);
2484 copy_reg
= import_copy_reg();
2485 if (copy_reg
== NULL
)
2488 slotnames
= PyObject_CallMethod(copy_reg
, "_slotnames", "O", cls
);
2489 Py_DECREF(copy_reg
);
2490 if (slotnames
!= NULL
&&
2491 slotnames
!= Py_None
&&
2492 !PyList_Check(slotnames
))
2494 PyErr_SetString(PyExc_TypeError
,
2495 "copy_reg._slotnames didn't return a list or None");
2496 Py_DECREF(slotnames
);
2504 reduce_2(PyObject
*obj
)
2506 PyObject
*cls
, *getnewargs
;
2507 PyObject
*args
= NULL
, *args2
= NULL
;
2508 PyObject
*getstate
= NULL
, *state
= NULL
, *names
= NULL
;
2509 PyObject
*slots
= NULL
, *listitems
= NULL
, *dictitems
= NULL
;
2510 PyObject
*copy_reg
= NULL
, *newobj
= NULL
, *res
= NULL
;
2513 cls
= PyObject_GetAttrString(obj
, "__class__");
2517 getnewargs
= PyObject_GetAttrString(obj
, "__getnewargs__");
2518 if (getnewargs
!= NULL
) {
2519 args
= PyObject_CallObject(getnewargs
, NULL
);
2520 Py_DECREF(getnewargs
);
2521 if (args
!= NULL
&& !PyTuple_Check(args
)) {
2522 PyErr_SetString(PyExc_TypeError
,
2523 "__getnewargs__ should return a tuple");
2529 args
= PyTuple_New(0);
2534 getstate
= PyObject_GetAttrString(obj
, "__getstate__");
2535 if (getstate
!= NULL
) {
2536 state
= PyObject_CallObject(getstate
, NULL
);
2537 Py_DECREF(getstate
);
2540 state
= PyObject_GetAttrString(obj
, "__dict__");
2541 if (state
== NULL
) {
2546 names
= slotnames(cls
);
2549 if (names
!= Py_None
) {
2550 assert(PyList_Check(names
));
2551 slots
= PyDict_New();
2555 /* Can't pre-compute the list size; the list
2556 is stored on the class so accessible to other
2557 threads, which may be run by DECREF */
2558 for (i
= 0; i
< PyList_GET_SIZE(names
); i
++) {
2559 PyObject
*name
, *value
;
2560 name
= PyList_GET_ITEM(names
, i
);
2561 value
= PyObject_GetAttr(obj
, name
);
2565 int err
= PyDict_SetItem(slots
, name
,
2574 state
= Py_BuildValue("(NO)", state
, slots
);
2581 if (!PyList_Check(obj
)) {
2582 listitems
= Py_None
;
2583 Py_INCREF(listitems
);
2586 listitems
= PyObject_GetIter(obj
);
2587 if (listitems
== NULL
)
2591 if (!PyDict_Check(obj
)) {
2592 dictitems
= Py_None
;
2593 Py_INCREF(dictitems
);
2596 dictitems
= PyObject_CallMethod(obj
, "iteritems", "");
2597 if (dictitems
== NULL
)
2601 copy_reg
= import_copy_reg();
2602 if (copy_reg
== NULL
)
2604 newobj
= PyObject_GetAttrString(copy_reg
, "__newobj__");
2608 n
= PyTuple_GET_SIZE(args
);
2609 args2
= PyTuple_New(n
+1);
2612 PyTuple_SET_ITEM(args2
, 0, cls
);
2614 for (i
= 0; i
< n
; i
++) {
2615 PyObject
*v
= PyTuple_GET_ITEM(args
, i
);
2617 PyTuple_SET_ITEM(args2
, i
+1, v
);
2620 res
= Py_BuildValue("(OOOOO)",
2621 newobj
, args2
, state
, listitems
, dictitems
);
2630 Py_XDECREF(listitems
);
2631 Py_XDECREF(dictitems
);
2632 Py_XDECREF(copy_reg
);
2638 object_reduce_ex(PyObject
*self
, PyObject
*args
)
2640 /* Call copy_reg._reduce_ex(self, proto) */
2641 PyObject
*reduce
, *copy_reg
, *res
;
2644 if (!PyArg_ParseTuple(args
, "|i:__reduce_ex__", &proto
))
2647 reduce
= PyObject_GetAttrString(self
, "__reduce__");
2651 PyObject
*cls
, *clsreduce
, *objreduce
;
2653 cls
= PyObject_GetAttrString(self
, "__class__");
2658 clsreduce
= PyObject_GetAttrString(cls
, "__reduce__");
2660 if (clsreduce
== NULL
) {
2664 objreduce
= PyDict_GetItemString(PyBaseObject_Type
.tp_dict
,
2666 override
= (clsreduce
!= objreduce
);
2667 Py_DECREF(clsreduce
);
2669 res
= PyObject_CallObject(reduce
, NULL
);
2678 return reduce_2(self
);
2680 copy_reg
= import_copy_reg();
2684 res
= PyEval_CallMethod(copy_reg
, "_reduce_ex", "(Oi)", self
, proto
);
2685 Py_DECREF(copy_reg
);
2690 static PyMethodDef object_methods
[] = {
2691 {"__reduce_ex__", object_reduce_ex
, METH_VARARGS
,
2692 PyDoc_STR("helper for pickle")},
2693 {"__reduce__", object_reduce_ex
, METH_VARARGS
,
2694 PyDoc_STR("helper for pickle")},
2699 PyTypeObject PyBaseObject_Type
= {
2700 PyObject_HEAD_INIT(&PyType_Type
)
2702 "object", /* tp_name */
2703 sizeof(PyObject
), /* tp_basicsize */
2704 0, /* tp_itemsize */
2705 (destructor
)object_dealloc
, /* tp_dealloc */
2710 object_repr
, /* tp_repr */
2711 0, /* tp_as_number */
2712 0, /* tp_as_sequence */
2713 0, /* tp_as_mapping */
2714 object_hash
, /* tp_hash */
2716 object_str
, /* tp_str */
2717 PyObject_GenericGetAttr
, /* tp_getattro */
2718 PyObject_GenericSetAttr
, /* tp_setattro */
2719 0, /* tp_as_buffer */
2720 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2721 PyDoc_STR("The most base type"), /* tp_doc */
2722 0, /* tp_traverse */
2724 0, /* tp_richcompare */
2725 0, /* tp_weaklistoffset */
2727 0, /* tp_iternext */
2728 object_methods
, /* tp_methods */
2730 object_getsets
, /* tp_getset */
2733 0, /* tp_descr_get */
2734 0, /* tp_descr_set */
2735 0, /* tp_dictoffset */
2736 object_init
, /* tp_init */
2737 PyType_GenericAlloc
, /* tp_alloc */
2738 object_new
, /* tp_new */
2739 PyObject_Del
, /* tp_free */
2743 /* Initialize the __dict__ in a type object */
2746 add_methods(PyTypeObject
*type
, PyMethodDef
*meth
)
2748 PyObject
*dict
= type
->tp_dict
;
2750 for (; meth
->ml_name
!= NULL
; meth
++) {
2752 if (PyDict_GetItemString(dict
, meth
->ml_name
))
2754 if (meth
->ml_flags
& METH_CLASS
) {
2755 if (meth
->ml_flags
& METH_STATIC
) {
2756 PyErr_SetString(PyExc_ValueError
,
2757 "method cannot be both class and static");
2760 descr
= PyDescr_NewClassMethod(type
, meth
);
2762 else if (meth
->ml_flags
& METH_STATIC
) {
2763 PyObject
*cfunc
= PyCFunction_New(meth
, NULL
);
2766 descr
= PyStaticMethod_New(cfunc
);
2770 descr
= PyDescr_NewMethod(type
, meth
);
2774 if (PyDict_SetItemString(dict
, meth
->ml_name
, descr
) < 0)
2782 add_members(PyTypeObject
*type
, PyMemberDef
*memb
)
2784 PyObject
*dict
= type
->tp_dict
;
2786 for (; memb
->name
!= NULL
; memb
++) {
2788 if (PyDict_GetItemString(dict
, memb
->name
))
2790 descr
= PyDescr_NewMember(type
, memb
);
2793 if (PyDict_SetItemString(dict
, memb
->name
, descr
) < 0)
2801 add_getset(PyTypeObject
*type
, PyGetSetDef
*gsp
)
2803 PyObject
*dict
= type
->tp_dict
;
2805 for (; gsp
->name
!= NULL
; gsp
++) {
2807 if (PyDict_GetItemString(dict
, gsp
->name
))
2809 descr
= PyDescr_NewGetSet(type
, gsp
);
2813 if (PyDict_SetItemString(dict
, gsp
->name
, descr
) < 0)
2821 inherit_special(PyTypeObject
*type
, PyTypeObject
*base
)
2823 int oldsize
, newsize
;
2825 /* Special flag magic */
2826 if (!type
->tp_as_buffer
&& base
->tp_as_buffer
) {
2827 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_GETCHARBUFFER
;
2829 base
->tp_flags
& Py_TPFLAGS_HAVE_GETCHARBUFFER
;
2831 if (!type
->tp_as_sequence
&& base
->tp_as_sequence
) {
2832 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_SEQUENCE_IN
;
2833 type
->tp_flags
|= base
->tp_flags
& Py_TPFLAGS_HAVE_SEQUENCE_IN
;
2835 if ((type
->tp_flags
& Py_TPFLAGS_HAVE_INPLACEOPS
) !=
2836 (base
->tp_flags
& Py_TPFLAGS_HAVE_INPLACEOPS
)) {
2837 if ((!type
->tp_as_number
&& base
->tp_as_number
) ||
2838 (!type
->tp_as_sequence
&& base
->tp_as_sequence
)) {
2839 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_INPLACEOPS
;
2840 if (!type
->tp_as_number
&& !type
->tp_as_sequence
) {
2841 type
->tp_flags
|= base
->tp_flags
&
2842 Py_TPFLAGS_HAVE_INPLACEOPS
;
2847 if (!type
->tp_as_number
&& base
->tp_as_number
) {
2848 type
->tp_flags
&= ~Py_TPFLAGS_CHECKTYPES
;
2849 type
->tp_flags
|= base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
;
2852 /* Copying basicsize is connected to the GC flags */
2853 oldsize
= base
->tp_basicsize
;
2854 newsize
= type
->tp_basicsize
? type
->tp_basicsize
: oldsize
;
2855 if (!(type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
2856 (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
2857 (type
->tp_flags
& Py_TPFLAGS_HAVE_RICHCOMPARE
/*GC slots exist*/) &&
2858 (!type
->tp_traverse
&& !type
->tp_clear
)) {
2859 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
2860 if (type
->tp_traverse
== NULL
)
2861 type
->tp_traverse
= base
->tp_traverse
;
2862 if (type
->tp_clear
== NULL
)
2863 type
->tp_clear
= base
->tp_clear
;
2865 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
2866 /* The condition below could use some explanation.
2867 It appears that tp_new is not inherited for static types
2868 whose base class is 'object'; this seems to be a precaution
2869 so that old extension types don't suddenly become
2870 callable (object.__new__ wouldn't insure the invariants
2871 that the extension type's own factory function ensures).
2872 Heap types, of course, are under our control, so they do
2873 inherit tp_new; static extension types that specify some
2874 other built-in type as the default are considered
2875 new-style-aware so they also inherit object.__new__. */
2876 if (base
!= &PyBaseObject_Type
||
2877 (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
2878 if (type
->tp_new
== NULL
)
2879 type
->tp_new
= base
->tp_new
;
2882 type
->tp_basicsize
= newsize
;
2884 /* Copy other non-function slots */
2887 #define COPYVAL(SLOT) \
2888 if (type->SLOT == 0) type->SLOT = base->SLOT
2890 COPYVAL(tp_itemsize
);
2891 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_WEAKREFS
) {
2892 COPYVAL(tp_weaklistoffset
);
2894 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
2895 COPYVAL(tp_dictoffset
);
2900 inherit_slots(PyTypeObject
*type
, PyTypeObject
*base
)
2902 PyTypeObject
*basebase
;
2911 #define SLOTDEFINED(SLOT) \
2912 (base->SLOT != 0 && \
2913 (basebase == NULL || base->SLOT != basebase->SLOT))
2915 #define COPYSLOT(SLOT) \
2916 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
2918 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2919 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2920 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
2921 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
2923 /* This won't inherit indirect slots (from tp_as_number etc.)
2924 if type doesn't provide the space. */
2926 if (type
->tp_as_number
!= NULL
&& base
->tp_as_number
!= NULL
) {
2927 basebase
= base
->tp_base
;
2928 if (basebase
->tp_as_number
== NULL
)
2931 COPYNUM(nb_subtract
);
2932 COPYNUM(nb_multiply
);
2934 COPYNUM(nb_remainder
);
2937 COPYNUM(nb_negative
);
2938 COPYNUM(nb_positive
);
2939 COPYNUM(nb_absolute
);
2940 COPYNUM(nb_nonzero
);
2953 COPYNUM(nb_inplace_add
);
2954 COPYNUM(nb_inplace_subtract
);
2955 COPYNUM(nb_inplace_multiply
);
2956 COPYNUM(nb_inplace_divide
);
2957 COPYNUM(nb_inplace_remainder
);
2958 COPYNUM(nb_inplace_power
);
2959 COPYNUM(nb_inplace_lshift
);
2960 COPYNUM(nb_inplace_rshift
);
2961 COPYNUM(nb_inplace_and
);
2962 COPYNUM(nb_inplace_xor
);
2963 COPYNUM(nb_inplace_or
);
2964 if (base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) {
2965 COPYNUM(nb_true_divide
);
2966 COPYNUM(nb_floor_divide
);
2967 COPYNUM(nb_inplace_true_divide
);
2968 COPYNUM(nb_inplace_floor_divide
);
2972 if (type
->tp_as_sequence
!= NULL
&& base
->tp_as_sequence
!= NULL
) {
2973 basebase
= base
->tp_base
;
2974 if (basebase
->tp_as_sequence
== NULL
)
2981 COPYSEQ(sq_ass_item
);
2982 COPYSEQ(sq_ass_slice
);
2983 COPYSEQ(sq_contains
);
2984 COPYSEQ(sq_inplace_concat
);
2985 COPYSEQ(sq_inplace_repeat
);
2988 if (type
->tp_as_mapping
!= NULL
&& base
->tp_as_mapping
!= NULL
) {
2989 basebase
= base
->tp_base
;
2990 if (basebase
->tp_as_mapping
== NULL
)
2993 COPYMAP(mp_subscript
);
2994 COPYMAP(mp_ass_subscript
);
2997 if (type
->tp_as_buffer
!= NULL
&& base
->tp_as_buffer
!= NULL
) {
2998 basebase
= base
->tp_base
;
2999 if (basebase
->tp_as_buffer
== NULL
)
3001 COPYBUF(bf_getreadbuffer
);
3002 COPYBUF(bf_getwritebuffer
);
3003 COPYBUF(bf_getsegcount
);
3004 COPYBUF(bf_getcharbuffer
);
3007 basebase
= base
->tp_base
;
3009 COPYSLOT(tp_dealloc
);
3011 if (type
->tp_getattr
== NULL
&& type
->tp_getattro
== NULL
) {
3012 type
->tp_getattr
= base
->tp_getattr
;
3013 type
->tp_getattro
= base
->tp_getattro
;
3015 if (type
->tp_setattr
== NULL
&& type
->tp_setattro
== NULL
) {
3016 type
->tp_setattr
= base
->tp_setattr
;
3017 type
->tp_setattro
= base
->tp_setattro
;
3019 /* tp_compare see tp_richcompare */
3021 /* tp_hash see tp_richcompare */
3024 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_RICHCOMPARE
) {
3025 if (type
->tp_compare
== NULL
&&
3026 type
->tp_richcompare
== NULL
&&
3027 type
->tp_hash
== NULL
)
3029 type
->tp_compare
= base
->tp_compare
;
3030 type
->tp_richcompare
= base
->tp_richcompare
;
3031 type
->tp_hash
= base
->tp_hash
;
3035 COPYSLOT(tp_compare
);
3037 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_ITER
) {
3039 COPYSLOT(tp_iternext
);
3041 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
3042 COPYSLOT(tp_descr_get
);
3043 COPYSLOT(tp_descr_set
);
3044 COPYSLOT(tp_dictoffset
);
3052 static int add_operators(PyTypeObject
*);
3055 PyType_Ready(PyTypeObject
*type
)
3057 PyObject
*dict
, *bases
;
3061 if (type
->tp_flags
& Py_TPFLAGS_READY
) {
3062 assert(type
->tp_dict
!= NULL
);
3065 assert((type
->tp_flags
& Py_TPFLAGS_READYING
) == 0);
3067 type
->tp_flags
|= Py_TPFLAGS_READYING
;
3069 #ifdef Py_TRACE_REFS
3070 /* PyType_Ready is the closest thing we have to a choke point
3071 * for type objects, so is the best place I can think of to try
3072 * to get type objects into the doubly-linked list of all objects.
3073 * Still, not all type objects go thru PyType_Ready.
3075 _Py_AddToAllObjects((PyObject
*)type
, 0);
3078 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3079 base
= type
->tp_base
;
3080 if (base
== NULL
&& type
!= &PyBaseObject_Type
)
3081 base
= type
->tp_base
= &PyBaseObject_Type
;
3083 /* Initialize the base class */
3084 if (base
&& base
->tp_dict
== NULL
) {
3085 if (PyType_Ready(base
) < 0)
3089 /* Initialize ob_type if NULL. This means extensions that want to be
3090 compilable separately on Windows can call PyType_Ready() instead of
3091 initializing the ob_type field of their type objects. */
3092 if (type
->ob_type
== NULL
)
3093 type
->ob_type
= base
->ob_type
;
3095 /* Initialize tp_bases */
3096 bases
= type
->tp_bases
;
3097 if (bases
== NULL
) {
3099 bases
= PyTuple_New(0);
3101 bases
= Py_BuildValue("(O)", base
);
3104 type
->tp_bases
= bases
;
3107 /* Initialize tp_dict */
3108 dict
= type
->tp_dict
;
3110 dict
= PyDict_New();
3113 type
->tp_dict
= dict
;
3116 /* Add type-specific descriptors to tp_dict */
3117 if (add_operators(type
) < 0)
3119 if (type
->tp_methods
!= NULL
) {
3120 if (add_methods(type
, type
->tp_methods
) < 0)
3123 if (type
->tp_members
!= NULL
) {
3124 if (add_members(type
, type
->tp_members
) < 0)
3127 if (type
->tp_getset
!= NULL
) {
3128 if (add_getset(type
, type
->tp_getset
) < 0)
3132 /* Calculate method resolution order */
3133 if (mro_internal(type
) < 0) {
3137 /* Inherit special flags from dominant base */
3138 if (type
->tp_base
!= NULL
)
3139 inherit_special(type
, type
->tp_base
);
3141 /* Initialize tp_dict properly */
3142 bases
= type
->tp_mro
;
3143 assert(bases
!= NULL
);
3144 assert(PyTuple_Check(bases
));
3145 n
= PyTuple_GET_SIZE(bases
);
3146 for (i
= 1; i
< n
; i
++) {
3147 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
3148 if (PyType_Check(b
))
3149 inherit_slots(type
, (PyTypeObject
*)b
);
3152 /* if the type dictionary doesn't contain a __doc__, set it from
3155 if (PyDict_GetItemString(type
->tp_dict
, "__doc__") == NULL
) {
3156 if (type
->tp_doc
!= NULL
) {
3157 PyObject
*doc
= PyString_FromString(type
->tp_doc
);
3158 PyDict_SetItemString(type
->tp_dict
, "__doc__", doc
);
3161 PyDict_SetItemString(type
->tp_dict
,
3162 "__doc__", Py_None
);
3166 /* Some more special stuff */
3167 base
= type
->tp_base
;
3169 if (type
->tp_as_number
== NULL
)
3170 type
->tp_as_number
= base
->tp_as_number
;
3171 if (type
->tp_as_sequence
== NULL
)
3172 type
->tp_as_sequence
= base
->tp_as_sequence
;
3173 if (type
->tp_as_mapping
== NULL
)
3174 type
->tp_as_mapping
= base
->tp_as_mapping
;
3175 if (type
->tp_as_buffer
== NULL
)
3176 type
->tp_as_buffer
= base
->tp_as_buffer
;
3179 /* Link into each base class's list of subclasses */
3180 bases
= type
->tp_bases
;
3181 n
= PyTuple_GET_SIZE(bases
);
3182 for (i
= 0; i
< n
; i
++) {
3183 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
3184 if (PyType_Check(b
) &&
3185 add_subclass((PyTypeObject
*)b
, type
) < 0)
3189 /* All done -- set the ready flag */
3190 assert(type
->tp_dict
!= NULL
);
3192 (type
->tp_flags
& ~Py_TPFLAGS_READYING
) | Py_TPFLAGS_READY
;
3196 type
->tp_flags
&= ~Py_TPFLAGS_READYING
;
3201 add_subclass(PyTypeObject
*base
, PyTypeObject
*type
)
3204 PyObject
*list
, *ref
, *new;
3206 list
= base
->tp_subclasses
;
3208 base
->tp_subclasses
= list
= PyList_New(0);
3212 assert(PyList_Check(list
));
3213 new = PyWeakref_NewRef((PyObject
*)type
, NULL
);
3214 i
= PyList_GET_SIZE(list
);
3216 ref
= PyList_GET_ITEM(list
, i
);
3217 assert(PyWeakref_CheckRef(ref
));
3218 if (PyWeakref_GET_OBJECT(ref
) == Py_None
)
3219 return PyList_SetItem(list
, i
, new);
3221 i
= PyList_Append(list
, new);
3227 remove_subclass(PyTypeObject
*base
, PyTypeObject
*type
)
3230 PyObject
*list
, *ref
;
3232 list
= base
->tp_subclasses
;
3236 assert(PyList_Check(list
));
3237 i
= PyList_GET_SIZE(list
);
3239 ref
= PyList_GET_ITEM(list
, i
);
3240 assert(PyWeakref_CheckRef(ref
));
3241 if (PyWeakref_GET_OBJECT(ref
) == (PyObject
*)type
) {
3242 /* this can't fail, right? */
3243 PySequence_DelItem(list
, i
);
3249 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
3251 /* There's a wrapper *function* for each distinct function typedef used
3252 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3253 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3254 Most tables have only one entry; the tables for binary operators have two
3255 entries, one regular and one with reversed arguments. */
3258 wrap_inquiry(PyObject
*self
, PyObject
*args
, void *wrapped
)
3260 inquiry func
= (inquiry
)wrapped
;
3263 if (!PyArg_ParseTuple(args
, ""))
3265 res
= (*func
)(self
);
3266 if (res
== -1 && PyErr_Occurred())
3268 return PyInt_FromLong((long)res
);
3272 wrap_binaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3274 binaryfunc func
= (binaryfunc
)wrapped
;
3277 if (!PyArg_ParseTuple(args
, "O", &other
))
3279 return (*func
)(self
, other
);
3283 wrap_binaryfunc_l(PyObject
*self
, PyObject
*args
, void *wrapped
)
3285 binaryfunc func
= (binaryfunc
)wrapped
;
3288 if (!PyArg_ParseTuple(args
, "O", &other
))
3290 if (!(self
->ob_type
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) &&
3291 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
3292 Py_INCREF(Py_NotImplemented
);
3293 return Py_NotImplemented
;
3295 return (*func
)(self
, other
);
3299 wrap_binaryfunc_r(PyObject
*self
, PyObject
*args
, void *wrapped
)
3301 binaryfunc func
= (binaryfunc
)wrapped
;
3304 if (!PyArg_ParseTuple(args
, "O", &other
))
3306 if (!(self
->ob_type
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) &&
3307 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
3308 Py_INCREF(Py_NotImplemented
);
3309 return Py_NotImplemented
;
3311 return (*func
)(other
, self
);
3315 wrap_coercefunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3317 coercion func
= (coercion
)wrapped
;
3318 PyObject
*other
, *res
;
3321 if (!PyArg_ParseTuple(args
, "O", &other
))
3323 ok
= func(&self
, &other
);
3327 Py_INCREF(Py_NotImplemented
);
3328 return Py_NotImplemented
;
3330 res
= PyTuple_New(2);
3336 PyTuple_SET_ITEM(res
, 0, self
);
3337 PyTuple_SET_ITEM(res
, 1, other
);
3342 wrap_ternaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3344 ternaryfunc func
= (ternaryfunc
)wrapped
;
3346 PyObject
*third
= Py_None
;
3348 /* Note: This wrapper only works for __pow__() */
3350 if (!PyArg_ParseTuple(args
, "O|O", &other
, &third
))
3352 return (*func
)(self
, other
, third
);
3356 wrap_ternaryfunc_r(PyObject
*self
, PyObject
*args
, void *wrapped
)
3358 ternaryfunc func
= (ternaryfunc
)wrapped
;
3360 PyObject
*third
= Py_None
;
3362 /* Note: This wrapper only works for __pow__() */
3364 if (!PyArg_ParseTuple(args
, "O|O", &other
, &third
))
3366 return (*func
)(other
, self
, third
);
3370 wrap_unaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3372 unaryfunc func
= (unaryfunc
)wrapped
;
3374 if (!PyArg_ParseTuple(args
, ""))
3376 return (*func
)(self
);
3380 wrap_intargfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3382 intargfunc func
= (intargfunc
)wrapped
;
3385 if (!PyArg_ParseTuple(args
, "i", &i
))
3387 return (*func
)(self
, i
);
3391 getindex(PyObject
*self
, PyObject
*arg
)
3395 i
= PyInt_AsLong(arg
);
3396 if (i
== -1 && PyErr_Occurred())
3399 PySequenceMethods
*sq
= self
->ob_type
->tp_as_sequence
;
3400 if (sq
&& sq
->sq_length
) {
3401 int n
= (*sq
->sq_length
)(self
);
3411 wrap_sq_item(PyObject
*self
, PyObject
*args
, void *wrapped
)
3413 intargfunc func
= (intargfunc
)wrapped
;
3417 if (PyTuple_GET_SIZE(args
) == 1) {
3418 arg
= PyTuple_GET_ITEM(args
, 0);
3419 i
= getindex(self
, arg
);
3420 if (i
== -1 && PyErr_Occurred())
3422 return (*func
)(self
, i
);
3424 PyArg_ParseTuple(args
, "O", &arg
);
3425 assert(PyErr_Occurred());
3430 wrap_intintargfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3432 intintargfunc func
= (intintargfunc
)wrapped
;
3435 if (!PyArg_ParseTuple(args
, "ii", &i
, &j
))
3437 return (*func
)(self
, i
, j
);
3441 wrap_sq_setitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
3443 intobjargproc func
= (intobjargproc
)wrapped
;
3445 PyObject
*arg
, *value
;
3447 if (!PyArg_ParseTuple(args
, "OO", &arg
, &value
))
3449 i
= getindex(self
, arg
);
3450 if (i
== -1 && PyErr_Occurred())
3452 res
= (*func
)(self
, i
, value
);
3453 if (res
== -1 && PyErr_Occurred())
3460 wrap_sq_delitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
3462 intobjargproc func
= (intobjargproc
)wrapped
;
3466 if (!PyArg_ParseTuple(args
, "O", &arg
))
3468 i
= getindex(self
, arg
);
3469 if (i
== -1 && PyErr_Occurred())
3471 res
= (*func
)(self
, i
, NULL
);
3472 if (res
== -1 && PyErr_Occurred())
3479 wrap_intintobjargproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3481 intintobjargproc func
= (intintobjargproc
)wrapped
;
3485 if (!PyArg_ParseTuple(args
, "iiO", &i
, &j
, &value
))
3487 res
= (*func
)(self
, i
, j
, value
);
3488 if (res
== -1 && PyErr_Occurred())
3495 wrap_delslice(PyObject
*self
, PyObject
*args
, void *wrapped
)
3497 intintobjargproc func
= (intintobjargproc
)wrapped
;
3500 if (!PyArg_ParseTuple(args
, "ii", &i
, &j
))
3502 res
= (*func
)(self
, i
, j
, NULL
);
3503 if (res
== -1 && PyErr_Occurred())
3509 /* XXX objobjproc is a misnomer; should be objargpred */
3511 wrap_objobjproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3513 objobjproc func
= (objobjproc
)wrapped
;
3517 if (!PyArg_ParseTuple(args
, "O", &value
))
3519 res
= (*func
)(self
, value
);
3520 if (res
== -1 && PyErr_Occurred())
3522 return PyInt_FromLong((long)res
);
3526 wrap_objobjargproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3528 objobjargproc func
= (objobjargproc
)wrapped
;
3530 PyObject
*key
, *value
;
3532 if (!PyArg_ParseTuple(args
, "OO", &key
, &value
))
3534 res
= (*func
)(self
, key
, value
);
3535 if (res
== -1 && PyErr_Occurred())
3542 wrap_delitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
3544 objobjargproc func
= (objobjargproc
)wrapped
;
3548 if (!PyArg_ParseTuple(args
, "O", &key
))
3550 res
= (*func
)(self
, key
, NULL
);
3551 if (res
== -1 && PyErr_Occurred())
3558 wrap_cmpfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3560 cmpfunc func
= (cmpfunc
)wrapped
;
3564 if (!PyArg_ParseTuple(args
, "O", &other
))
3566 if (other
->ob_type
->tp_compare
!= func
&&
3567 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
3570 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3571 self
->ob_type
->tp_name
,
3572 self
->ob_type
->tp_name
,
3573 other
->ob_type
->tp_name
);
3576 res
= (*func
)(self
, other
);
3577 if (PyErr_Occurred())
3579 return PyInt_FromLong((long)res
);
3582 /* Helper to check for object.__setattr__ or __delattr__ applied to a type.
3583 This is called the Carlo Verre hack after its discoverer. */
3585 hackcheck(PyObject
*self
, setattrofunc func
, char *what
)
3587 PyTypeObject
*type
= self
->ob_type
;
3588 while (type
&& type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
3589 type
= type
->tp_base
;
3590 if (type
->tp_setattro
!= func
) {
3591 PyErr_Format(PyExc_TypeError
,
3592 "can't apply this %s to %s object",
3601 wrap_setattr(PyObject
*self
, PyObject
*args
, void *wrapped
)
3603 setattrofunc func
= (setattrofunc
)wrapped
;
3605 PyObject
*name
, *value
;
3607 if (!PyArg_ParseTuple(args
, "OO", &name
, &value
))
3609 if (!hackcheck(self
, func
, "__setattr__"))
3611 res
= (*func
)(self
, name
, value
);
3619 wrap_delattr(PyObject
*self
, PyObject
*args
, void *wrapped
)
3621 setattrofunc func
= (setattrofunc
)wrapped
;
3625 if (!PyArg_ParseTuple(args
, "O", &name
))
3627 if (!hackcheck(self
, func
, "__delattr__"))
3629 res
= (*func
)(self
, name
, NULL
);
3637 wrap_hashfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
3639 hashfunc func
= (hashfunc
)wrapped
;
3642 if (!PyArg_ParseTuple(args
, ""))
3644 res
= (*func
)(self
);
3645 if (res
== -1 && PyErr_Occurred())
3647 return PyInt_FromLong(res
);
3651 wrap_call(PyObject
*self
, PyObject
*args
, void *wrapped
, PyObject
*kwds
)
3653 ternaryfunc func
= (ternaryfunc
)wrapped
;
3655 return (*func
)(self
, args
, kwds
);
3659 wrap_richcmpfunc(PyObject
*self
, PyObject
*args
, void *wrapped
, int op
)
3661 richcmpfunc func
= (richcmpfunc
)wrapped
;
3664 if (!PyArg_ParseTuple(args
, "O", &other
))
3666 return (*func
)(self
, other
, op
);
3669 #undef RICHCMP_WRAPPER
3670 #define RICHCMP_WRAPPER(NAME, OP) \
3672 richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3674 return wrap_richcmpfunc(self, args, wrapped, OP); \
3677 RICHCMP_WRAPPER(lt
, Py_LT
)
3678 RICHCMP_WRAPPER(le
, Py_LE
)
3679 RICHCMP_WRAPPER(eq
, Py_EQ
)
3680 RICHCMP_WRAPPER(ne
, Py_NE
)
3681 RICHCMP_WRAPPER(gt
, Py_GT
)
3682 RICHCMP_WRAPPER(ge
, Py_GE
)
3685 wrap_next(PyObject
*self
, PyObject
*args
, void *wrapped
)
3687 unaryfunc func
= (unaryfunc
)wrapped
;
3690 if (!PyArg_ParseTuple(args
, ""))
3692 res
= (*func
)(self
);
3693 if (res
== NULL
&& !PyErr_Occurred())
3694 PyErr_SetNone(PyExc_StopIteration
);
3699 wrap_descr_get(PyObject
*self
, PyObject
*args
, void *wrapped
)
3701 descrgetfunc func
= (descrgetfunc
)wrapped
;
3703 PyObject
*type
= NULL
;
3705 if (!PyArg_ParseTuple(args
, "O|O", &obj
, &type
))
3709 if (type
== Py_None
)
3711 if (type
== NULL
&&obj
== NULL
) {
3712 PyErr_SetString(PyExc_TypeError
,
3713 "__get__(None, None) is invalid");
3716 return (*func
)(self
, obj
, type
);
3720 wrap_descr_set(PyObject
*self
, PyObject
*args
, void *wrapped
)
3722 descrsetfunc func
= (descrsetfunc
)wrapped
;
3723 PyObject
*obj
, *value
;
3726 if (!PyArg_ParseTuple(args
, "OO", &obj
, &value
))
3728 ret
= (*func
)(self
, obj
, value
);
3736 wrap_descr_delete(PyObject
*self
, PyObject
*args
, void *wrapped
)
3738 descrsetfunc func
= (descrsetfunc
)wrapped
;
3742 if (!PyArg_ParseTuple(args
, "O", &obj
))
3744 ret
= (*func
)(self
, obj
, NULL
);
3752 wrap_init(PyObject
*self
, PyObject
*args
, void *wrapped
, PyObject
*kwds
)
3754 initproc func
= (initproc
)wrapped
;
3756 if (func(self
, args
, kwds
) < 0)
3763 tp_new_wrapper(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
3765 PyTypeObject
*type
, *subtype
, *staticbase
;
3766 PyObject
*arg0
, *res
;
3768 if (self
== NULL
|| !PyType_Check(self
))
3769 Py_FatalError("__new__() called with non-type 'self'");
3770 type
= (PyTypeObject
*)self
;
3771 if (!PyTuple_Check(args
) || PyTuple_GET_SIZE(args
) < 1) {
3772 PyErr_Format(PyExc_TypeError
,
3773 "%s.__new__(): not enough arguments",
3777 arg0
= PyTuple_GET_ITEM(args
, 0);
3778 if (!PyType_Check(arg0
)) {
3779 PyErr_Format(PyExc_TypeError
,
3780 "%s.__new__(X): X is not a type object (%s)",
3782 arg0
->ob_type
->tp_name
);
3785 subtype
= (PyTypeObject
*)arg0
;
3786 if (!PyType_IsSubtype(subtype
, type
)) {
3787 PyErr_Format(PyExc_TypeError
,
3788 "%s.__new__(%s): %s is not a subtype of %s",
3796 /* Check that the use doesn't do something silly and unsafe like
3797 object.__new__(dict). To do this, we check that the
3798 most derived base that's not a heap type is this type. */
3799 staticbase
= subtype
;
3800 while (staticbase
&& (staticbase
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
3801 staticbase
= staticbase
->tp_base
;
3802 if (staticbase
->tp_new
!= type
->tp_new
) {
3803 PyErr_Format(PyExc_TypeError
,
3804 "%s.__new__(%s) is not safe, use %s.__new__()",
3807 staticbase
== NULL
? "?" : staticbase
->tp_name
);
3811 args
= PyTuple_GetSlice(args
, 1, PyTuple_GET_SIZE(args
));
3814 res
= type
->tp_new(subtype
, args
, kwds
);
3819 static struct PyMethodDef tp_new_methoddef
[] = {
3820 {"__new__", (PyCFunction
)tp_new_wrapper
, METH_KEYWORDS
,
3821 PyDoc_STR("T.__new__(S, ...) -> "
3822 "a new object with type S, a subtype of T")},
3827 add_tp_new_wrapper(PyTypeObject
*type
)
3831 if (PyDict_GetItemString(type
->tp_dict
, "__new__") != NULL
)
3833 func
= PyCFunction_New(tp_new_methoddef
, (PyObject
*)type
);
3836 return PyDict_SetItemString(type
->tp_dict
, "__new__", func
);
3839 /* Slot wrappers that call the corresponding __foo__ slot. See comments
3840 below at override_slots() for more explanation. */
3842 #define SLOT0(FUNCNAME, OPSTR) \
3844 FUNCNAME(PyObject *self) \
3846 static PyObject *cache_str; \
3847 return call_method(self, OPSTR, &cache_str, "()"); \
3850 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
3852 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
3854 static PyObject *cache_str; \
3855 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
3858 /* Boolean helper for SLOT1BINFULL().
3859 right.__class__ is a nontrivial subclass of left.__class__. */
3861 method_is_overloaded(PyObject
*left
, PyObject
*right
, char *name
)
3866 b
= PyObject_GetAttrString((PyObject
*)(right
->ob_type
), name
);
3869 /* If right doesn't have it, it's not overloaded */
3873 a
= PyObject_GetAttrString((PyObject
*)(left
->ob_type
), name
);
3877 /* If right has it but left doesn't, it's overloaded */
3881 ok
= PyObject_RichCompareBool(a
, b
, Py_NE
);
3893 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
3895 FUNCNAME(PyObject *self, PyObject *other) \
3897 static PyObject *cache_str, *rcache_str; \
3898 int do_other = self->ob_type != other->ob_type && \
3899 other->ob_type->tp_as_number != NULL && \
3900 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
3901 if (self->ob_type->tp_as_number != NULL && \
3902 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3905 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3906 method_is_overloaded(self, other, ROPSTR)) { \
3908 other, ROPSTR, &rcache_str, "(O)", self); \
3909 if (r != Py_NotImplemented) \
3915 self, OPSTR, &cache_str, "(O)", other); \
3916 if (r != Py_NotImplemented || \
3917 other->ob_type == self->ob_type) \
3922 return call_maybe( \
3923 other, ROPSTR, &rcache_str, "(O)", self); \
3925 Py_INCREF(Py_NotImplemented); \
3926 return Py_NotImplemented; \
3929 #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3930 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3932 #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3934 FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3936 static PyObject *cache_str; \
3937 return call_method(self, OPSTR, &cache_str, \
3938 "(" ARGCODES ")", arg1, arg2); \
3942 slot_sq_length(PyObject
*self
)
3944 static PyObject
*len_str
;
3945 PyObject
*res
= call_method(self
, "__len__", &len_str
, "()");
3950 len
= (int)PyInt_AsLong(res
);
3952 if (len
== -1 && PyErr_Occurred())
3955 PyErr_SetString(PyExc_ValueError
,
3956 "__len__() should return >= 0");
3962 SLOT1(slot_sq_concat
, "__add__", PyObject
*, "O")
3963 SLOT1(slot_sq_repeat
, "__mul__", int, "i")
3965 /* Super-optimized version of slot_sq_item.
3966 Other slots could do the same... */
3968 slot_sq_item(PyObject
*self
, int i
)
3970 static PyObject
*getitem_str
;
3971 PyObject
*func
, *args
= NULL
, *ival
= NULL
, *retval
= NULL
;
3974 if (getitem_str
== NULL
) {
3975 getitem_str
= PyString_InternFromString("__getitem__");
3976 if (getitem_str
== NULL
)
3979 func
= _PyType_Lookup(self
->ob_type
, getitem_str
);
3981 if ((f
= func
->ob_type
->tp_descr_get
) == NULL
)
3984 func
= f(func
, self
, (PyObject
*)(self
->ob_type
));
3989 ival
= PyInt_FromLong(i
);
3991 args
= PyTuple_New(1);
3993 PyTuple_SET_ITEM(args
, 0, ival
);
3994 retval
= PyObject_Call(func
, args
, NULL
);
4002 PyErr_SetObject(PyExc_AttributeError
, getitem_str
);
4010 SLOT2(slot_sq_slice
, "__getslice__", int, int, "ii")
4013 slot_sq_ass_item(PyObject
*self
, int index
, PyObject
*value
)
4016 static PyObject
*delitem_str
, *setitem_str
;
4019 res
= call_method(self
, "__delitem__", &delitem_str
,
4022 res
= call_method(self
, "__setitem__", &setitem_str
,
4023 "(iO)", index
, value
);
4031 slot_sq_ass_slice(PyObject
*self
, int i
, int j
, PyObject
*value
)
4034 static PyObject
*delslice_str
, *setslice_str
;
4037 res
= call_method(self
, "__delslice__", &delslice_str
,
4040 res
= call_method(self
, "__setslice__", &setslice_str
,
4041 "(iiO)", i
, j
, value
);
4049 slot_sq_contains(PyObject
*self
, PyObject
*value
)
4051 PyObject
*func
, *res
, *args
;
4054 static PyObject
*contains_str
;
4056 func
= lookup_maybe(self
, "__contains__", &contains_str
);
4058 args
= Py_BuildValue("(O)", value
);
4062 res
= PyObject_Call(func
, args
, NULL
);
4067 result
= PyObject_IsTrue(res
);
4071 else if (! PyErr_Occurred()) {
4072 result
= _PySequence_IterSearch(self
, value
,
4073 PY_ITERSEARCH_CONTAINS
);
4078 SLOT1(slot_sq_inplace_concat
, "__iadd__", PyObject
*, "O")
4079 SLOT1(slot_sq_inplace_repeat
, "__imul__", int, "i")
4081 #define slot_mp_length slot_sq_length
4083 SLOT1(slot_mp_subscript
, "__getitem__", PyObject
*, "O")
4086 slot_mp_ass_subscript(PyObject
*self
, PyObject
*key
, PyObject
*value
)
4089 static PyObject
*delitem_str
, *setitem_str
;
4092 res
= call_method(self
, "__delitem__", &delitem_str
,
4095 res
= call_method(self
, "__setitem__", &setitem_str
,
4096 "(OO)", key
, value
);
4103 SLOT1BIN(slot_nb_add
, nb_add
, "__add__", "__radd__")
4104 SLOT1BIN(slot_nb_subtract
, nb_subtract
, "__sub__", "__rsub__")
4105 SLOT1BIN(slot_nb_multiply
, nb_multiply
, "__mul__", "__rmul__")
4106 SLOT1BIN(slot_nb_divide
, nb_divide
, "__div__", "__rdiv__")
4107 SLOT1BIN(slot_nb_remainder
, nb_remainder
, "__mod__", "__rmod__")
4108 SLOT1BIN(slot_nb_divmod
, nb_divmod
, "__divmod__", "__rdivmod__")
4110 static PyObject
*slot_nb_power(PyObject
*, PyObject
*, PyObject
*);
4112 SLOT1BINFULL(slot_nb_power_binary
, slot_nb_power
,
4113 nb_power
, "__pow__", "__rpow__")
4116 slot_nb_power(PyObject
*self
, PyObject
*other
, PyObject
*modulus
)
4118 static PyObject
*pow_str
;
4120 if (modulus
== Py_None
)
4121 return slot_nb_power_binary(self
, other
);
4122 /* Three-arg power doesn't use __rpow__. But ternary_op
4123 can call this when the second argument's type uses
4124 slot_nb_power, so check before calling self.__pow__. */
4125 if (self
->ob_type
->tp_as_number
!= NULL
&&
4126 self
->ob_type
->tp_as_number
->nb_power
== slot_nb_power
) {
4127 return call_method(self
, "__pow__", &pow_str
,
4128 "(OO)", other
, modulus
);
4130 Py_INCREF(Py_NotImplemented
);
4131 return Py_NotImplemented
;
4134 SLOT0(slot_nb_negative
, "__neg__")
4135 SLOT0(slot_nb_positive
, "__pos__")
4136 SLOT0(slot_nb_absolute
, "__abs__")
4139 slot_nb_nonzero(PyObject
*self
)
4141 PyObject
*func
, *args
;
4142 static PyObject
*nonzero_str
, *len_str
;
4145 func
= lookup_maybe(self
, "__nonzero__", &nonzero_str
);
4147 if (PyErr_Occurred())
4149 func
= lookup_maybe(self
, "__len__", &len_str
);
4151 return PyErr_Occurred() ? -1 : 1;
4153 args
= PyTuple_New(0);
4155 PyObject
*temp
= PyObject_Call(func
, args
, NULL
);
4158 result
= PyObject_IsTrue(temp
);
4166 SLOT0(slot_nb_invert
, "__invert__")
4167 SLOT1BIN(slot_nb_lshift
, nb_lshift
, "__lshift__", "__rlshift__")
4168 SLOT1BIN(slot_nb_rshift
, nb_rshift
, "__rshift__", "__rrshift__")
4169 SLOT1BIN(slot_nb_and
, nb_and
, "__and__", "__rand__")
4170 SLOT1BIN(slot_nb_xor
, nb_xor
, "__xor__", "__rxor__")
4171 SLOT1BIN(slot_nb_or
, nb_or
, "__or__", "__ror__")
4174 slot_nb_coerce(PyObject
**a
, PyObject
**b
)
4176 static PyObject
*coerce_str
;
4177 PyObject
*self
= *a
, *other
= *b
;
4179 if (self
->ob_type
->tp_as_number
!= NULL
&&
4180 self
->ob_type
->tp_as_number
->nb_coerce
== slot_nb_coerce
) {
4183 self
, "__coerce__", &coerce_str
, "(O)", other
);
4186 if (r
== Py_NotImplemented
) {
4190 if (!PyTuple_Check(r
) || PyTuple_GET_SIZE(r
) != 2) {
4191 PyErr_SetString(PyExc_TypeError
,
4192 "__coerce__ didn't return a 2-tuple");
4196 *a
= PyTuple_GET_ITEM(r
, 0);
4198 *b
= PyTuple_GET_ITEM(r
, 1);
4204 if (other
->ob_type
->tp_as_number
!= NULL
&&
4205 other
->ob_type
->tp_as_number
->nb_coerce
== slot_nb_coerce
) {
4208 other
, "__coerce__", &coerce_str
, "(O)", self
);
4211 if (r
== Py_NotImplemented
) {
4215 if (!PyTuple_Check(r
) || PyTuple_GET_SIZE(r
) != 2) {
4216 PyErr_SetString(PyExc_TypeError
,
4217 "__coerce__ didn't return a 2-tuple");
4221 *a
= PyTuple_GET_ITEM(r
, 1);
4223 *b
= PyTuple_GET_ITEM(r
, 0);
4231 SLOT0(slot_nb_int
, "__int__")
4232 SLOT0(slot_nb_long
, "__long__")
4233 SLOT0(slot_nb_float
, "__float__")
4234 SLOT0(slot_nb_oct
, "__oct__")
4235 SLOT0(slot_nb_hex
, "__hex__")
4236 SLOT1(slot_nb_inplace_add
, "__iadd__", PyObject
*, "O")
4237 SLOT1(slot_nb_inplace_subtract
, "__isub__", PyObject
*, "O")
4238 SLOT1(slot_nb_inplace_multiply
, "__imul__", PyObject
*, "O")
4239 SLOT1(slot_nb_inplace_divide
, "__idiv__", PyObject
*, "O")
4240 SLOT1(slot_nb_inplace_remainder
, "__imod__", PyObject
*, "O")
4241 SLOT1(slot_nb_inplace_power
, "__ipow__", PyObject
*, "O")
4242 SLOT1(slot_nb_inplace_lshift
, "__ilshift__", PyObject
*, "O")
4243 SLOT1(slot_nb_inplace_rshift
, "__irshift__", PyObject
*, "O")
4244 SLOT1(slot_nb_inplace_and
, "__iand__", PyObject
*, "O")
4245 SLOT1(slot_nb_inplace_xor
, "__ixor__", PyObject
*, "O")
4246 SLOT1(slot_nb_inplace_or
, "__ior__", PyObject
*, "O")
4247 SLOT1BIN(slot_nb_floor_divide
, nb_floor_divide
,
4248 "__floordiv__", "__rfloordiv__")
4249 SLOT1BIN(slot_nb_true_divide
, nb_true_divide
, "__truediv__", "__rtruediv__")
4250 SLOT1(slot_nb_inplace_floor_divide
, "__ifloordiv__", PyObject
*, "O")
4251 SLOT1(slot_nb_inplace_true_divide
, "__itruediv__", PyObject
*, "O")
4254 half_compare(PyObject
*self
, PyObject
*other
)
4256 PyObject
*func
, *args
, *res
;
4257 static PyObject
*cmp_str
;
4260 func
= lookup_method(self
, "__cmp__", &cmp_str
);
4265 args
= Py_BuildValue("(O)", other
);
4269 res
= PyObject_Call(func
, args
, NULL
);
4273 if (res
!= Py_NotImplemented
) {
4276 c
= PyInt_AsLong(res
);
4278 if (c
== -1 && PyErr_Occurred())
4280 return (c
< 0) ? -1 : (c
> 0) ? 1 : 0;
4287 /* This slot is published for the benefit of try_3way_compare in object.c */
4289 _PyObject_SlotCompare(PyObject
*self
, PyObject
*other
)
4293 if (self
->ob_type
->tp_compare
== _PyObject_SlotCompare
) {
4294 c
= half_compare(self
, other
);
4298 if (other
->ob_type
->tp_compare
== _PyObject_SlotCompare
) {
4299 c
= half_compare(other
, self
);
4305 return (void *)self
< (void *)other
? -1 :
4306 (void *)self
> (void *)other
? 1 : 0;
4310 slot_tp_repr(PyObject
*self
)
4312 PyObject
*func
, *res
;
4313 static PyObject
*repr_str
;
4315 func
= lookup_method(self
, "__repr__", &repr_str
);
4317 res
= PyEval_CallObject(func
, NULL
);
4322 return PyString_FromFormat("<%s object at %p>",
4323 self
->ob_type
->tp_name
, self
);
4327 slot_tp_str(PyObject
*self
)
4329 PyObject
*func
, *res
;
4330 static PyObject
*str_str
;
4332 func
= lookup_method(self
, "__str__", &str_str
);
4334 res
= PyEval_CallObject(func
, NULL
);
4340 return slot_tp_repr(self
);
4345 slot_tp_hash(PyObject
*self
)
4348 static PyObject
*hash_str
, *eq_str
, *cmp_str
;
4351 func
= lookup_method(self
, "__hash__", &hash_str
);
4354 PyObject
*res
= PyEval_CallObject(func
, NULL
);
4358 h
= PyInt_AsLong(res
);
4363 func
= lookup_method(self
, "__eq__", &eq_str
);
4366 func
= lookup_method(self
, "__cmp__", &cmp_str
);
4370 PyErr_SetString(PyExc_TypeError
, "unhashable type");
4374 h
= _Py_HashPointer((void *)self
);
4376 if (h
== -1 && !PyErr_Occurred())
4382 slot_tp_call(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
4384 static PyObject
*call_str
;
4385 PyObject
*meth
= lookup_method(self
, "__call__", &call_str
);
4390 res
= PyObject_Call(meth
, args
, kwds
);
4395 /* There are two slot dispatch functions for tp_getattro.
4397 - slot_tp_getattro() is used when __getattribute__ is overridden
4398 but no __getattr__ hook is present;
4400 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4402 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4403 detects the absence of __getattr__ and then installs the simpler slot if
4407 slot_tp_getattro(PyObject
*self
, PyObject
*name
)
4409 static PyObject
*getattribute_str
= NULL
;
4410 return call_method(self
, "__getattribute__", &getattribute_str
,
4415 slot_tp_getattr_hook(PyObject
*self
, PyObject
*name
)
4417 PyTypeObject
*tp
= self
->ob_type
;
4418 PyObject
*getattr
, *getattribute
, *res
;
4419 static PyObject
*getattribute_str
= NULL
;
4420 static PyObject
*getattr_str
= NULL
;
4422 if (getattr_str
== NULL
) {
4423 getattr_str
= PyString_InternFromString("__getattr__");
4424 if (getattr_str
== NULL
)
4427 if (getattribute_str
== NULL
) {
4429 PyString_InternFromString("__getattribute__");
4430 if (getattribute_str
== NULL
)
4433 getattr
= _PyType_Lookup(tp
, getattr_str
);
4434 if (getattr
== NULL
) {
4435 /* No __getattr__ hook: use a simpler dispatcher */
4436 tp
->tp_getattro
= slot_tp_getattro
;
4437 return slot_tp_getattro(self
, name
);
4439 getattribute
= _PyType_Lookup(tp
, getattribute_str
);
4440 if (getattribute
== NULL
||
4441 (getattribute
->ob_type
== &PyWrapperDescr_Type
&&
4442 ((PyWrapperDescrObject
*)getattribute
)->d_wrapped
==
4443 (void *)PyObject_GenericGetAttr
))
4444 res
= PyObject_GenericGetAttr(self
, name
);
4446 res
= PyObject_CallFunction(getattribute
, "OO", self
, name
);
4447 if (res
== NULL
&& PyErr_ExceptionMatches(PyExc_AttributeError
)) {
4449 res
= PyObject_CallFunction(getattr
, "OO", self
, name
);
4455 slot_tp_setattro(PyObject
*self
, PyObject
*name
, PyObject
*value
)
4458 static PyObject
*delattr_str
, *setattr_str
;
4461 res
= call_method(self
, "__delattr__", &delattr_str
,
4464 res
= call_method(self
, "__setattr__", &setattr_str
,
4465 "(OO)", name
, value
);
4472 /* Map rich comparison operators to their __xx__ namesakes */
4473 static char *name_op
[] = {
4483 half_richcompare(PyObject
*self
, PyObject
*other
, int op
)
4485 PyObject
*func
, *args
, *res
;
4486 static PyObject
*op_str
[6];
4488 func
= lookup_method(self
, name_op
[op
], &op_str
[op
]);
4491 Py_INCREF(Py_NotImplemented
);
4492 return Py_NotImplemented
;
4494 args
= Py_BuildValue("(O)", other
);
4498 res
= PyObject_Call(func
, args
, NULL
);
4505 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4506 static int swapped_op
[] = {Py_GT
, Py_GE
, Py_EQ
, Py_NE
, Py_LT
, Py_LE
};
4509 slot_tp_richcompare(PyObject
*self
, PyObject
*other
, int op
)
4513 if (self
->ob_type
->tp_richcompare
== slot_tp_richcompare
) {
4514 res
= half_richcompare(self
, other
, op
);
4515 if (res
!= Py_NotImplemented
)
4519 if (other
->ob_type
->tp_richcompare
== slot_tp_richcompare
) {
4520 res
= half_richcompare(other
, self
, swapped_op
[op
]);
4521 if (res
!= Py_NotImplemented
) {
4526 Py_INCREF(Py_NotImplemented
);
4527 return Py_NotImplemented
;
4531 slot_tp_iter(PyObject
*self
)
4533 PyObject
*func
, *res
;
4534 static PyObject
*iter_str
, *getitem_str
;
4536 func
= lookup_method(self
, "__iter__", &iter_str
);
4539 args
= res
= PyTuple_New(0);
4541 res
= PyObject_Call(func
, args
, NULL
);
4548 func
= lookup_method(self
, "__getitem__", &getitem_str
);
4550 PyErr_SetString(PyExc_TypeError
,
4551 "iteration over non-sequence");
4555 return PySeqIter_New(self
);
4559 slot_tp_iternext(PyObject
*self
)
4561 static PyObject
*next_str
;
4562 return call_method(self
, "next", &next_str
, "()");
4566 slot_tp_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
4568 PyTypeObject
*tp
= self
->ob_type
;
4570 static PyObject
*get_str
= NULL
;
4572 if (get_str
== NULL
) {
4573 get_str
= PyString_InternFromString("__get__");
4574 if (get_str
== NULL
)
4577 get
= _PyType_Lookup(tp
, get_str
);
4579 /* Avoid further slowdowns */
4580 if (tp
->tp_descr_get
== slot_tp_descr_get
)
4581 tp
->tp_descr_get
= NULL
;
4589 return PyObject_CallFunction(get
, "OOO", self
, obj
, type
);
4593 slot_tp_descr_set(PyObject
*self
, PyObject
*target
, PyObject
*value
)
4596 static PyObject
*del_str
, *set_str
;
4599 res
= call_method(self
, "__delete__", &del_str
,
4602 res
= call_method(self
, "__set__", &set_str
,
4603 "(OO)", target
, value
);
4611 slot_tp_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
4613 static PyObject
*init_str
;
4614 PyObject
*meth
= lookup_method(self
, "__init__", &init_str
);
4619 res
= PyObject_Call(meth
, args
, kwds
);
4628 slot_tp_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
4630 static PyObject
*new_str
;
4632 PyObject
*newargs
, *x
;
4635 if (new_str
== NULL
) {
4636 new_str
= PyString_InternFromString("__new__");
4637 if (new_str
== NULL
)
4640 func
= PyObject_GetAttr((PyObject
*)type
, new_str
);
4643 assert(PyTuple_Check(args
));
4644 n
= PyTuple_GET_SIZE(args
);
4645 newargs
= PyTuple_New(n
+1);
4646 if (newargs
== NULL
)
4649 PyTuple_SET_ITEM(newargs
, 0, (PyObject
*)type
);
4650 for (i
= 0; i
< n
; i
++) {
4651 x
= PyTuple_GET_ITEM(args
, i
);
4653 PyTuple_SET_ITEM(newargs
, i
+1, x
);
4655 x
= PyObject_Call(func
, newargs
, kwds
);
4662 slot_tp_del(PyObject
*self
)
4664 static PyObject
*del_str
= NULL
;
4665 PyObject
*del
, *res
;
4666 PyObject
*error_type
, *error_value
, *error_traceback
;
4668 /* Temporarily resurrect the object. */
4669 assert(self
->ob_refcnt
== 0);
4670 self
->ob_refcnt
= 1;
4672 /* Save the current exception, if any. */
4673 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
4675 /* Execute __del__ method, if any. */
4676 del
= lookup_maybe(self
, "__del__", &del_str
);
4678 res
= PyEval_CallObject(del
, NULL
);
4680 PyErr_WriteUnraisable(del
);
4686 /* Restore the saved exception. */
4687 PyErr_Restore(error_type
, error_value
, error_traceback
);
4689 /* Undo the temporary resurrection; can't use DECREF here, it would
4690 * cause a recursive call.
4692 assert(self
->ob_refcnt
> 0);
4693 if (--self
->ob_refcnt
== 0)
4694 return; /* this is the normal path out */
4696 /* __del__ resurrected it! Make it look like the original Py_DECREF
4700 int refcnt
= self
->ob_refcnt
;
4701 _Py_NewReference(self
);
4702 self
->ob_refcnt
= refcnt
;
4704 assert(!PyType_IS_GC(self
->ob_type
) ||
4705 _Py_AS_GC(self
)->gc
.gc_refs
!= _PyGC_REFS_UNTRACKED
);
4706 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4707 * _Py_NewReference bumped it again, so that's a wash.
4708 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4709 * chain, so no more to do there either.
4710 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4711 * _Py_NewReference bumped tp_allocs: both of those need to be
4715 --self
->ob_type
->tp_frees
;
4716 --self
->ob_type
->tp_allocs
;
4721 /* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4722 functions. The offsets here are relative to the 'PyHeapTypeObject'
4723 structure, which incorporates the additional structures used for numbers,
4724 sequences and mappings.
4725 Note that multiple names may map to the same slot (e.g. __eq__,
4726 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
4727 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4728 terminated with an all-zero entry. (This table is further initialized and
4729 sorted in init_slotdefs() below.) */
4731 typedef struct wrapperbase slotdef
;
4744 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4745 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4747 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4748 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4749 PyDoc_STR(DOC), FLAGS}
4750 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4751 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4753 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4754 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4755 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4756 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4757 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4758 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4759 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4760 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4761 "x." NAME "() <==> " DOC)
4762 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4763 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4764 "x." NAME "(y) <==> x" DOC "y")
4765 #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4766 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4767 "x." NAME "(y) <==> x" DOC "y")
4768 #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4769 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4770 "x." NAME "(y) <==> y" DOC "x")
4772 static slotdef slotdefs
[] = {
4773 SQSLOT("__len__", sq_length
, slot_sq_length
, wrap_inquiry
,
4774 "x.__len__() <==> len(x)"),
4775 SQSLOT("__add__", sq_concat
, slot_sq_concat
, wrap_binaryfunc
,
4776 "x.__add__(y) <==> x+y"),
4777 SQSLOT("__mul__", sq_repeat
, slot_sq_repeat
, wrap_intargfunc
,
4778 "x.__mul__(n) <==> x*n"),
4779 SQSLOT("__rmul__", sq_repeat
, slot_sq_repeat
, wrap_intargfunc
,
4780 "x.__rmul__(n) <==> n*x"),
4781 SQSLOT("__getitem__", sq_item
, slot_sq_item
, wrap_sq_item
,
4782 "x.__getitem__(y) <==> x[y]"),
4783 SQSLOT("__getslice__", sq_slice
, slot_sq_slice
, wrap_intintargfunc
,
4784 "x.__getslice__(i, j) <==> x[i:j]"),
4785 SQSLOT("__setitem__", sq_ass_item
, slot_sq_ass_item
, wrap_sq_setitem
,
4786 "x.__setitem__(i, y) <==> x[i]=y"),
4787 SQSLOT("__delitem__", sq_ass_item
, slot_sq_ass_item
, wrap_sq_delitem
,
4788 "x.__delitem__(y) <==> del x[y]"),
4789 SQSLOT("__setslice__", sq_ass_slice
, slot_sq_ass_slice
,
4790 wrap_intintobjargproc
,
4791 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4792 SQSLOT("__delslice__", sq_ass_slice
, slot_sq_ass_slice
, wrap_delslice
,
4793 "x.__delslice__(i, j) <==> del x[i:j]"),
4794 SQSLOT("__contains__", sq_contains
, slot_sq_contains
, wrap_objobjproc
,
4795 "x.__contains__(y) <==> y in x"),
4796 SQSLOT("__iadd__", sq_inplace_concat
, slot_sq_inplace_concat
,
4797 wrap_binaryfunc
, "x.__iadd__(y) <==> x+=y"),
4798 SQSLOT("__imul__", sq_inplace_repeat
, slot_sq_inplace_repeat
,
4799 wrap_intargfunc
, "x.__imul__(y) <==> x*=y"),
4801 MPSLOT("__len__", mp_length
, slot_mp_length
, wrap_inquiry
,
4802 "x.__len__() <==> len(x)"),
4803 MPSLOT("__getitem__", mp_subscript
, slot_mp_subscript
,
4805 "x.__getitem__(y) <==> x[y]"),
4806 MPSLOT("__setitem__", mp_ass_subscript
, slot_mp_ass_subscript
,
4808 "x.__setitem__(i, y) <==> x[i]=y"),
4809 MPSLOT("__delitem__", mp_ass_subscript
, slot_mp_ass_subscript
,
4811 "x.__delitem__(y) <==> del x[y]"),
4813 BINSLOT("__add__", nb_add
, slot_nb_add
,
4815 RBINSLOT("__radd__", nb_add
, slot_nb_add
,
4817 BINSLOT("__sub__", nb_subtract
, slot_nb_subtract
,
4819 RBINSLOT("__rsub__", nb_subtract
, slot_nb_subtract
,
4821 BINSLOT("__mul__", nb_multiply
, slot_nb_multiply
,
4823 RBINSLOT("__rmul__", nb_multiply
, slot_nb_multiply
,
4825 BINSLOT("__div__", nb_divide
, slot_nb_divide
,
4827 RBINSLOT("__rdiv__", nb_divide
, slot_nb_divide
,
4829 BINSLOT("__mod__", nb_remainder
, slot_nb_remainder
,
4831 RBINSLOT("__rmod__", nb_remainder
, slot_nb_remainder
,
4833 BINSLOT("__divmod__", nb_divmod
, slot_nb_divmod
,
4835 RBINSLOT("__rdivmod__", nb_divmod
, slot_nb_divmod
,
4837 NBSLOT("__pow__", nb_power
, slot_nb_power
, wrap_ternaryfunc
,
4838 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4839 NBSLOT("__rpow__", nb_power
, slot_nb_power
, wrap_ternaryfunc_r
,
4840 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4841 UNSLOT("__neg__", nb_negative
, slot_nb_negative
, wrap_unaryfunc
, "-x"),
4842 UNSLOT("__pos__", nb_positive
, slot_nb_positive
, wrap_unaryfunc
, "+x"),
4843 UNSLOT("__abs__", nb_absolute
, slot_nb_absolute
, wrap_unaryfunc
,
4845 UNSLOT("__nonzero__", nb_nonzero
, slot_nb_nonzero
, wrap_inquiry
,
4847 UNSLOT("__invert__", nb_invert
, slot_nb_invert
, wrap_unaryfunc
, "~x"),
4848 BINSLOT("__lshift__", nb_lshift
, slot_nb_lshift
, "<<"),
4849 RBINSLOT("__rlshift__", nb_lshift
, slot_nb_lshift
, "<<"),
4850 BINSLOT("__rshift__", nb_rshift
, slot_nb_rshift
, ">>"),
4851 RBINSLOT("__rrshift__", nb_rshift
, slot_nb_rshift
, ">>"),
4852 BINSLOT("__and__", nb_and
, slot_nb_and
, "&"),
4853 RBINSLOT("__rand__", nb_and
, slot_nb_and
, "&"),
4854 BINSLOT("__xor__", nb_xor
, slot_nb_xor
, "^"),
4855 RBINSLOT("__rxor__", nb_xor
, slot_nb_xor
, "^"),
4856 BINSLOT("__or__", nb_or
, slot_nb_or
, "|"),
4857 RBINSLOT("__ror__", nb_or
, slot_nb_or
, "|"),
4858 NBSLOT("__coerce__", nb_coerce
, slot_nb_coerce
, wrap_coercefunc
,
4859 "x.__coerce__(y) <==> coerce(x, y)"),
4860 UNSLOT("__int__", nb_int
, slot_nb_int
, wrap_unaryfunc
,
4862 UNSLOT("__long__", nb_long
, slot_nb_long
, wrap_unaryfunc
,
4864 UNSLOT("__float__", nb_float
, slot_nb_float
, wrap_unaryfunc
,
4866 UNSLOT("__oct__", nb_oct
, slot_nb_oct
, wrap_unaryfunc
,
4868 UNSLOT("__hex__", nb_hex
, slot_nb_hex
, wrap_unaryfunc
,
4870 IBSLOT("__iadd__", nb_inplace_add
, slot_nb_inplace_add
,
4871 wrap_binaryfunc
, "+"),
4872 IBSLOT("__isub__", nb_inplace_subtract
, slot_nb_inplace_subtract
,
4873 wrap_binaryfunc
, "-"),
4874 IBSLOT("__imul__", nb_inplace_multiply
, slot_nb_inplace_multiply
,
4875 wrap_binaryfunc
, "*"),
4876 IBSLOT("__idiv__", nb_inplace_divide
, slot_nb_inplace_divide
,
4877 wrap_binaryfunc
, "/"),
4878 IBSLOT("__imod__", nb_inplace_remainder
, slot_nb_inplace_remainder
,
4879 wrap_binaryfunc
, "%"),
4880 IBSLOT("__ipow__", nb_inplace_power
, slot_nb_inplace_power
,
4881 wrap_binaryfunc
, "**"),
4882 IBSLOT("__ilshift__", nb_inplace_lshift
, slot_nb_inplace_lshift
,
4883 wrap_binaryfunc
, "<<"),
4884 IBSLOT("__irshift__", nb_inplace_rshift
, slot_nb_inplace_rshift
,
4885 wrap_binaryfunc
, ">>"),
4886 IBSLOT("__iand__", nb_inplace_and
, slot_nb_inplace_and
,
4887 wrap_binaryfunc
, "&"),
4888 IBSLOT("__ixor__", nb_inplace_xor
, slot_nb_inplace_xor
,
4889 wrap_binaryfunc
, "^"),
4890 IBSLOT("__ior__", nb_inplace_or
, slot_nb_inplace_or
,
4891 wrap_binaryfunc
, "|"),
4892 BINSLOT("__floordiv__", nb_floor_divide
, slot_nb_floor_divide
, "//"),
4893 RBINSLOT("__rfloordiv__", nb_floor_divide
, slot_nb_floor_divide
, "//"),
4894 BINSLOT("__truediv__", nb_true_divide
, slot_nb_true_divide
, "/"),
4895 RBINSLOT("__rtruediv__", nb_true_divide
, slot_nb_true_divide
, "/"),
4896 IBSLOT("__ifloordiv__", nb_inplace_floor_divide
,
4897 slot_nb_inplace_floor_divide
, wrap_binaryfunc
, "//"),
4898 IBSLOT("__itruediv__", nb_inplace_true_divide
,
4899 slot_nb_inplace_true_divide
, wrap_binaryfunc
, "/"),
4901 TPSLOT("__str__", tp_str
, slot_tp_str
, wrap_unaryfunc
,
4902 "x.__str__() <==> str(x)"),
4903 TPSLOT("__str__", tp_print
, NULL
, NULL
, ""),
4904 TPSLOT("__repr__", tp_repr
, slot_tp_repr
, wrap_unaryfunc
,
4905 "x.__repr__() <==> repr(x)"),
4906 TPSLOT("__repr__", tp_print
, NULL
, NULL
, ""),
4907 TPSLOT("__cmp__", tp_compare
, _PyObject_SlotCompare
, wrap_cmpfunc
,
4908 "x.__cmp__(y) <==> cmp(x,y)"),
4909 TPSLOT("__hash__", tp_hash
, slot_tp_hash
, wrap_hashfunc
,
4910 "x.__hash__() <==> hash(x)"),
4911 FLSLOT("__call__", tp_call
, slot_tp_call
, (wrapperfunc
)wrap_call
,
4912 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS
),
4913 TPSLOT("__getattribute__", tp_getattro
, slot_tp_getattr_hook
,
4914 wrap_binaryfunc
, "x.__getattribute__('name') <==> x.name"),
4915 TPSLOT("__getattribute__", tp_getattr
, NULL
, NULL
, ""),
4916 TPSLOT("__getattr__", tp_getattro
, slot_tp_getattr_hook
, NULL
, ""),
4917 TPSLOT("__getattr__", tp_getattr
, NULL
, NULL
, ""),
4918 TPSLOT("__setattr__", tp_setattro
, slot_tp_setattro
, wrap_setattr
,
4919 "x.__setattr__('name', value) <==> x.name = value"),
4920 TPSLOT("__setattr__", tp_setattr
, NULL
, NULL
, ""),
4921 TPSLOT("__delattr__", tp_setattro
, slot_tp_setattro
, wrap_delattr
,
4922 "x.__delattr__('name') <==> del x.name"),
4923 TPSLOT("__delattr__", tp_setattr
, NULL
, NULL
, ""),
4924 TPSLOT("__lt__", tp_richcompare
, slot_tp_richcompare
, richcmp_lt
,
4925 "x.__lt__(y) <==> x<y"),
4926 TPSLOT("__le__", tp_richcompare
, slot_tp_richcompare
, richcmp_le
,
4927 "x.__le__(y) <==> x<=y"),
4928 TPSLOT("__eq__", tp_richcompare
, slot_tp_richcompare
, richcmp_eq
,
4929 "x.__eq__(y) <==> x==y"),
4930 TPSLOT("__ne__", tp_richcompare
, slot_tp_richcompare
, richcmp_ne
,
4931 "x.__ne__(y) <==> x!=y"),
4932 TPSLOT("__gt__", tp_richcompare
, slot_tp_richcompare
, richcmp_gt
,
4933 "x.__gt__(y) <==> x>y"),
4934 TPSLOT("__ge__", tp_richcompare
, slot_tp_richcompare
, richcmp_ge
,
4935 "x.__ge__(y) <==> x>=y"),
4936 TPSLOT("__iter__", tp_iter
, slot_tp_iter
, wrap_unaryfunc
,
4937 "x.__iter__() <==> iter(x)"),
4938 TPSLOT("next", tp_iternext
, slot_tp_iternext
, wrap_next
,
4939 "x.next() -> the next value, or raise StopIteration"),
4940 TPSLOT("__get__", tp_descr_get
, slot_tp_descr_get
, wrap_descr_get
,
4941 "descr.__get__(obj[, type]) -> value"),
4942 TPSLOT("__set__", tp_descr_set
, slot_tp_descr_set
, wrap_descr_set
,
4943 "descr.__set__(obj, value)"),
4944 TPSLOT("__delete__", tp_descr_set
, slot_tp_descr_set
,
4945 wrap_descr_delete
, "descr.__delete__(obj)"),
4946 FLSLOT("__init__", tp_init
, slot_tp_init
, (wrapperfunc
)wrap_init
,
4947 "x.__init__(...) initializes x; "
4948 "see x.__class__.__doc__ for signature",
4949 PyWrapperFlag_KEYWORDS
),
4950 TPSLOT("__new__", tp_new
, slot_tp_new
, NULL
, ""),
4951 TPSLOT("__del__", tp_del
, slot_tp_del
, NULL
, ""),
4955 /* Given a type pointer and an offset gotten from a slotdef entry, return a
4956 pointer to the actual slot. This is not quite the same as simply adding
4957 the offset to the type pointer, since it takes care to indirect through the
4958 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4959 indirection pointer is NULL. */
4961 slotptr(PyTypeObject
*type
, int offset
)
4965 /* Note: this depends on the order of the members of PyHeapTypeObject! */
4966 assert(offset
>= 0);
4967 assert(offset
< offsetof(PyHeapTypeObject
, as_buffer
));
4968 if (offset
>= offsetof(PyHeapTypeObject
, as_sequence
)) {
4969 ptr
= (void *)type
->tp_as_sequence
;
4970 offset
-= offsetof(PyHeapTypeObject
, as_sequence
);
4972 else if (offset
>= offsetof(PyHeapTypeObject
, as_mapping
)) {
4973 ptr
= (void *)type
->tp_as_mapping
;
4974 offset
-= offsetof(PyHeapTypeObject
, as_mapping
);
4976 else if (offset
>= offsetof(PyHeapTypeObject
, as_number
)) {
4977 ptr
= (void *)type
->tp_as_number
;
4978 offset
-= offsetof(PyHeapTypeObject
, as_number
);
4985 return (void **)ptr
;
4988 /* Length of array of slotdef pointers used to store slots with the
4989 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4990 the same __name__, for any __name__. Since that's a static property, it is
4991 appropriate to declare fixed-size arrays for this. */
4992 #define MAX_EQUIV 10
4994 /* Return a slot pointer for a given name, but ONLY if the attribute has
4995 exactly one slot function. The name must be an interned string. */
4997 resolve_slotdups(PyTypeObject
*type
, PyObject
*name
)
4999 /* XXX Maybe this could be optimized more -- but is it worth it? */
5001 /* pname and ptrs act as a little cache */
5002 static PyObject
*pname
;
5003 static slotdef
*ptrs
[MAX_EQUIV
];
5007 if (pname
!= name
) {
5008 /* Collect all slotdefs that match name into ptrs. */
5011 for (p
= slotdefs
; p
->name_strobj
; p
++) {
5012 if (p
->name_strobj
== name
)
5018 /* Look in all matching slots of the type; if exactly one of these has
5019 a filled-in slot, return its value. Otherwise return NULL. */
5021 for (pp
= ptrs
; *pp
; pp
++) {
5022 ptr
= slotptr(type
, (*pp
)->offset
);
5023 if (ptr
== NULL
|| *ptr
== NULL
)
5032 /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
5033 does some incredibly complex thinking and then sticks something into the
5034 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5035 interests, and then stores a generic wrapper or a specific function into
5036 the slot.) Return a pointer to the next slotdef with a different offset,
5037 because that's convenient for fixup_slot_dispatchers(). */
5039 update_one_slot(PyTypeObject
*type
, slotdef
*p
)
5042 PyWrapperDescrObject
*d
;
5043 void *generic
= NULL
, *specific
= NULL
;
5044 int use_generic
= 0;
5045 int offset
= p
->offset
;
5046 void **ptr
= slotptr(type
, offset
);
5051 } while (p
->offset
== offset
);
5055 descr
= _PyType_Lookup(type
, p
->name_strobj
);
5058 if (descr
->ob_type
== &PyWrapperDescr_Type
) {
5059 void **tptr
= resolve_slotdups(type
, p
->name_strobj
);
5060 if (tptr
== NULL
|| tptr
== ptr
)
5061 generic
= p
->function
;
5062 d
= (PyWrapperDescrObject
*)descr
;
5063 if (d
->d_base
->wrapper
== p
->wrapper
&&
5064 PyType_IsSubtype(type
, d
->d_type
))
5066 if (specific
== NULL
||
5067 specific
== d
->d_wrapped
)
5068 specific
= d
->d_wrapped
;
5073 else if (descr
->ob_type
== &PyCFunction_Type
&&
5074 PyCFunction_GET_FUNCTION(descr
) ==
5075 (PyCFunction
)tp_new_wrapper
&&
5076 strcmp(p
->name
, "__new__") == 0)
5078 /* The __new__ wrapper is not a wrapper descriptor,
5079 so must be special-cased differently.
5080 If we don't do this, creating an instance will
5081 always use slot_tp_new which will look up
5082 __new__ in the MRO which will call tp_new_wrapper
5083 which will look through the base classes looking
5084 for a static base and call its tp_new (usually
5085 PyType_GenericNew), after performing various
5086 sanity checks and constructing a new argument
5087 list. Cut all that nonsense short -- this speeds
5088 up instance creation tremendously. */
5089 specific
= type
->tp_new
;
5090 /* XXX I'm not 100% sure that there isn't a hole
5091 in this reasoning that requires additional
5092 sanity checks. I'll buy the first person to
5093 point out a bug in this reasoning a beer. */
5097 generic
= p
->function
;
5099 } while ((++p
)->offset
== offset
);
5100 if (specific
&& !use_generic
)
5107 /* In the type, update the slots whose slotdefs are gathered in the pp array.
5108 This is a callback for update_subclasses(). */
5110 update_slots_callback(PyTypeObject
*type
, void *data
)
5112 slotdef
**pp
= (slotdef
**)data
;
5115 update_one_slot(type
, *pp
);
5119 /* Comparison function for qsort() to compare slotdefs by their offset, and
5120 for equal offset by their address (to force a stable sort). */
5122 slotdef_cmp(const void *aa
, const void *bb
)
5124 const slotdef
*a
= (const slotdef
*)aa
, *b
= (const slotdef
*)bb
;
5125 int c
= a
->offset
- b
->offset
;
5132 /* Initialize the slotdefs table by adding interned string objects for the
5133 names and sorting the entries. */
5138 static int initialized
= 0;
5142 for (p
= slotdefs
; p
->name
; p
++) {
5143 p
->name_strobj
= PyString_InternFromString(p
->name
);
5144 if (!p
->name_strobj
)
5145 Py_FatalError("Out of memory interning slotdef names");
5147 qsort((void *)slotdefs
, (size_t)(p
-slotdefs
), sizeof(slotdef
),
5152 /* Update the slots after assignment to a class (type) attribute. */
5154 update_slot(PyTypeObject
*type
, PyObject
*name
)
5156 slotdef
*ptrs
[MAX_EQUIV
];
5163 for (p
= slotdefs
; p
->name
; p
++) {
5164 /* XXX assume name is interned! */
5165 if (p
->name_strobj
== name
)
5169 for (pp
= ptrs
; *pp
; pp
++) {
5172 while (p
> slotdefs
&& (p
-1)->offset
== offset
)
5176 if (ptrs
[0] == NULL
)
5177 return 0; /* Not an attribute that affects any slots */
5178 return update_subclasses(type
, name
,
5179 update_slots_callback
, (void *)ptrs
);
5182 /* Store the proper functions in the slot dispatches at class (type)
5183 definition time, based upon which operations the class overrides in its
5186 fixup_slot_dispatchers(PyTypeObject
*type
)
5191 for (p
= slotdefs
; p
->name
; )
5192 p
= update_one_slot(type
, p
);
5196 update_all_slots(PyTypeObject
* type
)
5201 for (p
= slotdefs
; p
->name
; p
++) {
5202 /* update_slot returns int but can't actually fail */
5203 update_slot(type
, p
->name_strobj
);
5207 /* recurse_down_subclasses() and update_subclasses() are mutually
5208 recursive functions to call a callback for all subclasses,
5209 but refraining from recursing into subclasses that define 'name'. */
5212 update_subclasses(PyTypeObject
*type
, PyObject
*name
,
5213 update_callback callback
, void *data
)
5215 if (callback(type
, data
) < 0)
5217 return recurse_down_subclasses(type
, name
, callback
, data
);
5221 recurse_down_subclasses(PyTypeObject
*type
, PyObject
*name
,
5222 update_callback callback
, void *data
)
5224 PyTypeObject
*subclass
;
5225 PyObject
*ref
, *subclasses
, *dict
;
5228 subclasses
= type
->tp_subclasses
;
5229 if (subclasses
== NULL
)
5231 assert(PyList_Check(subclasses
));
5232 n
= PyList_GET_SIZE(subclasses
);
5233 for (i
= 0; i
< n
; i
++) {
5234 ref
= PyList_GET_ITEM(subclasses
, i
);
5235 assert(PyWeakref_CheckRef(ref
));
5236 subclass
= (PyTypeObject
*)PyWeakref_GET_OBJECT(ref
);
5237 assert(subclass
!= NULL
);
5238 if ((PyObject
*)subclass
== Py_None
)
5240 assert(PyType_Check(subclass
));
5241 /* Avoid recursing down into unaffected classes */
5242 dict
= subclass
->tp_dict
;
5243 if (dict
!= NULL
&& PyDict_Check(dict
) &&
5244 PyDict_GetItem(dict
, name
) != NULL
)
5246 if (update_subclasses(subclass
, name
, callback
, data
) < 0)
5252 /* This function is called by PyType_Ready() to populate the type's
5253 dictionary with method descriptors for function slots. For each
5254 function slot (like tp_repr) that's defined in the type, one or more
5255 corresponding descriptors are added in the type's tp_dict dictionary
5256 under the appropriate name (like __repr__). Some function slots
5257 cause more than one descriptor to be added (for example, the nb_add
5258 slot adds both __add__ and __radd__ descriptors) and some function
5259 slots compete for the same descriptor (for example both sq_item and
5260 mp_subscript generate a __getitem__ descriptor).
5262 In the latter case, the first slotdef entry encoutered wins. Since
5263 slotdef entries are sorted by the offset of the slot in the
5264 PyHeapTypeObject, this gives us some control over disambiguating
5265 between competing slots: the members of PyHeapTypeObject are listed
5266 from most general to least general, so the most general slot is
5267 preferred. In particular, because as_mapping comes before as_sequence,
5268 for a type that defines both mp_subscript and sq_item, mp_subscript
5271 This only adds new descriptors and doesn't overwrite entries in
5272 tp_dict that were previously defined. The descriptors contain a
5273 reference to the C function they must call, so that it's safe if they
5274 are copied into a subtype's __dict__ and the subtype has a different
5275 C function in its slot -- calling the method defined by the
5276 descriptor will call the C function that was used to create it,
5277 rather than the C function present in the slot when it is called.
5278 (This is important because a subtype may have a C function in the
5279 slot that calls the method from the dictionary, and we want to avoid
5280 infinite recursion here.) */
5283 add_operators(PyTypeObject
*type
)
5285 PyObject
*dict
= type
->tp_dict
;
5291 for (p
= slotdefs
; p
->name
; p
++) {
5292 if (p
->wrapper
== NULL
)
5294 ptr
= slotptr(type
, p
->offset
);
5297 if (PyDict_GetItem(dict
, p
->name_strobj
))
5299 descr
= PyDescr_NewWrapper(type
, p
, *ptr
);
5302 if (PyDict_SetItem(dict
, p
->name_strobj
, descr
) < 0)
5306 if (type
->tp_new
!= NULL
) {
5307 if (add_tp_new_wrapper(type
) < 0)
5314 /* Cooperative 'super' */
5320 PyTypeObject
*obj_type
;
5323 static PyMemberDef super_members
[] = {
5324 {"__thisclass__", T_OBJECT
, offsetof(superobject
, type
), READONLY
,
5325 "the class invoking super()"},
5326 {"__self__", T_OBJECT
, offsetof(superobject
, obj
), READONLY
,
5327 "the instance invoking super(); may be None"},
5328 {"__self_class__", T_OBJECT
, offsetof(superobject
, obj_type
), READONLY
,
5329 "the type of the the instance invoking super(); may be None"},
5334 super_dealloc(PyObject
*self
)
5336 superobject
*su
= (superobject
*)self
;
5338 _PyObject_GC_UNTRACK(self
);
5339 Py_XDECREF(su
->obj
);
5340 Py_XDECREF(su
->type
);
5341 Py_XDECREF(su
->obj_type
);
5342 self
->ob_type
->tp_free(self
);
5346 super_repr(PyObject
*self
)
5348 superobject
*su
= (superobject
*)self
;
5351 return PyString_FromFormat(
5352 "<super: <class '%s'>, <%s object>>",
5353 su
->type
? su
->type
->tp_name
: "NULL",
5354 su
->obj_type
->tp_name
);
5356 return PyString_FromFormat(
5357 "<super: <class '%s'>, NULL>",
5358 su
->type
? su
->type
->tp_name
: "NULL");
5362 super_getattro(PyObject
*self
, PyObject
*name
)
5364 superobject
*su
= (superobject
*)self
;
5365 int skip
= su
->obj_type
== NULL
;
5368 /* We want __class__ to return the class of the super object
5369 (i.e. super, or a subclass), not the class of su->obj. */
5370 skip
= (PyString_Check(name
) &&
5371 PyString_GET_SIZE(name
) == 9 &&
5372 strcmp(PyString_AS_STRING(name
), "__class__") == 0);
5376 PyObject
*mro
, *res
, *tmp
, *dict
;
5377 PyTypeObject
*starttype
;
5381 starttype
= su
->obj_type
;
5382 mro
= starttype
->tp_mro
;
5387 assert(PyTuple_Check(mro
));
5388 n
= PyTuple_GET_SIZE(mro
);
5390 for (i
= 0; i
< n
; i
++) {
5391 if ((PyObject
*)(su
->type
) == PyTuple_GET_ITEM(mro
, i
))
5396 for (; i
< n
; i
++) {
5397 tmp
= PyTuple_GET_ITEM(mro
, i
);
5398 if (PyType_Check(tmp
))
5399 dict
= ((PyTypeObject
*)tmp
)->tp_dict
;
5400 else if (PyClass_Check(tmp
))
5401 dict
= ((PyClassObject
*)tmp
)->cl_dict
;
5404 res
= PyDict_GetItem(dict
, name
);
5407 f
= res
->ob_type
->tp_descr_get
;
5409 tmp
= f(res
, su
->obj
,
5410 (PyObject
*)starttype
);
5418 return PyObject_GenericGetAttr(self
, name
);
5421 static PyTypeObject
*
5422 supercheck(PyTypeObject
*type
, PyObject
*obj
)
5424 /* Check that a super() call makes sense. Return a type object.
5426 obj can be a new-style class, or an instance of one:
5428 - If it is a class, it must be a subclass of 'type'. This case is
5429 used for class methods; the return value is obj.
5431 - If it is an instance, it must be an instance of 'type'. This is
5432 the normal case; the return value is obj.__class__.
5434 But... when obj is an instance, we want to allow for the case where
5435 obj->ob_type is not a subclass of type, but obj.__class__ is!
5436 This will allow using super() with a proxy for obj.
5439 /* Check for first bullet above (special case) */
5440 if (PyType_Check(obj
) && PyType_IsSubtype((PyTypeObject
*)obj
, type
)) {
5442 return (PyTypeObject
*)obj
;
5446 if (PyType_IsSubtype(obj
->ob_type
, type
)) {
5447 Py_INCREF(obj
->ob_type
);
5448 return obj
->ob_type
;
5451 /* Try the slow way */
5452 static PyObject
*class_str
= NULL
;
5453 PyObject
*class_attr
;
5455 if (class_str
== NULL
) {
5456 class_str
= PyString_FromString("__class__");
5457 if (class_str
== NULL
)
5461 class_attr
= PyObject_GetAttr(obj
, class_str
);
5463 if (class_attr
!= NULL
&&
5464 PyType_Check(class_attr
) &&
5465 (PyTypeObject
*)class_attr
!= obj
->ob_type
)
5467 int ok
= PyType_IsSubtype(
5468 (PyTypeObject
*)class_attr
, type
);
5470 return (PyTypeObject
*)class_attr
;
5473 if (class_attr
== NULL
)
5476 Py_DECREF(class_attr
);
5479 PyErr_SetString(PyExc_TypeError
,
5480 "super(type, obj): "
5481 "obj must be an instance or subtype of type");
5486 super_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
5488 superobject
*su
= (superobject
*)self
;
5491 if (obj
== NULL
|| obj
== Py_None
|| su
->obj
!= NULL
) {
5492 /* Not binding to an object, or already bound */
5496 if (su
->ob_type
!= &PySuper_Type
)
5497 /* If su is an instance of a subclass of super,
5499 return PyObject_CallFunction((PyObject
*)su
->ob_type
,
5500 "OO", su
->type
, obj
);
5502 /* Inline the common case */
5503 PyTypeObject
*obj_type
= supercheck(su
->type
, obj
);
5504 if (obj_type
== NULL
)
5506 new = (superobject
*)PySuper_Type
.tp_new(&PySuper_Type
,
5510 Py_INCREF(su
->type
);
5512 new->type
= su
->type
;
5514 new->obj_type
= obj_type
;
5515 return (PyObject
*)new;
5520 super_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5522 superobject
*su
= (superobject
*)self
;
5524 PyObject
*obj
= NULL
;
5525 PyTypeObject
*obj_type
= NULL
;
5527 if (!PyArg_ParseTuple(args
, "O!|O:super", &PyType_Type
, &type
, &obj
))
5532 obj_type
= supercheck(type
, obj
);
5533 if (obj_type
== NULL
)
5540 su
->obj_type
= obj_type
;
5544 PyDoc_STRVAR(super_doc
,
5545 "super(type) -> unbound super object\n"
5546 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
5547 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
5548 "Typical use to call a cooperative superclass method:\n"
5550 " def meth(self, arg):\n"
5551 " super(C, self).meth(arg)");
5554 super_traverse(PyObject
*self
, visitproc visit
, void *arg
)
5556 superobject
*su
= (superobject
*)self
;
5559 #define VISIT(SLOT) \
5561 err = visit((PyObject *)(SLOT), arg); \
5568 VISIT(su
->obj_type
);
5575 PyTypeObject PySuper_Type
= {
5576 PyObject_HEAD_INIT(&PyType_Type
)
5578 "super", /* tp_name */
5579 sizeof(superobject
), /* tp_basicsize */
5580 0, /* tp_itemsize */
5582 super_dealloc
, /* tp_dealloc */
5587 super_repr
, /* tp_repr */
5588 0, /* tp_as_number */
5589 0, /* tp_as_sequence */
5590 0, /* tp_as_mapping */
5594 super_getattro
, /* tp_getattro */
5595 0, /* tp_setattro */
5596 0, /* tp_as_buffer */
5597 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
5598 Py_TPFLAGS_BASETYPE
, /* tp_flags */
5599 super_doc
, /* tp_doc */
5600 super_traverse
, /* tp_traverse */
5602 0, /* tp_richcompare */
5603 0, /* tp_weaklistoffset */
5605 0, /* tp_iternext */
5607 super_members
, /* tp_members */
5611 super_descr_get
, /* tp_descr_get */
5612 0, /* tp_descr_set */
5613 0, /* tp_dictoffset */
5614 super_init
, /* tp_init */
5615 PyType_GenericAlloc
, /* tp_alloc */
5616 PyType_GenericNew
, /* tp_new */
5617 PyObject_GC_Del
, /* tp_free */