1 /* Type object implementation */
4 #include "structmember.h"
9 /* Support type attribute cache */
11 /* The cache can keep references to the names alive for longer than
12 they normally would. This is why the maximum size is limited to
13 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
14 strings are used as attribute names. */
15 #define MCACHE_MAX_ATTR_SIZE 100
16 #define MCACHE_SIZE_EXP 10
17 #define MCACHE_HASH(version, name_hash) \
18 (((unsigned int)(version) * (unsigned int)(name_hash)) \
19 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
20 #define MCACHE_HASH_METHOD(type, name) \
21 MCACHE_HASH((type)->tp_version_tag, \
22 ((PyStringObject *)(name))->ob_shash)
23 #define MCACHE_CACHEABLE_NAME(name) \
24 PyString_CheckExact(name) && \
25 PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
27 struct method_cache_entry
{
29 PyObject
*name
; /* reference to exactly a str or None */
30 PyObject
*value
; /* borrowed */
33 static struct method_cache_entry method_cache
[1 << MCACHE_SIZE_EXP
];
34 static unsigned int next_version_tag
= 0;
37 PyType_ClearCache(void)
40 unsigned int cur_version_tag
= next_version_tag
- 1;
42 for (i
= 0; i
< (1 << MCACHE_SIZE_EXP
); i
++) {
43 method_cache
[i
].version
= 0;
44 Py_CLEAR(method_cache
[i
].name
);
45 method_cache
[i
].value
= NULL
;
48 /* mark all version tags as invalid */
49 PyType_Modified(&PyBaseObject_Type
);
50 return cur_version_tag
;
54 PyType_Modified(PyTypeObject
*type
)
56 /* Invalidate any cached data for the specified type and all
57 subclasses. This function is called after the base
58 classes, mro, or attributes of the type are altered.
62 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
63 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
64 objects coming from non-recompiled extension modules)
66 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
67 it must first be set on all super types.
69 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
70 type (so it must first clear it on all subclasses). The
71 tp_version_tag value is meaningless unless this flag is set.
72 We don't assign new version tags eagerly, but only as
78 if (!PyType_HasFeature(type
, Py_TPFLAGS_VALID_VERSION_TAG
))
81 raw
= type
->tp_subclasses
;
83 n
= PyList_GET_SIZE(raw
);
84 for (i
= 0; i
< n
; i
++) {
85 ref
= PyList_GET_ITEM(raw
, i
);
86 ref
= PyWeakref_GET_OBJECT(ref
);
88 PyType_Modified((PyTypeObject
*)ref
);
92 type
->tp_flags
&= ~Py_TPFLAGS_VALID_VERSION_TAG
;
96 type_mro_modified(PyTypeObject
*type
, PyObject
*bases
) {
98 Check that all base classes or elements of the mro of type are
99 able to be cached. This function is called after the base
100 classes or mro of the type are altered.
102 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
103 inherits from an old-style class, either directly or if it
104 appears in the MRO of a new-style class. No support either for
105 custom MROs that include types that are not officially super
108 Called from mro_internal, which will subsequently be called on
109 each subclass when their mro is recursively updated.
114 if (!PyType_HasFeature(type
, Py_TPFLAGS_HAVE_VERSION_TAG
))
117 n
= PyTuple_GET_SIZE(bases
);
118 for (i
= 0; i
< n
; i
++) {
119 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
122 if (!PyType_Check(b
) ) {
127 cls
= (PyTypeObject
*)b
;
129 if (!PyType_HasFeature(cls
, Py_TPFLAGS_HAVE_VERSION_TAG
) ||
130 !PyType_IsSubtype(type
, cls
)) {
137 type
->tp_flags
&= ~(Py_TPFLAGS_HAVE_VERSION_TAG
|
138 Py_TPFLAGS_VALID_VERSION_TAG
);
142 assign_version_tag(PyTypeObject
*type
)
144 /* Ensure that the tp_version_tag is valid and set
145 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
146 must first be done on all super classes. Return 0 if this
147 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
152 if (PyType_HasFeature(type
, Py_TPFLAGS_VALID_VERSION_TAG
))
154 if (!PyType_HasFeature(type
, Py_TPFLAGS_HAVE_VERSION_TAG
))
156 if (!PyType_HasFeature(type
, Py_TPFLAGS_READY
))
159 type
->tp_version_tag
= next_version_tag
++;
160 /* for stress-testing: next_version_tag &= 0xFF; */
162 if (type
->tp_version_tag
== 0) {
163 /* wrap-around or just starting Python - clear the whole
164 cache by filling names with references to Py_None.
165 Values are also set to NULL for added protection, as they
166 are borrowed reference */
167 for (i
= 0; i
< (1 << MCACHE_SIZE_EXP
); i
++) {
168 method_cache
[i
].value
= NULL
;
169 Py_XDECREF(method_cache
[i
].name
);
170 method_cache
[i
].name
= Py_None
;
173 /* mark all version tags as invalid */
174 PyType_Modified(&PyBaseObject_Type
);
177 bases
= type
->tp_bases
;
178 n
= PyTuple_GET_SIZE(bases
);
179 for (i
= 0; i
< n
; i
++) {
180 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
181 assert(PyType_Check(b
));
182 if (!assign_version_tag((PyTypeObject
*)b
))
185 type
->tp_flags
|= Py_TPFLAGS_VALID_VERSION_TAG
;
190 static PyMemberDef type_members
[] = {
191 {"__basicsize__", T_INT
, offsetof(PyTypeObject
,tp_basicsize
),READONLY
},
192 {"__itemsize__", T_INT
, offsetof(PyTypeObject
, tp_itemsize
), READONLY
},
193 {"__flags__", T_LONG
, offsetof(PyTypeObject
, tp_flags
), READONLY
},
194 {"__weakrefoffset__", T_LONG
,
195 offsetof(PyTypeObject
, tp_weaklistoffset
), READONLY
},
196 {"__base__", T_OBJECT
, offsetof(PyTypeObject
, tp_base
), READONLY
},
197 {"__dictoffset__", T_LONG
,
198 offsetof(PyTypeObject
, tp_dictoffset
), READONLY
},
199 {"__mro__", T_OBJECT
, offsetof(PyTypeObject
, tp_mro
), READONLY
},
204 type_name(PyTypeObject
*type
, void *context
)
208 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
209 PyHeapTypeObject
* et
= (PyHeapTypeObject
*)type
;
211 Py_INCREF(et
->ht_name
);
215 s
= strrchr(type
->tp_name
, '.');
220 return PyString_FromString(s
);
225 type_set_name(PyTypeObject
*type
, PyObject
*value
, void *context
)
227 PyHeapTypeObject
* et
;
229 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
230 PyErr_Format(PyExc_TypeError
,
231 "can't set %s.__name__", type
->tp_name
);
235 PyErr_Format(PyExc_TypeError
,
236 "can't delete %s.__name__", type
->tp_name
);
239 if (!PyString_Check(value
)) {
240 PyErr_Format(PyExc_TypeError
,
241 "can only assign string to %s.__name__, not '%s'",
242 type
->tp_name
, Py_TYPE(value
)->tp_name
);
245 if (strlen(PyString_AS_STRING(value
))
246 != (size_t)PyString_GET_SIZE(value
)) {
247 PyErr_Format(PyExc_ValueError
,
248 "__name__ must not contain null bytes");
252 et
= (PyHeapTypeObject
*)type
;
256 Py_DECREF(et
->ht_name
);
259 type
->tp_name
= PyString_AS_STRING(value
);
265 type_module(PyTypeObject
*type
, void *context
)
270 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
271 mod
= PyDict_GetItemString(type
->tp_dict
, "__module__");
273 PyErr_Format(PyExc_AttributeError
, "__module__");
280 s
= strrchr(type
->tp_name
, '.');
282 return PyString_FromStringAndSize(
283 type
->tp_name
, (Py_ssize_t
)(s
- type
->tp_name
));
284 return PyString_FromString("__builtin__");
289 type_set_module(PyTypeObject
*type
, PyObject
*value
, void *context
)
291 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
292 PyErr_Format(PyExc_TypeError
,
293 "can't set %s.__module__", type
->tp_name
);
297 PyErr_Format(PyExc_TypeError
,
298 "can't delete %s.__module__", type
->tp_name
);
302 PyType_Modified(type
);
304 return PyDict_SetItemString(type
->tp_dict
, "__module__", value
);
308 type_abstractmethods(PyTypeObject
*type
, void *context
)
310 PyObject
*mod
= PyDict_GetItemString(type
->tp_dict
,
311 "__abstractmethods__");
313 PyErr_Format(PyExc_AttributeError
, "__abstractmethods__");
321 type_set_abstractmethods(PyTypeObject
*type
, PyObject
*value
, void *context
)
323 /* __abstractmethods__ should only be set once on a type, in
324 abc.ABCMeta.__new__, so this function doesn't do anything
325 special to update subclasses.
327 int res
= PyDict_SetItemString(type
->tp_dict
,
328 "__abstractmethods__", value
);
330 PyType_Modified(type
);
331 if (value
&& PyObject_IsTrue(value
)) {
332 type
->tp_flags
|= Py_TPFLAGS_IS_ABSTRACT
;
335 type
->tp_flags
&= ~Py_TPFLAGS_IS_ABSTRACT
;
342 type_get_bases(PyTypeObject
*type
, void *context
)
344 Py_INCREF(type
->tp_bases
);
345 return type
->tp_bases
;
348 static PyTypeObject
*best_base(PyObject
*);
349 static int mro_internal(PyTypeObject
*);
350 static int compatible_for_assignment(PyTypeObject
*, PyTypeObject
*, char *);
351 static int add_subclass(PyTypeObject
*, PyTypeObject
*);
352 static void remove_subclass(PyTypeObject
*, PyTypeObject
*);
353 static void update_all_slots(PyTypeObject
*);
355 typedef int (*update_callback
)(PyTypeObject
*, void *);
356 static int update_subclasses(PyTypeObject
*type
, PyObject
*name
,
357 update_callback callback
, void *data
);
358 static int recurse_down_subclasses(PyTypeObject
*type
, PyObject
*name
,
359 update_callback callback
, void *data
);
362 mro_subclasses(PyTypeObject
*type
, PyObject
* temp
)
364 PyTypeObject
*subclass
;
365 PyObject
*ref
, *subclasses
, *old_mro
;
368 subclasses
= type
->tp_subclasses
;
369 if (subclasses
== NULL
)
371 assert(PyList_Check(subclasses
));
372 n
= PyList_GET_SIZE(subclasses
);
373 for (i
= 0; i
< n
; i
++) {
374 ref
= PyList_GET_ITEM(subclasses
, i
);
375 assert(PyWeakref_CheckRef(ref
));
376 subclass
= (PyTypeObject
*)PyWeakref_GET_OBJECT(ref
);
377 assert(subclass
!= NULL
);
378 if ((PyObject
*)subclass
== Py_None
)
380 assert(PyType_Check(subclass
));
381 old_mro
= subclass
->tp_mro
;
382 if (mro_internal(subclass
) < 0) {
383 subclass
->tp_mro
= old_mro
;
388 tuple
= PyTuple_Pack(2, subclass
, old_mro
);
392 if (PyList_Append(temp
, tuple
) < 0)
396 if (mro_subclasses(subclass
, temp
) < 0)
403 type_set_bases(PyTypeObject
*type
, PyObject
*value
, void *context
)
408 PyTypeObject
*new_base
, *old_base
;
409 PyObject
*old_bases
, *old_mro
;
411 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
412 PyErr_Format(PyExc_TypeError
,
413 "can't set %s.__bases__", type
->tp_name
);
417 PyErr_Format(PyExc_TypeError
,
418 "can't delete %s.__bases__", type
->tp_name
);
421 if (!PyTuple_Check(value
)) {
422 PyErr_Format(PyExc_TypeError
,
423 "can only assign tuple to %s.__bases__, not %s",
424 type
->tp_name
, Py_TYPE(value
)->tp_name
);
427 if (PyTuple_GET_SIZE(value
) == 0) {
428 PyErr_Format(PyExc_TypeError
,
429 "can only assign non-empty tuple to %s.__bases__, not ()",
433 for (i
= 0; i
< PyTuple_GET_SIZE(value
); i
++) {
434 ob
= PyTuple_GET_ITEM(value
, i
);
435 if (!PyClass_Check(ob
) && !PyType_Check(ob
)) {
438 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
439 type
->tp_name
, Py_TYPE(ob
)->tp_name
);
442 if (PyType_Check(ob
)) {
443 if (PyType_IsSubtype((PyTypeObject
*)ob
, type
)) {
444 PyErr_SetString(PyExc_TypeError
,
445 "a __bases__ item causes an inheritance cycle");
451 new_base
= best_base(value
);
457 if (!compatible_for_assignment(type
->tp_base
, new_base
, "__bases__"))
463 old_bases
= type
->tp_bases
;
464 old_base
= type
->tp_base
;
465 old_mro
= type
->tp_mro
;
467 type
->tp_bases
= value
;
468 type
->tp_base
= new_base
;
470 if (mro_internal(type
) < 0) {
474 temp
= PyList_New(0);
478 r
= mro_subclasses(type
, temp
);
481 for (i
= 0; i
< PyList_Size(temp
); i
++) {
484 PyArg_UnpackTuple(PyList_GET_ITEM(temp
, i
),
485 "", 2, 2, &cls
, &mro
);
497 /* any base that was in __bases__ but now isn't, we
498 need to remove |type| from its tp_subclasses.
499 conversely, any class now in __bases__ that wasn't
500 needs to have |type| added to its subclasses. */
502 /* for now, sod that: just remove from all old_bases,
503 add to all new_bases */
505 for (i
= PyTuple_GET_SIZE(old_bases
) - 1; i
>= 0; i
--) {
506 ob
= PyTuple_GET_ITEM(old_bases
, i
);
507 if (PyType_Check(ob
)) {
509 (PyTypeObject
*)ob
, type
);
513 for (i
= PyTuple_GET_SIZE(value
) - 1; i
>= 0; i
--) {
514 ob
= PyTuple_GET_ITEM(value
, i
);
515 if (PyType_Check(ob
)) {
516 if (add_subclass((PyTypeObject
*)ob
, type
) < 0)
521 update_all_slots(type
);
523 Py_DECREF(old_bases
);
530 Py_DECREF(type
->tp_bases
);
531 Py_DECREF(type
->tp_base
);
532 if (type
->tp_mro
!= old_mro
) {
533 Py_DECREF(type
->tp_mro
);
536 type
->tp_bases
= old_bases
;
537 type
->tp_base
= old_base
;
538 type
->tp_mro
= old_mro
;
544 type_dict(PyTypeObject
*type
, void *context
)
546 if (type
->tp_dict
== NULL
) {
550 return PyDictProxy_New(type
->tp_dict
);
554 type_get_doc(PyTypeObject
*type
, void *context
)
557 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) && type
->tp_doc
!= NULL
)
558 return PyString_FromString(type
->tp_doc
);
559 result
= PyDict_GetItemString(type
->tp_dict
, "__doc__");
560 if (result
== NULL
) {
564 else if (Py_TYPE(result
)->tp_descr_get
) {
565 result
= Py_TYPE(result
)->tp_descr_get(result
, NULL
,
575 type___instancecheck__(PyObject
*type
, PyObject
*inst
)
577 switch (_PyObject_RealIsInstance(inst
, type
)) {
589 type___subclasscheck__(PyObject
*type
, PyObject
*inst
)
591 switch (_PyObject_RealIsSubclass(inst
, type
)) {
602 static PyGetSetDef type_getsets
[] = {
603 {"__name__", (getter
)type_name
, (setter
)type_set_name
, NULL
},
604 {"__bases__", (getter
)type_get_bases
, (setter
)type_set_bases
, NULL
},
605 {"__module__", (getter
)type_module
, (setter
)type_set_module
, NULL
},
606 {"__abstractmethods__", (getter
)type_abstractmethods
,
607 (setter
)type_set_abstractmethods
, NULL
},
608 {"__dict__", (getter
)type_dict
, NULL
, NULL
},
609 {"__doc__", (getter
)type_get_doc
, NULL
, NULL
},
614 type_compare(PyObject
*v
, PyObject
*w
)
616 /* This is called with type objects only. So we
617 can just compare the addresses. */
618 Py_uintptr_t vv
= (Py_uintptr_t
)v
;
619 Py_uintptr_t ww
= (Py_uintptr_t
)w
;
620 return (vv
< ww
) ? -1 : (vv
> ww
) ? 1 : 0;
624 type_richcompare(PyObject
*v
, PyObject
*w
, int op
)
630 /* Make sure both arguments are types. */
631 if (!PyType_Check(v
) || !PyType_Check(w
)) {
632 result
= Py_NotImplemented
;
636 /* Py3K warning if comparison isn't == or != */
637 if (Py_Py3kWarningFlag
&& op
!= Py_EQ
&& op
!= Py_NE
&&
638 PyErr_WarnEx(PyExc_DeprecationWarning
,
639 "type inequality comparisons not supported "
644 /* Compare addresses */
645 vv
= (Py_uintptr_t
)v
;
646 ww
= (Py_uintptr_t
)w
;
648 case Py_LT
: c
= vv
< ww
; break;
649 case Py_LE
: c
= vv
<= ww
; break;
650 case Py_EQ
: c
= vv
== ww
; break;
651 case Py_NE
: c
= vv
!= ww
; break;
652 case Py_GT
: c
= vv
> ww
; break;
653 case Py_GE
: c
= vv
>= ww
; break;
655 result
= Py_NotImplemented
;
658 result
= c
? Py_True
: Py_False
;
660 /* incref and return */
667 type_repr(PyTypeObject
*type
)
669 PyObject
*mod
, *name
, *rtn
;
672 mod
= type_module(type
, NULL
);
675 else if (!PyString_Check(mod
)) {
679 name
= type_name(type
, NULL
);
683 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
688 if (mod
!= NULL
&& strcmp(PyString_AS_STRING(mod
), "__builtin__")) {
689 rtn
= PyString_FromFormat("<%s '%s.%s'>",
691 PyString_AS_STRING(mod
),
692 PyString_AS_STRING(name
));
695 rtn
= PyString_FromFormat("<%s '%s'>", kind
, type
->tp_name
);
703 type_call(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
707 if (type
->tp_new
== NULL
) {
708 PyErr_Format(PyExc_TypeError
,
709 "cannot create '%.100s' instances",
714 obj
= type
->tp_new(type
, args
, kwds
);
716 /* Ugly exception: when the call was type(something),
717 don't call tp_init on the result. */
718 if (type
== &PyType_Type
&&
719 PyTuple_Check(args
) && PyTuple_GET_SIZE(args
) == 1 &&
721 (PyDict_Check(kwds
) && PyDict_Size(kwds
) == 0)))
723 /* If the returned object is not an instance of type,
724 it won't be initialized. */
725 if (!PyType_IsSubtype(obj
->ob_type
, type
))
728 if (PyType_HasFeature(type
, Py_TPFLAGS_HAVE_CLASS
) &&
729 type
->tp_init
!= NULL
&&
730 type
->tp_init(obj
, args
, kwds
) < 0) {
739 PyType_GenericAlloc(PyTypeObject
*type
, Py_ssize_t nitems
)
742 const size_t size
= _PyObject_VAR_SIZE(type
, nitems
+1);
743 /* note that we need to add one, for the sentinel */
745 if (PyType_IS_GC(type
))
746 obj
= _PyObject_GC_Malloc(size
);
748 obj
= (PyObject
*)PyObject_MALLOC(size
);
751 return PyErr_NoMemory();
753 memset(obj
, '\0', size
);
755 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
758 if (type
->tp_itemsize
== 0)
759 PyObject_INIT(obj
, type
);
761 (void) PyObject_INIT_VAR((PyVarObject
*)obj
, type
, nitems
);
763 if (PyType_IS_GC(type
))
764 _PyObject_GC_TRACK(obj
);
769 PyType_GenericNew(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
771 return type
->tp_alloc(type
, 0);
774 /* Helpers for subtyping */
777 traverse_slots(PyTypeObject
*type
, PyObject
*self
, visitproc visit
, void *arg
)
783 mp
= PyHeapType_GET_MEMBERS((PyHeapTypeObject
*)type
);
784 for (i
= 0; i
< n
; i
++, mp
++) {
785 if (mp
->type
== T_OBJECT_EX
) {
786 char *addr
= (char *)self
+ mp
->offset
;
787 PyObject
*obj
= *(PyObject
**)addr
;
789 int err
= visit(obj
, arg
);
799 subtype_traverse(PyObject
*self
, visitproc visit
, void *arg
)
801 PyTypeObject
*type
, *base
;
802 traverseproc basetraverse
;
804 /* Find the nearest base with a different tp_traverse,
805 and traverse slots while we're at it */
806 type
= Py_TYPE(self
);
808 while ((basetraverse
= base
->tp_traverse
) == subtype_traverse
) {
810 int err
= traverse_slots(base
, self
, visit
, arg
);
814 base
= base
->tp_base
;
818 if (type
->tp_dictoffset
!= base
->tp_dictoffset
) {
819 PyObject
**dictptr
= _PyObject_GetDictPtr(self
);
820 if (dictptr
&& *dictptr
)
824 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
825 /* For a heaptype, the instances count as references
826 to the type. Traverse the type so the collector
827 can find cycles involving this link. */
831 return basetraverse(self
, visit
, arg
);
836 clear_slots(PyTypeObject
*type
, PyObject
*self
)
842 mp
= PyHeapType_GET_MEMBERS((PyHeapTypeObject
*)type
);
843 for (i
= 0; i
< n
; i
++, mp
++) {
844 if (mp
->type
== T_OBJECT_EX
&& !(mp
->flags
& READONLY
)) {
845 char *addr
= (char *)self
+ mp
->offset
;
846 PyObject
*obj
= *(PyObject
**)addr
;
848 *(PyObject
**)addr
= NULL
;
856 subtype_clear(PyObject
*self
)
858 PyTypeObject
*type
, *base
;
861 /* Find the nearest base with a different tp_clear
862 and clear slots while we're at it */
863 type
= Py_TYPE(self
);
865 while ((baseclear
= base
->tp_clear
) == subtype_clear
) {
867 clear_slots(base
, self
);
868 base
= base
->tp_base
;
872 /* There's no need to clear the instance dict (if any);
873 the collector will call its tp_clear handler. */
876 return baseclear(self
);
881 subtype_dealloc(PyObject
*self
)
883 PyTypeObject
*type
, *base
;
884 destructor basedealloc
;
886 /* Extract the type; we expect it to be a heap type */
887 type
= Py_TYPE(self
);
888 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
890 /* Test whether the type has GC exactly once */
892 if (!PyType_IS_GC(type
)) {
893 /* It's really rare to find a dynamic type that doesn't have
894 GC; it can only happen when deriving from 'object' and not
895 adding any slots or instance variables. This allows
896 certain simplifications: there's no need to call
897 clear_slots(), or DECREF the dict, or clear weakrefs. */
899 /* Maybe call finalizer; exit early if resurrected */
902 if (self
->ob_refcnt
> 0)
906 /* Find the nearest base with a different tp_dealloc */
908 while ((basedealloc
= base
->tp_dealloc
) == subtype_dealloc
) {
909 assert(Py_SIZE(base
) == 0);
910 base
= base
->tp_base
;
914 /* Extract the type again; tp_del may have changed it */
915 type
= Py_TYPE(self
);
917 /* Call the base tp_dealloc() */
921 /* Can't reference self beyond this point */
928 /* We get here only if the type has GC */
930 /* UnTrack and re-Track around the trashcan macro, alas */
931 /* See explanation at end of function for full disclosure */
932 PyObject_GC_UnTrack(self
);
933 ++_PyTrash_delete_nesting
;
934 Py_TRASHCAN_SAFE_BEGIN(self
);
935 --_PyTrash_delete_nesting
;
936 /* DO NOT restore GC tracking at this point. weakref callbacks
937 * (if any, and whether directly here or indirectly in something we
938 * call) may trigger GC, and if self is tracked at that point, it
939 * will look like trash to GC and GC will try to delete self again.
942 /* Find the nearest base with a different tp_dealloc */
944 while ((basedealloc
= base
->tp_dealloc
) == subtype_dealloc
) {
945 base
= base
->tp_base
;
949 /* If we added a weaklist, we clear it. Do this *before* calling
950 the finalizer (__del__), clearing slots, or clearing the instance
953 if (type
->tp_weaklistoffset
&& !base
->tp_weaklistoffset
)
954 PyObject_ClearWeakRefs(self
);
956 /* Maybe call finalizer; exit early if resurrected */
958 _PyObject_GC_TRACK(self
);
960 if (self
->ob_refcnt
> 0)
961 goto endlabel
; /* resurrected */
963 _PyObject_GC_UNTRACK(self
);
964 /* New weakrefs could be created during the finalizer call.
965 If this occurs, clear them out without calling their
966 finalizers since they might rely on part of the object
967 being finalized that has already been destroyed. */
968 if (type
->tp_weaklistoffset
&& !base
->tp_weaklistoffset
) {
969 /* Modeled after GET_WEAKREFS_LISTPTR() */
970 PyWeakReference
**list
= (PyWeakReference
**) \
971 PyObject_GET_WEAKREFS_LISTPTR(self
);
973 _PyWeakref_ClearRef(*list
);
977 /* Clear slots up to the nearest base with a different tp_dealloc */
979 while ((basedealloc
= base
->tp_dealloc
) == subtype_dealloc
) {
981 clear_slots(base
, self
);
982 base
= base
->tp_base
;
986 /* If we added a dict, DECREF it */
987 if (type
->tp_dictoffset
&& !base
->tp_dictoffset
) {
988 PyObject
**dictptr
= _PyObject_GetDictPtr(self
);
989 if (dictptr
!= NULL
) {
990 PyObject
*dict
= *dictptr
;
998 /* Extract the type again; tp_del may have changed it */
999 type
= Py_TYPE(self
);
1001 /* Call the base tp_dealloc(); first retrack self if
1002 * basedealloc knows about gc.
1004 if (PyType_IS_GC(base
))
1005 _PyObject_GC_TRACK(self
);
1006 assert(basedealloc
);
1009 /* Can't reference self beyond this point */
1013 ++_PyTrash_delete_nesting
;
1014 Py_TRASHCAN_SAFE_END(self
);
1015 --_PyTrash_delete_nesting
;
1017 /* Explanation of the weirdness around the trashcan macros:
1019 Q. What do the trashcan macros do?
1021 A. Read the comment titled "Trashcan mechanism" in object.h.
1022 For one, this explains why there must be a call to GC-untrack
1023 before the trashcan begin macro. Without understanding the
1024 trashcan code, the answers to the following questions don't make
1027 Q. Why do we GC-untrack before the trashcan and then immediately
1028 GC-track again afterward?
1030 A. In the case that the base class is GC-aware, the base class
1031 probably GC-untracks the object. If it does that using the
1032 UNTRACK macro, this will crash when the object is already
1033 untracked. Because we don't know what the base class does, the
1034 only safe thing is to make sure the object is tracked when we
1035 call the base class dealloc. But... The trashcan begin macro
1036 requires that the object is *untracked* before it is called. So
1043 Q. Why did the last question say "immediately GC-track again"?
1044 It's nowhere near immediately.
1046 A. Because the code *used* to re-track immediately. Bad Idea.
1047 self has a refcount of 0, and if gc ever gets its hands on it
1048 (which can happen if any weakref callback gets invoked), it
1049 looks like trash to gc too, and gc also tries to delete self
1050 then. But we're already deleting self. Double dealloction is
1053 Q. Why the bizarre (net-zero) manipulation of
1054 _PyTrash_delete_nesting around the trashcan macros?
1056 A. Some base classes (e.g. list) also use the trashcan mechanism.
1057 The following scenario used to be possible:
1059 - suppose the trashcan level is one below the trashcan limit
1061 - subtype_dealloc() is called
1063 - the trashcan limit is not yet reached, so the trashcan level
1064 is incremented and the code between trashcan begin and end is
1067 - this destroys much of the object's contents, including its
1070 - basedealloc() is called; this is really list_dealloc(), or
1071 some other type which also uses the trashcan macros
1073 - the trashcan limit is now reached, so the object is put on the
1074 trashcan's to-be-deleted-later list
1076 - basedealloc() returns
1078 - subtype_dealloc() decrefs the object's type
1080 - subtype_dealloc() returns
1082 - later, the trashcan code starts deleting the objects from its
1083 to-be-deleted-later list
1085 - subtype_dealloc() is called *AGAIN* for the same object
1087 - at the very least (if the destroyed slots and __dict__ don't
1088 cause problems) the object's type gets decref'ed a second
1089 time, which is *BAD*!!!
1091 The remedy is to make sure that if the code between trashcan
1092 begin and end in subtype_dealloc() is called, the code between
1093 trashcan begin and end in basedealloc() will also be called.
1094 This is done by decrementing the level after passing into the
1095 trashcan block, and incrementing it just before leaving the
1098 But now it's possible that a chain of objects consisting solely
1099 of objects whose deallocator is subtype_dealloc() will defeat
1100 the trashcan mechanism completely: the decremented level means
1101 that the effective level never reaches the limit. Therefore, we
1102 *increment* the level *before* entering the trashcan block, and
1103 matchingly decrement it after leaving. This means the trashcan
1104 code will trigger a little early, but that's no big deal.
1106 Q. Are there any live examples of code in need of all this
1109 A. Yes. See SF bug 668433 for code that crashed (when Python was
1110 compiled in debug mode) before the trashcan level manipulations
1111 were added. For more discussion, see SF patches 581742, 575073
1116 static PyTypeObject
*solid_base(PyTypeObject
*type
);
1118 /* type test with subclassing support */
1121 PyType_IsSubtype(PyTypeObject
*a
, PyTypeObject
*b
)
1125 if (!(a
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
))
1126 return b
== a
|| b
== &PyBaseObject_Type
;
1130 /* Deal with multiple inheritance without recursion
1131 by walking the MRO tuple */
1133 assert(PyTuple_Check(mro
));
1134 n
= PyTuple_GET_SIZE(mro
);
1135 for (i
= 0; i
< n
; i
++) {
1136 if (PyTuple_GET_ITEM(mro
, i
) == (PyObject
*)b
)
1142 /* a is not completely initilized yet; follow tp_base */
1147 } while (a
!= NULL
);
1148 return b
== &PyBaseObject_Type
;
1152 /* Internal routines to do a method lookup in the type
1153 without looking in the instance dictionary
1154 (so we can't use PyObject_GetAttr) but still binding
1155 it to the instance. The arguments are the object,
1156 the method name as a C string, and the address of a
1157 static variable used to cache the interned Python string.
1161 - lookup_maybe() returns NULL without raising an exception
1162 when the _PyType_Lookup() call fails;
1164 - lookup_method() always raises an exception upon errors.
1166 - _PyObject_LookupSpecial() exported for the benefit of other places.
1170 lookup_maybe(PyObject
*self
, char *attrstr
, PyObject
**attrobj
)
1174 if (*attrobj
== NULL
) {
1175 *attrobj
= PyString_InternFromString(attrstr
);
1176 if (*attrobj
== NULL
)
1179 res
= _PyType_Lookup(Py_TYPE(self
), *attrobj
);
1182 if ((f
= Py_TYPE(res
)->tp_descr_get
) == NULL
)
1185 res
= f(res
, self
, (PyObject
*)(Py_TYPE(self
)));
1191 lookup_method(PyObject
*self
, char *attrstr
, PyObject
**attrobj
)
1193 PyObject
*res
= lookup_maybe(self
, attrstr
, attrobj
);
1194 if (res
== NULL
&& !PyErr_Occurred())
1195 PyErr_SetObject(PyExc_AttributeError
, *attrobj
);
1200 _PyObject_LookupSpecial(PyObject
*self
, char *attrstr
, PyObject
**attrobj
)
1202 assert(!PyInstance_Check(self
));
1203 return lookup_maybe(self
, attrstr
, attrobj
);
1206 /* A variation of PyObject_CallMethod that uses lookup_method()
1207 instead of PyObject_GetAttrString(). This uses the same convention
1208 as lookup_method to cache the interned name string object. */
1211 call_method(PyObject
*o
, char *name
, PyObject
**nameobj
, char *format
, ...)
1214 PyObject
*args
, *func
= 0, *retval
;
1215 va_start(va
, format
);
1217 func
= lookup_maybe(o
, name
, nameobj
);
1220 if (!PyErr_Occurred())
1221 PyErr_SetObject(PyExc_AttributeError
, *nameobj
);
1225 if (format
&& *format
)
1226 args
= Py_VaBuildValue(format
, va
);
1228 args
= PyTuple_New(0);
1235 assert(PyTuple_Check(args
));
1236 retval
= PyObject_Call(func
, args
, NULL
);
1244 /* Clone of call_method() that returns NotImplemented when the lookup fails. */
1247 call_maybe(PyObject
*o
, char *name
, PyObject
**nameobj
, char *format
, ...)
1250 PyObject
*args
, *func
= 0, *retval
;
1251 va_start(va
, format
);
1253 func
= lookup_maybe(o
, name
, nameobj
);
1256 if (!PyErr_Occurred()) {
1257 Py_INCREF(Py_NotImplemented
);
1258 return Py_NotImplemented
;
1263 if (format
&& *format
)
1264 args
= Py_VaBuildValue(format
, va
);
1266 args
= PyTuple_New(0);
1273 assert(PyTuple_Check(args
));
1274 retval
= PyObject_Call(func
, args
, NULL
);
1283 fill_classic_mro(PyObject
*mro
, PyObject
*cls
)
1285 PyObject
*bases
, *base
;
1288 assert(PyList_Check(mro
));
1289 assert(PyClass_Check(cls
));
1290 i
= PySequence_Contains(mro
, cls
);
1294 if (PyList_Append(mro
, cls
) < 0)
1297 bases
= ((PyClassObject
*)cls
)->cl_bases
;
1298 assert(bases
&& PyTuple_Check(bases
));
1299 n
= PyTuple_GET_SIZE(bases
);
1300 for (i
= 0; i
< n
; i
++) {
1301 base
= PyTuple_GET_ITEM(bases
, i
);
1302 if (fill_classic_mro(mro
, base
) < 0)
1309 classic_mro(PyObject
*cls
)
1313 assert(PyClass_Check(cls
));
1314 mro
= PyList_New(0);
1316 if (fill_classic_mro(mro
, cls
) == 0)
1324 Method resolution order algorithm C3 described in
1325 "A Monotonic Superclass Linearization for Dylan",
1326 by Kim Barrett, Bob Cassel, Paul Haahr,
1327 David A. Moon, Keith Playford, and P. Tucker Withington.
1330 Some notes about the rules implied by C3:
1333 It isn't legal to repeat a class in a list of base classes.
1335 The next three properties are the 3 constraints in "C3".
1337 Local precendece order.
1338 If A precedes B in C's MRO, then A will precede B in the MRO of all
1342 The MRO of a class must be an extension without reordering of the
1343 MRO of each of its superclasses.
1345 Extended Precedence Graph (EPG).
1346 Linearization is consistent if there is a path in the EPG from
1347 each class to all its successors in the linearization. See
1348 the paper for definition of EPG.
1352 tail_contains(PyObject
*list
, int whence
, PyObject
*o
) {
1354 size
= PyList_GET_SIZE(list
);
1356 for (j
= whence
+1; j
< size
; j
++) {
1357 if (PyList_GET_ITEM(list
, j
) == o
)
1364 class_name(PyObject
*cls
)
1366 PyObject
*name
= PyObject_GetAttrString(cls
, "__name__");
1370 name
= PyObject_Repr(cls
);
1374 if (!PyString_Check(name
)) {
1382 check_duplicates(PyObject
*list
)
1385 /* Let's use a quadratic time algorithm,
1386 assuming that the bases lists is short.
1388 n
= PyList_GET_SIZE(list
);
1389 for (i
= 0; i
< n
; i
++) {
1390 PyObject
*o
= PyList_GET_ITEM(list
, i
);
1391 for (j
= i
+ 1; j
< n
; j
++) {
1392 if (PyList_GET_ITEM(list
, j
) == o
) {
1394 PyErr_Format(PyExc_TypeError
,
1395 "duplicate base class %s",
1396 o
? PyString_AS_STRING(o
) : "?");
1405 /* Raise a TypeError for an MRO order disagreement.
1407 It's hard to produce a good error message. In the absence of better
1408 insight into error reporting, report the classes that were candidates
1409 to be put next into the MRO. There is some conflict between the
1410 order in which they should be put in the MRO, but it's hard to
1411 diagnose what constraint can't be satisfied.
1415 set_mro_error(PyObject
*to_merge
, int *remain
)
1417 Py_ssize_t i
, n
, off
, to_merge_size
;
1420 PyObject
*set
= PyDict_New();
1423 to_merge_size
= PyList_GET_SIZE(to_merge
);
1424 for (i
= 0; i
< to_merge_size
; i
++) {
1425 PyObject
*L
= PyList_GET_ITEM(to_merge
, i
);
1426 if (remain
[i
] < PyList_GET_SIZE(L
)) {
1427 PyObject
*c
= PyList_GET_ITEM(L
, remain
[i
]);
1428 if (PyDict_SetItem(set
, c
, Py_None
) < 0) {
1434 n
= PyDict_Size(set
);
1436 off
= PyOS_snprintf(buf
, sizeof(buf
), "Cannot create a \
1437 consistent method resolution\norder (MRO) for bases");
1439 while (PyDict_Next(set
, &i
, &k
, &v
) && (size_t)off
< sizeof(buf
)) {
1440 PyObject
*name
= class_name(k
);
1441 off
+= PyOS_snprintf(buf
+ off
, sizeof(buf
) - off
, " %s",
1442 name
? PyString_AS_STRING(name
) : "?");
1444 if (--n
&& (size_t)(off
+1) < sizeof(buf
)) {
1449 PyErr_SetString(PyExc_TypeError
, buf
);
1454 pmerge(PyObject
*acc
, PyObject
* to_merge
) {
1455 Py_ssize_t i
, j
, to_merge_size
, empty_cnt
;
1459 to_merge_size
= PyList_GET_SIZE(to_merge
);
1461 /* remain stores an index into each sublist of to_merge.
1462 remain[i] is the index of the next base in to_merge[i]
1463 that is not included in acc.
1465 remain
= (int *)PyMem_MALLOC(SIZEOF_INT
*to_merge_size
);
1468 for (i
= 0; i
< to_merge_size
; i
++)
1473 for (i
= 0; i
< to_merge_size
; i
++) {
1474 PyObject
*candidate
;
1476 PyObject
*cur_list
= PyList_GET_ITEM(to_merge
, i
);
1478 if (remain
[i
] >= PyList_GET_SIZE(cur_list
)) {
1483 /* Choose next candidate for MRO.
1485 The input sequences alone can determine the choice.
1486 If not, choose the class which appears in the MRO
1487 of the earliest direct superclass of the new class.
1490 candidate
= PyList_GET_ITEM(cur_list
, remain
[i
]);
1491 for (j
= 0; j
< to_merge_size
; j
++) {
1492 PyObject
*j_lst
= PyList_GET_ITEM(to_merge
, j
);
1493 if (tail_contains(j_lst
, remain
[j
], candidate
)) {
1494 goto skip
; /* continue outer loop */
1497 ok
= PyList_Append(acc
, candidate
);
1502 for (j
= 0; j
< to_merge_size
; j
++) {
1503 PyObject
*j_lst
= PyList_GET_ITEM(to_merge
, j
);
1504 if (remain
[j
] < PyList_GET_SIZE(j_lst
) &&
1505 PyList_GET_ITEM(j_lst
, remain
[j
]) == candidate
) {
1513 if (empty_cnt
== to_merge_size
) {
1517 set_mro_error(to_merge
, remain
);
1523 mro_implementation(PyTypeObject
*type
)
1527 PyObject
*bases
, *result
;
1528 PyObject
*to_merge
, *bases_aslist
;
1530 if (type
->tp_dict
== NULL
) {
1531 if (PyType_Ready(type
) < 0)
1535 /* Find a superclass linearization that honors the constraints
1536 of the explicit lists of bases and the constraints implied by
1539 to_merge is a list of lists, where each list is a superclass
1540 linearization implied by a base class. The last element of
1541 to_merge is the declared list of bases.
1544 bases
= type
->tp_bases
;
1545 n
= PyTuple_GET_SIZE(bases
);
1547 to_merge
= PyList_New(n
+1);
1548 if (to_merge
== NULL
)
1551 for (i
= 0; i
< n
; i
++) {
1552 PyObject
*base
= PyTuple_GET_ITEM(bases
, i
);
1553 PyObject
*parentMRO
;
1554 if (PyType_Check(base
))
1555 parentMRO
= PySequence_List(
1556 ((PyTypeObject
*)base
)->tp_mro
);
1558 parentMRO
= classic_mro(base
);
1559 if (parentMRO
== NULL
) {
1560 Py_DECREF(to_merge
);
1564 PyList_SET_ITEM(to_merge
, i
, parentMRO
);
1567 bases_aslist
= PySequence_List(bases
);
1568 if (bases_aslist
== NULL
) {
1569 Py_DECREF(to_merge
);
1572 /* This is just a basic sanity check. */
1573 if (check_duplicates(bases_aslist
) < 0) {
1574 Py_DECREF(to_merge
);
1575 Py_DECREF(bases_aslist
);
1578 PyList_SET_ITEM(to_merge
, n
, bases_aslist
);
1580 result
= Py_BuildValue("[O]", (PyObject
*)type
);
1581 if (result
== NULL
) {
1582 Py_DECREF(to_merge
);
1586 ok
= pmerge(result
, to_merge
);
1587 Py_DECREF(to_merge
);
1597 mro_external(PyObject
*self
)
1599 PyTypeObject
*type
= (PyTypeObject
*)self
;
1601 return mro_implementation(type
);
1605 mro_internal(PyTypeObject
*type
)
1607 PyObject
*mro
, *result
, *tuple
;
1610 if (Py_TYPE(type
) == &PyType_Type
) {
1611 result
= mro_implementation(type
);
1614 static PyObject
*mro_str
;
1616 mro
= lookup_method((PyObject
*)type
, "mro", &mro_str
);
1619 result
= PyObject_CallObject(mro
, NULL
);
1624 tuple
= PySequence_Tuple(result
);
1631 PyTypeObject
*solid
;
1633 solid
= solid_base(type
);
1635 len
= PyTuple_GET_SIZE(tuple
);
1637 for (i
= 0; i
< len
; i
++) {
1639 cls
= PyTuple_GET_ITEM(tuple
, i
);
1640 if (PyClass_Check(cls
))
1642 else if (!PyType_Check(cls
)) {
1643 PyErr_Format(PyExc_TypeError
,
1644 "mro() returned a non-class ('%.500s')",
1645 Py_TYPE(cls
)->tp_name
);
1649 t
= (PyTypeObject
*)cls
;
1650 if (!PyType_IsSubtype(solid
, solid_base(t
))) {
1651 PyErr_Format(PyExc_TypeError
,
1652 "mro() returned base with unsuitable layout ('%.500s')",
1659 type
->tp_mro
= tuple
;
1661 type_mro_modified(type
, type
->tp_mro
);
1662 /* corner case: the old-style super class might have been hidden
1663 from the custom MRO */
1664 type_mro_modified(type
, type
->tp_bases
);
1666 PyType_Modified(type
);
1672 /* Calculate the best base amongst multiple base classes.
1673 This is the first one that's on the path to the "solid base". */
1675 static PyTypeObject
*
1676 best_base(PyObject
*bases
)
1679 PyTypeObject
*base
, *winner
, *candidate
, *base_i
;
1680 PyObject
*base_proto
;
1682 assert(PyTuple_Check(bases
));
1683 n
= PyTuple_GET_SIZE(bases
);
1687 for (i
= 0; i
< n
; i
++) {
1688 base_proto
= PyTuple_GET_ITEM(bases
, i
);
1689 if (PyClass_Check(base_proto
))
1691 if (!PyType_Check(base_proto
)) {
1694 "bases must be types");
1697 base_i
= (PyTypeObject
*)base_proto
;
1698 if (base_i
->tp_dict
== NULL
) {
1699 if (PyType_Ready(base_i
) < 0)
1702 candidate
= solid_base(base_i
);
1703 if (winner
== NULL
) {
1707 else if (PyType_IsSubtype(winner
, candidate
))
1709 else if (PyType_IsSubtype(candidate
, winner
)) {
1716 "multiple bases have "
1717 "instance lay-out conflict");
1722 PyErr_SetString(PyExc_TypeError
,
1723 "a new-style class can't have only classic bases");
1728 extra_ivars(PyTypeObject
*type
, PyTypeObject
*base
)
1730 size_t t_size
= type
->tp_basicsize
;
1731 size_t b_size
= base
->tp_basicsize
;
1733 assert(t_size
>= b_size
); /* Else type smaller than base! */
1734 if (type
->tp_itemsize
|| base
->tp_itemsize
) {
1735 /* If itemsize is involved, stricter rules */
1736 return t_size
!= b_size
||
1737 type
->tp_itemsize
!= base
->tp_itemsize
;
1739 if (type
->tp_weaklistoffset
&& base
->tp_weaklistoffset
== 0 &&
1740 type
->tp_weaklistoffset
+ sizeof(PyObject
*) == t_size
&&
1741 type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
1742 t_size
-= sizeof(PyObject
*);
1743 if (type
->tp_dictoffset
&& base
->tp_dictoffset
== 0 &&
1744 type
->tp_dictoffset
+ sizeof(PyObject
*) == t_size
&&
1745 type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
1746 t_size
-= sizeof(PyObject
*);
1748 return t_size
!= b_size
;
1751 static PyTypeObject
*
1752 solid_base(PyTypeObject
*type
)
1757 base
= solid_base(type
->tp_base
);
1759 base
= &PyBaseObject_Type
;
1760 if (extra_ivars(type
, base
))
1766 static void object_dealloc(PyObject
*);
1767 static int object_init(PyObject
*, PyObject
*, PyObject
*);
1768 static int update_slot(PyTypeObject
*, PyObject
*);
1769 static void fixup_slot_dispatchers(PyTypeObject
*);
1772 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1773 * inherited from various builtin types. The builtin base usually provides
1774 * its own __dict__ descriptor, so we use that when we can.
1776 static PyTypeObject
*
1777 get_builtin_base_with_dict(PyTypeObject
*type
)
1779 while (type
->tp_base
!= NULL
) {
1780 if (type
->tp_dictoffset
!= 0 &&
1781 !(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
1783 type
= type
->tp_base
;
1789 get_dict_descriptor(PyTypeObject
*type
)
1791 static PyObject
*dict_str
;
1794 if (dict_str
== NULL
) {
1795 dict_str
= PyString_InternFromString("__dict__");
1796 if (dict_str
== NULL
)
1799 descr
= _PyType_Lookup(type
, dict_str
);
1800 if (descr
== NULL
|| !PyDescr_IsData(descr
))
1807 raise_dict_descr_error(PyObject
*obj
)
1809 PyErr_Format(PyExc_TypeError
,
1810 "this __dict__ descriptor does not support "
1811 "'%.200s' objects", obj
->ob_type
->tp_name
);
1815 subtype_dict(PyObject
*obj
, void *context
)
1821 base
= get_builtin_base_with_dict(obj
->ob_type
);
1824 PyObject
*descr
= get_dict_descriptor(base
);
1825 if (descr
== NULL
) {
1826 raise_dict_descr_error(obj
);
1829 func
= descr
->ob_type
->tp_descr_get
;
1831 raise_dict_descr_error(obj
);
1834 return func(descr
, obj
, (PyObject
*)(obj
->ob_type
));
1837 dictptr
= _PyObject_GetDictPtr(obj
);
1838 if (dictptr
== NULL
) {
1839 PyErr_SetString(PyExc_AttributeError
,
1840 "This object has no __dict__");
1845 *dictptr
= dict
= PyDict_New();
1851 subtype_setdict(PyObject
*obj
, PyObject
*value
, void *context
)
1857 base
= get_builtin_base_with_dict(obj
->ob_type
);
1860 PyObject
*descr
= get_dict_descriptor(base
);
1861 if (descr
== NULL
) {
1862 raise_dict_descr_error(obj
);
1865 func
= descr
->ob_type
->tp_descr_set
;
1867 raise_dict_descr_error(obj
);
1870 return func(descr
, obj
, value
);
1873 dictptr
= _PyObject_GetDictPtr(obj
);
1874 if (dictptr
== NULL
) {
1875 PyErr_SetString(PyExc_AttributeError
,
1876 "This object has no __dict__");
1879 if (value
!= NULL
&& !PyDict_Check(value
)) {
1880 PyErr_Format(PyExc_TypeError
,
1881 "__dict__ must be set to a dictionary, "
1882 "not a '%.200s'", Py_TYPE(value
)->tp_name
);
1893 subtype_getweakref(PyObject
*obj
, void *context
)
1895 PyObject
**weaklistptr
;
1898 if (Py_TYPE(obj
)->tp_weaklistoffset
== 0) {
1899 PyErr_SetString(PyExc_AttributeError
,
1900 "This object has no __weakref__");
1903 assert(Py_TYPE(obj
)->tp_weaklistoffset
> 0);
1904 assert(Py_TYPE(obj
)->tp_weaklistoffset
+ sizeof(PyObject
*) <=
1905 (size_t)(Py_TYPE(obj
)->tp_basicsize
));
1906 weaklistptr
= (PyObject
**)
1907 ((char *)obj
+ Py_TYPE(obj
)->tp_weaklistoffset
);
1908 if (*weaklistptr
== NULL
)
1911 result
= *weaklistptr
;
1916 /* Three variants on the subtype_getsets list. */
1918 static PyGetSetDef subtype_getsets_full
[] = {
1919 {"__dict__", subtype_dict
, subtype_setdict
,
1920 PyDoc_STR("dictionary for instance variables (if defined)")},
1921 {"__weakref__", subtype_getweakref
, NULL
,
1922 PyDoc_STR("list of weak references to the object (if defined)")},
1926 static PyGetSetDef subtype_getsets_dict_only
[] = {
1927 {"__dict__", subtype_dict
, subtype_setdict
,
1928 PyDoc_STR("dictionary for instance variables (if defined)")},
1932 static PyGetSetDef subtype_getsets_weakref_only
[] = {
1933 {"__weakref__", subtype_getweakref
, NULL
,
1934 PyDoc_STR("list of weak references to the object (if defined)")},
1939 valid_identifier(PyObject
*s
)
1944 if (!PyString_Check(s
)) {
1945 PyErr_Format(PyExc_TypeError
,
1946 "__slots__ items must be strings, not '%.200s'",
1947 Py_TYPE(s
)->tp_name
);
1950 p
= (unsigned char *) PyString_AS_STRING(s
);
1951 n
= PyString_GET_SIZE(s
);
1952 /* We must reject an empty name. As a hack, we bump the
1953 length to 1 so that the loop will balk on the trailing \0. */
1956 for (i
= 0; i
< n
; i
++, p
++) {
1957 if (!(i
== 0 ? isalpha(*p
) : isalnum(*p
)) && *p
!= '_') {
1958 PyErr_SetString(PyExc_TypeError
,
1959 "__slots__ must be identifiers");
1966 #ifdef Py_USING_UNICODE
1967 /* Replace Unicode objects in slots. */
1970 _unicode_to_string(PyObject
*slots
, Py_ssize_t nslots
)
1972 PyObject
*tmp
= NULL
;
1973 PyObject
*slot_name
, *new_name
;
1976 for (i
= 0; i
< nslots
; i
++) {
1977 if (PyUnicode_Check(slot_name
= PyTuple_GET_ITEM(slots
, i
))) {
1979 tmp
= PySequence_List(slots
);
1983 new_name
= _PyUnicode_AsDefaultEncodedString(slot_name
,
1985 if (new_name
== NULL
) {
1989 Py_INCREF(new_name
);
1990 PyList_SET_ITEM(tmp
, i
, new_name
);
1991 Py_DECREF(slot_name
);
1995 slots
= PyList_AsTuple(tmp
);
2004 object_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
);
2007 type_init(PyObject
*cls
, PyObject
*args
, PyObject
*kwds
)
2011 assert(args
!= NULL
&& PyTuple_Check(args
));
2012 assert(kwds
== NULL
|| PyDict_Check(kwds
));
2014 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
) != 0) {
2015 PyErr_SetString(PyExc_TypeError
,
2016 "type.__init__() takes no keyword arguments");
2020 if (args
!= NULL
&& PyTuple_Check(args
) &&
2021 (PyTuple_GET_SIZE(args
) != 1 && PyTuple_GET_SIZE(args
) != 3)) {
2022 PyErr_SetString(PyExc_TypeError
,
2023 "type.__init__() takes 1 or 3 arguments");
2027 /* Call object.__init__(self) now. */
2028 /* XXX Could call super(type, cls).__init__() but what's the point? */
2029 args
= PyTuple_GetSlice(args
, 0, 0);
2030 res
= object_init(cls
, args
, NULL
);
2036 type_new(PyTypeObject
*metatype
, PyObject
*args
, PyObject
*kwds
)
2038 PyObject
*name
, *bases
, *dict
;
2039 static char *kwlist
[] = {"name", "bases", "dict", 0};
2040 PyObject
*slots
, *tmp
, *newslots
;
2041 PyTypeObject
*type
, *base
, *tmptype
, *winner
;
2042 PyHeapTypeObject
*et
;
2044 Py_ssize_t i
, nbases
, nslots
, slotoffset
, add_dict
, add_weak
;
2045 int j
, may_add_dict
, may_add_weak
;
2047 assert(args
!= NULL
&& PyTuple_Check(args
));
2048 assert(kwds
== NULL
|| PyDict_Check(kwds
));
2050 /* Special case: type(x) should return x->ob_type */
2052 const Py_ssize_t nargs
= PyTuple_GET_SIZE(args
);
2053 const Py_ssize_t nkwds
= kwds
== NULL
? 0 : PyDict_Size(kwds
);
2055 if (PyType_CheckExact(metatype
) && nargs
== 1 && nkwds
== 0) {
2056 PyObject
*x
= PyTuple_GET_ITEM(args
, 0);
2057 Py_INCREF(Py_TYPE(x
));
2058 return (PyObject
*) Py_TYPE(x
);
2061 /* SF bug 475327 -- if that didn't trigger, we need 3
2062 arguments. but PyArg_ParseTupleAndKeywords below may give
2063 a msg saying type() needs exactly 3. */
2064 if (nargs
+ nkwds
!= 3) {
2065 PyErr_SetString(PyExc_TypeError
,
2066 "type() takes 1 or 3 arguments");
2071 /* Check arguments: (name, bases, dict) */
2072 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "SO!O!:type", kwlist
,
2074 &PyTuple_Type
, &bases
,
2075 &PyDict_Type
, &dict
))
2078 /* Determine the proper metatype to deal with this,
2079 and check for metatype conflicts while we're at it.
2080 Note that if some other metatype wins to contract,
2081 it's possible that its instances are not types. */
2082 nbases
= PyTuple_GET_SIZE(bases
);
2084 for (i
= 0; i
< nbases
; i
++) {
2085 tmp
= PyTuple_GET_ITEM(bases
, i
);
2086 tmptype
= tmp
->ob_type
;
2087 if (tmptype
== &PyClass_Type
)
2088 continue; /* Special case classic classes */
2089 if (PyType_IsSubtype(winner
, tmptype
))
2091 if (PyType_IsSubtype(tmptype
, winner
)) {
2095 PyErr_SetString(PyExc_TypeError
,
2096 "metaclass conflict: "
2097 "the metaclass of a derived class "
2098 "must be a (non-strict) subclass "
2099 "of the metaclasses of all its bases");
2102 if (winner
!= metatype
) {
2103 if (winner
->tp_new
!= type_new
) /* Pass it to the winner */
2104 return winner
->tp_new(winner
, args
, kwds
);
2108 /* Adjust for empty tuple bases */
2110 bases
= PyTuple_Pack(1, &PyBaseObject_Type
);
2118 /* XXX From here until type is allocated, "return NULL" leaks bases! */
2120 /* Calculate best base, and check that all bases are type objects */
2121 base
= best_base(bases
);
2126 if (!PyType_HasFeature(base
, Py_TPFLAGS_BASETYPE
)) {
2127 PyErr_Format(PyExc_TypeError
,
2128 "type '%.100s' is not an acceptable base type",
2134 /* Check for a __slots__ sequence variable in dict, and count it */
2135 slots
= PyDict_GetItemString(dict
, "__slots__");
2139 may_add_dict
= base
->tp_dictoffset
== 0;
2140 may_add_weak
= base
->tp_weaklistoffset
== 0 && base
->tp_itemsize
== 0;
2141 if (slots
== NULL
) {
2152 /* Make it into a tuple */
2153 if (PyString_Check(slots
) || PyUnicode_Check(slots
))
2154 slots
= PyTuple_Pack(1, slots
);
2156 slots
= PySequence_Tuple(slots
);
2157 if (slots
== NULL
) {
2161 assert(PyTuple_Check(slots
));
2163 /* Are slots allowed? */
2164 nslots
= PyTuple_GET_SIZE(slots
);
2165 if (nslots
> 0 && base
->tp_itemsize
!= 0) {
2166 PyErr_Format(PyExc_TypeError
,
2167 "nonempty __slots__ "
2168 "not supported for subtype of '%s'",
2176 #ifdef Py_USING_UNICODE
2177 tmp
= _unicode_to_string(slots
, nslots
);
2185 /* Check for valid slot names and two special cases */
2186 for (i
= 0; i
< nslots
; i
++) {
2187 PyObject
*tmp
= PyTuple_GET_ITEM(slots
, i
);
2189 if (!valid_identifier(tmp
))
2191 assert(PyString_Check(tmp
));
2192 s
= PyString_AS_STRING(tmp
);
2193 if (strcmp(s
, "__dict__") == 0) {
2194 if (!may_add_dict
|| add_dict
) {
2195 PyErr_SetString(PyExc_TypeError
,
2196 "__dict__ slot disallowed: "
2197 "we already got one");
2202 if (strcmp(s
, "__weakref__") == 0) {
2203 if (!may_add_weak
|| add_weak
) {
2204 PyErr_SetString(PyExc_TypeError
,
2205 "__weakref__ slot disallowed: "
2206 "either we already got one, "
2207 "or __itemsize__ != 0");
2214 /* Copy slots into a list, mangle names and sort them.
2215 Sorted names are needed for __class__ assignment.
2216 Convert them back to tuple at the end.
2218 newslots
= PyList_New(nslots
- add_dict
- add_weak
);
2219 if (newslots
== NULL
)
2221 for (i
= j
= 0; i
< nslots
; i
++) {
2223 tmp
= PyTuple_GET_ITEM(slots
, i
);
2224 s
= PyString_AS_STRING(tmp
);
2225 if ((add_dict
&& strcmp(s
, "__dict__") == 0) ||
2226 (add_weak
&& strcmp(s
, "__weakref__") == 0))
2228 tmp
=_Py_Mangle(name
, tmp
);
2231 PyList_SET_ITEM(newslots
, j
, tmp
);
2234 assert(j
== nslots
- add_dict
- add_weak
);
2237 if (PyList_Sort(newslots
) == -1) {
2239 Py_DECREF(newslots
);
2242 slots
= PyList_AsTuple(newslots
);
2243 Py_DECREF(newslots
);
2244 if (slots
== NULL
) {
2249 /* Secondary bases may provide weakrefs or dict */
2251 ((may_add_dict
&& !add_dict
) ||
2252 (may_add_weak
&& !add_weak
))) {
2253 for (i
= 0; i
< nbases
; i
++) {
2254 tmp
= PyTuple_GET_ITEM(bases
, i
);
2255 if (tmp
== (PyObject
*)base
)
2256 continue; /* Skip primary base */
2257 if (PyClass_Check(tmp
)) {
2258 /* Classic base class provides both */
2259 if (may_add_dict
&& !add_dict
)
2261 if (may_add_weak
&& !add_weak
)
2265 assert(PyType_Check(tmp
));
2266 tmptype
= (PyTypeObject
*)tmp
;
2267 if (may_add_dict
&& !add_dict
&&
2268 tmptype
->tp_dictoffset
!= 0)
2270 if (may_add_weak
&& !add_weak
&&
2271 tmptype
->tp_weaklistoffset
!= 0)
2273 if (may_add_dict
&& !add_dict
)
2275 if (may_add_weak
&& !add_weak
)
2277 /* Nothing more to check */
2283 /* XXX From here until type is safely allocated,
2284 "return NULL" may leak slots! */
2286 /* Allocate the type object */
2287 type
= (PyTypeObject
*)metatype
->tp_alloc(metatype
, nslots
);
2294 /* Keep name and slots alive in the extended type object */
2295 et
= (PyHeapTypeObject
*)type
;
2298 et
->ht_slots
= slots
;
2300 /* Initialize tp_flags */
2301 type
->tp_flags
= Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HEAPTYPE
|
2302 Py_TPFLAGS_BASETYPE
;
2303 if (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
)
2304 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
2305 if (base
->tp_flags
& Py_TPFLAGS_HAVE_NEWBUFFER
)
2306 type
->tp_flags
|= Py_TPFLAGS_HAVE_NEWBUFFER
;
2308 /* It's a new-style number unless it specifically inherits any
2309 old-style numeric behavior */
2310 if ((base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) ||
2311 (base
->tp_as_number
== NULL
))
2312 type
->tp_flags
|= Py_TPFLAGS_CHECKTYPES
;
2314 /* Initialize essential fields */
2315 type
->tp_as_number
= &et
->as_number
;
2316 type
->tp_as_sequence
= &et
->as_sequence
;
2317 type
->tp_as_mapping
= &et
->as_mapping
;
2318 type
->tp_as_buffer
= &et
->as_buffer
;
2319 type
->tp_name
= PyString_AS_STRING(name
);
2321 /* Set tp_base and tp_bases */
2322 type
->tp_bases
= bases
;
2324 type
->tp_base
= base
;
2326 /* Initialize tp_dict from passed-in dict */
2327 type
->tp_dict
= dict
= PyDict_Copy(dict
);
2333 /* Set __module__ in the dict */
2334 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
2335 tmp
= PyEval_GetGlobals();
2337 tmp
= PyDict_GetItemString(tmp
, "__name__");
2339 if (PyDict_SetItemString(dict
, "__module__",
2346 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2347 and is a string. The __doc__ accessor will first look for tp_doc;
2348 if that fails, it will still look into __dict__.
2351 PyObject
*doc
= PyDict_GetItemString(dict
, "__doc__");
2352 if (doc
!= NULL
&& PyString_Check(doc
)) {
2353 const size_t n
= (size_t)PyString_GET_SIZE(doc
);
2354 char *tp_doc
= (char *)PyObject_MALLOC(n
+1);
2355 if (tp_doc
== NULL
) {
2359 memcpy(tp_doc
, PyString_AS_STRING(doc
), n
+1);
2360 type
->tp_doc
= tp_doc
;
2364 /* Special-case __new__: if it's a plain function,
2365 make it a static function */
2366 tmp
= PyDict_GetItemString(dict
, "__new__");
2367 if (tmp
!= NULL
&& PyFunction_Check(tmp
)) {
2368 tmp
= PyStaticMethod_New(tmp
);
2373 PyDict_SetItemString(dict
, "__new__", tmp
);
2377 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2378 mp
= PyHeapType_GET_MEMBERS(et
);
2379 slotoffset
= base
->tp_basicsize
;
2380 if (slots
!= NULL
) {
2381 for (i
= 0; i
< nslots
; i
++, mp
++) {
2382 mp
->name
= PyString_AS_STRING(
2383 PyTuple_GET_ITEM(slots
, i
));
2384 mp
->type
= T_OBJECT_EX
;
2385 mp
->offset
= slotoffset
;
2387 /* __dict__ and __weakref__ are already filtered out */
2388 assert(strcmp(mp
->name
, "__dict__") != 0);
2389 assert(strcmp(mp
->name
, "__weakref__") != 0);
2391 slotoffset
+= sizeof(PyObject
*);
2395 if (base
->tp_itemsize
)
2396 type
->tp_dictoffset
= -(long)sizeof(PyObject
*);
2398 type
->tp_dictoffset
= slotoffset
;
2399 slotoffset
+= sizeof(PyObject
*);
2402 assert(!base
->tp_itemsize
);
2403 type
->tp_weaklistoffset
= slotoffset
;
2404 slotoffset
+= sizeof(PyObject
*);
2406 type
->tp_basicsize
= slotoffset
;
2407 type
->tp_itemsize
= base
->tp_itemsize
;
2408 type
->tp_members
= PyHeapType_GET_MEMBERS(et
);
2410 if (type
->tp_weaklistoffset
&& type
->tp_dictoffset
)
2411 type
->tp_getset
= subtype_getsets_full
;
2412 else if (type
->tp_weaklistoffset
&& !type
->tp_dictoffset
)
2413 type
->tp_getset
= subtype_getsets_weakref_only
;
2414 else if (!type
->tp_weaklistoffset
&& type
->tp_dictoffset
)
2415 type
->tp_getset
= subtype_getsets_dict_only
;
2417 type
->tp_getset
= NULL
;
2419 /* Special case some slots */
2420 if (type
->tp_dictoffset
!= 0 || nslots
> 0) {
2421 if (base
->tp_getattr
== NULL
&& base
->tp_getattro
== NULL
)
2422 type
->tp_getattro
= PyObject_GenericGetAttr
;
2423 if (base
->tp_setattr
== NULL
&& base
->tp_setattro
== NULL
)
2424 type
->tp_setattro
= PyObject_GenericSetAttr
;
2426 type
->tp_dealloc
= subtype_dealloc
;
2428 /* Enable GC unless there are really no instance variables possible */
2429 if (!(type
->tp_basicsize
== sizeof(PyObject
) &&
2430 type
->tp_itemsize
== 0))
2431 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
2433 /* Always override allocation strategy to use regular heap */
2434 type
->tp_alloc
= PyType_GenericAlloc
;
2435 if (type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) {
2436 type
->tp_free
= PyObject_GC_Del
;
2437 type
->tp_traverse
= subtype_traverse
;
2438 type
->tp_clear
= subtype_clear
;
2441 type
->tp_free
= PyObject_Del
;
2443 /* Initialize the rest */
2444 if (PyType_Ready(type
) < 0) {
2449 /* Put the proper slots in place */
2450 fixup_slot_dispatchers(type
);
2452 return (PyObject
*)type
;
2455 /* Internal API to look for a name through the MRO.
2456 This returns a borrowed reference, and doesn't set an exception! */
2458 _PyType_Lookup(PyTypeObject
*type
, PyObject
*name
)
2461 PyObject
*mro
, *res
, *base
, *dict
;
2464 if (MCACHE_CACHEABLE_NAME(name
) &&
2465 PyType_HasFeature(type
, Py_TPFLAGS_VALID_VERSION_TAG
)) {
2467 h
= MCACHE_HASH_METHOD(type
, name
);
2468 if (method_cache
[h
].version
== type
->tp_version_tag
&&
2469 method_cache
[h
].name
== name
)
2470 return method_cache
[h
].value
;
2473 /* Look in tp_dict of types in MRO */
2476 /* If mro is NULL, the type is either not yet initialized
2477 by PyType_Ready(), or already cleared by type_clear().
2478 Either way the safest thing to do is to return NULL. */
2483 assert(PyTuple_Check(mro
));
2484 n
= PyTuple_GET_SIZE(mro
);
2485 for (i
= 0; i
< n
; i
++) {
2486 base
= PyTuple_GET_ITEM(mro
, i
);
2487 if (PyClass_Check(base
))
2488 dict
= ((PyClassObject
*)base
)->cl_dict
;
2490 assert(PyType_Check(base
));
2491 dict
= ((PyTypeObject
*)base
)->tp_dict
;
2493 assert(dict
&& PyDict_Check(dict
));
2494 res
= PyDict_GetItem(dict
, name
);
2499 if (MCACHE_CACHEABLE_NAME(name
) && assign_version_tag(type
)) {
2500 h
= MCACHE_HASH_METHOD(type
, name
);
2501 method_cache
[h
].version
= type
->tp_version_tag
;
2502 method_cache
[h
].value
= res
; /* borrowed */
2504 Py_DECREF(method_cache
[h
].name
);
2505 method_cache
[h
].name
= name
;
2510 /* This is similar to PyObject_GenericGetAttr(),
2511 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2513 type_getattro(PyTypeObject
*type
, PyObject
*name
)
2515 PyTypeObject
*metatype
= Py_TYPE(type
);
2516 PyObject
*meta_attribute
, *attribute
;
2517 descrgetfunc meta_get
;
2519 /* Initialize this type (we'll assume the metatype is initialized) */
2520 if (type
->tp_dict
== NULL
) {
2521 if (PyType_Ready(type
) < 0)
2525 /* No readable descriptor found yet */
2528 /* Look for the attribute in the metatype */
2529 meta_attribute
= _PyType_Lookup(metatype
, name
);
2531 if (meta_attribute
!= NULL
) {
2532 meta_get
= Py_TYPE(meta_attribute
)->tp_descr_get
;
2534 if (meta_get
!= NULL
&& PyDescr_IsData(meta_attribute
)) {
2535 /* Data descriptors implement tp_descr_set to intercept
2536 * writes. Assume the attribute is not overridden in
2537 * type's tp_dict (and bases): call the descriptor now.
2539 return meta_get(meta_attribute
, (PyObject
*)type
,
2540 (PyObject
*)metatype
);
2542 Py_INCREF(meta_attribute
);
2545 /* No data descriptor found on metatype. Look in tp_dict of this
2546 * type and its bases */
2547 attribute
= _PyType_Lookup(type
, name
);
2548 if (attribute
!= NULL
) {
2549 /* Implement descriptor functionality, if any */
2550 descrgetfunc local_get
= Py_TYPE(attribute
)->tp_descr_get
;
2552 Py_XDECREF(meta_attribute
);
2554 if (local_get
!= NULL
) {
2555 /* NULL 2nd argument indicates the descriptor was
2556 * found on the target object itself (or a base) */
2557 return local_get(attribute
, (PyObject
*)NULL
,
2561 Py_INCREF(attribute
);
2565 /* No attribute found in local __dict__ (or bases): use the
2566 * descriptor from the metatype, if any */
2567 if (meta_get
!= NULL
) {
2569 res
= meta_get(meta_attribute
, (PyObject
*)type
,
2570 (PyObject
*)metatype
);
2571 Py_DECREF(meta_attribute
);
2575 /* If an ordinary attribute was found on the metatype, return it now */
2576 if (meta_attribute
!= NULL
) {
2577 return meta_attribute
;
2581 PyErr_Format(PyExc_AttributeError
,
2582 "type object '%.50s' has no attribute '%.400s'",
2583 type
->tp_name
, PyString_AS_STRING(name
));
2588 type_setattro(PyTypeObject
*type
, PyObject
*name
, PyObject
*value
)
2590 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
2593 "can't set attributes of built-in/extension type '%s'",
2597 if (PyObject_GenericSetAttr((PyObject
*)type
, name
, value
) < 0)
2599 return update_slot(type
, name
);
2603 type_dealloc(PyTypeObject
*type
)
2605 PyHeapTypeObject
*et
;
2607 /* Assert this is a heap-allocated type object */
2608 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
2609 _PyObject_GC_UNTRACK(type
);
2610 PyObject_ClearWeakRefs((PyObject
*)type
);
2611 et
= (PyHeapTypeObject
*)type
;
2612 Py_XDECREF(type
->tp_base
);
2613 Py_XDECREF(type
->tp_dict
);
2614 Py_XDECREF(type
->tp_bases
);
2615 Py_XDECREF(type
->tp_mro
);
2616 Py_XDECREF(type
->tp_cache
);
2617 Py_XDECREF(type
->tp_subclasses
);
2618 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2619 * of most other objects. It's okay to cast it to char *.
2621 PyObject_Free((char *)type
->tp_doc
);
2622 Py_XDECREF(et
->ht_name
);
2623 Py_XDECREF(et
->ht_slots
);
2624 Py_TYPE(type
)->tp_free((PyObject
*)type
);
2628 type_subclasses(PyTypeObject
*type
, PyObject
*args_ignored
)
2630 PyObject
*list
, *raw
, *ref
;
2633 list
= PyList_New(0);
2636 raw
= type
->tp_subclasses
;
2639 assert(PyList_Check(raw
));
2640 n
= PyList_GET_SIZE(raw
);
2641 for (i
= 0; i
< n
; i
++) {
2642 ref
= PyList_GET_ITEM(raw
, i
);
2643 assert(PyWeakref_CheckRef(ref
));
2644 ref
= PyWeakref_GET_OBJECT(ref
);
2645 if (ref
!= Py_None
) {
2646 if (PyList_Append(list
, ref
) < 0) {
2655 static PyMethodDef type_methods
[] = {
2656 {"mro", (PyCFunction
)mro_external
, METH_NOARGS
,
2657 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2658 {"__subclasses__", (PyCFunction
)type_subclasses
, METH_NOARGS
,
2659 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2660 {"__instancecheck__", type___instancecheck__
, METH_O
,
2661 PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
2662 {"__subclasscheck__", type___subclasscheck__
, METH_O
,
2663 PyDoc_STR("__subclasschck__ -> check if an class is a subclass")},
2667 PyDoc_STRVAR(type_doc
,
2668 "type(object) -> the object's type\n"
2669 "type(name, bases, dict) -> a new type");
2672 type_traverse(PyTypeObject
*type
, visitproc visit
, void *arg
)
2674 /* Because of type_is_gc(), the collector only calls this
2676 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
2678 Py_VISIT(type
->tp_dict
);
2679 Py_VISIT(type
->tp_cache
);
2680 Py_VISIT(type
->tp_mro
);
2681 Py_VISIT(type
->tp_bases
);
2682 Py_VISIT(type
->tp_base
);
2684 /* There's no need to visit type->tp_subclasses or
2685 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2686 in cycles; tp_subclasses is a list of weak references,
2687 and slots is a tuple of strings. */
2693 type_clear(PyTypeObject
*type
)
2695 /* Because of type_is_gc(), the collector only calls this
2697 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
2699 /* The only field we need to clear is tp_mro, which is part of a
2700 hard cycle (its first element is the class itself) that won't
2701 be broken otherwise (it's a tuple and tuples don't have a
2702 tp_clear handler). None of the other fields need to be
2703 cleared, and here's why:
2706 It is a dict, so the collector will call its tp_clear.
2709 Not used; if it were, it would be a dict.
2712 If these are involved in a cycle, there must be at least
2713 one other, mutable object in the cycle, e.g. a base
2714 class's dict; the cycle will be broken that way.
2717 A list of weak references can't be part of a cycle; and
2718 lists have their own tp_clear.
2720 slots (in PyHeapTypeObject):
2721 A tuple of strings can't be part of a cycle.
2724 Py_CLEAR(type
->tp_mro
);
2730 type_is_gc(PyTypeObject
*type
)
2732 return type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
;
2735 PyTypeObject PyType_Type
= {
2736 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
2737 "type", /* tp_name */
2738 sizeof(PyHeapTypeObject
), /* tp_basicsize */
2739 sizeof(PyMemberDef
), /* tp_itemsize */
2740 (destructor
)type_dealloc
, /* tp_dealloc */
2744 type_compare
, /* tp_compare */
2745 (reprfunc
)type_repr
, /* tp_repr */
2746 0, /* tp_as_number */
2747 0, /* tp_as_sequence */
2748 0, /* tp_as_mapping */
2749 (hashfunc
)_Py_HashPointer
, /* tp_hash */
2750 (ternaryfunc
)type_call
, /* tp_call */
2752 (getattrofunc
)type_getattro
, /* tp_getattro */
2753 (setattrofunc
)type_setattro
, /* tp_setattro */
2754 0, /* tp_as_buffer */
2755 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
2756 Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_TYPE_SUBCLASS
, /* tp_flags */
2757 type_doc
, /* tp_doc */
2758 (traverseproc
)type_traverse
, /* tp_traverse */
2759 (inquiry
)type_clear
, /* tp_clear */
2760 type_richcompare
, /* tp_richcompare */
2761 offsetof(PyTypeObject
, tp_weaklist
), /* tp_weaklistoffset */
2763 0, /* tp_iternext */
2764 type_methods
, /* tp_methods */
2765 type_members
, /* tp_members */
2766 type_getsets
, /* tp_getset */
2769 0, /* tp_descr_get */
2770 0, /* tp_descr_set */
2771 offsetof(PyTypeObject
, tp_dict
), /* tp_dictoffset */
2772 type_init
, /* tp_init */
2774 type_new
, /* tp_new */
2775 PyObject_GC_Del
, /* tp_free */
2776 (inquiry
)type_is_gc
, /* tp_is_gc */
2780 /* The base type of all types (eventually)... except itself. */
2782 /* You may wonder why object.__new__() only complains about arguments
2783 when object.__init__() is not overridden, and vice versa.
2785 Consider the use cases:
2787 1. When neither is overridden, we want to hear complaints about
2788 excess (i.e., any) arguments, since their presence could
2789 indicate there's a bug.
2791 2. When defining an Immutable type, we are likely to override only
2792 __new__(), since __init__() is called too late to initialize an
2793 Immutable object. Since __new__() defines the signature for the
2794 type, it would be a pain to have to override __init__() just to
2795 stop it from complaining about excess arguments.
2797 3. When defining a Mutable type, we are likely to override only
2798 __init__(). So here the converse reasoning applies: we don't
2799 want to have to override __new__() just to stop it from
2802 4. When __init__() is overridden, and the subclass __init__() calls
2803 object.__init__(), the latter should complain about excess
2804 arguments; ditto for __new__().
2806 Use cases 2 and 3 make it unattractive to unconditionally check for
2807 excess arguments. The best solution that addresses all four use
2808 cases is as follows: __init__() complains about excess arguments
2809 unless __new__() is overridden and __init__() is not overridden
2810 (IOW, if __init__() is overridden or __new__() is not overridden);
2811 symmetrically, __new__() complains about excess arguments unless
2812 __init__() is overridden and __new__() is not overridden
2813 (IOW, if __new__() is overridden or __init__() is not overridden).
2815 However, for backwards compatibility, this breaks too much code.
2816 Therefore, in 2.6, we'll *warn* about excess arguments when both
2817 methods are overridden; for all other cases we'll use the above
2824 object_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
2827 excess_args(PyObject
*args
, PyObject
*kwds
)
2829 return PyTuple_GET_SIZE(args
) ||
2830 (kwds
&& PyDict_Check(kwds
) && PyDict_Size(kwds
));
2834 object_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2837 if (excess_args(args
, kwds
)) {
2838 PyTypeObject
*type
= Py_TYPE(self
);
2839 if (type
->tp_init
!= object_init
&&
2840 type
->tp_new
!= object_new
)
2842 err
= PyErr_WarnEx(PyExc_DeprecationWarning
,
2843 "object.__init__() takes no parameters",
2846 else if (type
->tp_init
!= object_init
||
2847 type
->tp_new
== object_new
)
2849 PyErr_SetString(PyExc_TypeError
,
2850 "object.__init__() takes no parameters");
2858 object_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2861 if (excess_args(args
, kwds
)) {
2862 if (type
->tp_new
!= object_new
&&
2863 type
->tp_init
!= object_init
)
2865 err
= PyErr_WarnEx(PyExc_DeprecationWarning
,
2866 "object.__new__() takes no parameters",
2869 else if (type
->tp_new
!= object_new
||
2870 type
->tp_init
== object_init
)
2872 PyErr_SetString(PyExc_TypeError
,
2873 "object.__new__() takes no parameters");
2880 if (type
->tp_flags
& Py_TPFLAGS_IS_ABSTRACT
) {
2881 static PyObject
*comma
= NULL
;
2882 PyObject
*abstract_methods
= NULL
;
2885 PyObject
*sorted_methods
= NULL
;
2886 PyObject
*joined
= NULL
;
2887 const char *joined_str
;
2889 /* Compute ", ".join(sorted(type.__abstractmethods__))
2891 abstract_methods
= type_abstractmethods(type
, NULL
);
2892 if (abstract_methods
== NULL
)
2894 builtins
= PyEval_GetBuiltins();
2895 if (builtins
== NULL
)
2897 sorted
= PyDict_GetItemString(builtins
, "sorted");
2900 sorted_methods
= PyObject_CallFunctionObjArgs(sorted
,
2903 if (sorted_methods
== NULL
)
2905 if (comma
== NULL
) {
2906 comma
= PyString_InternFromString(", ");
2910 joined
= PyObject_CallMethod(comma
, "join",
2911 "O", sorted_methods
);
2914 joined_str
= PyString_AsString(joined
);
2915 if (joined_str
== NULL
)
2918 PyErr_Format(PyExc_TypeError
,
2919 "Can't instantiate abstract class %s "
2920 "with abstract methods %s",
2925 Py_XDECREF(sorted_methods
);
2926 Py_XDECREF(abstract_methods
);
2929 return type
->tp_alloc(type
, 0);
2933 object_dealloc(PyObject
*self
)
2935 Py_TYPE(self
)->tp_free(self
);
2939 object_repr(PyObject
*self
)
2942 PyObject
*mod
, *name
, *rtn
;
2944 type
= Py_TYPE(self
);
2945 mod
= type_module(type
, NULL
);
2948 else if (!PyString_Check(mod
)) {
2952 name
= type_name(type
, NULL
);
2955 if (mod
!= NULL
&& strcmp(PyString_AS_STRING(mod
), "__builtin__"))
2956 rtn
= PyString_FromFormat("<%s.%s object at %p>",
2957 PyString_AS_STRING(mod
),
2958 PyString_AS_STRING(name
),
2961 rtn
= PyString_FromFormat("<%s object at %p>",
2962 type
->tp_name
, self
);
2969 object_str(PyObject
*self
)
2973 f
= Py_TYPE(self
)->tp_repr
;
2980 object_get_class(PyObject
*self
, void *closure
)
2982 Py_INCREF(Py_TYPE(self
));
2983 return (PyObject
*)(Py_TYPE(self
));
2987 equiv_structs(PyTypeObject
*a
, PyTypeObject
*b
)
2992 a
->tp_basicsize
== b
->tp_basicsize
&&
2993 a
->tp_itemsize
== b
->tp_itemsize
&&
2994 a
->tp_dictoffset
== b
->tp_dictoffset
&&
2995 a
->tp_weaklistoffset
== b
->tp_weaklistoffset
&&
2996 ((a
->tp_flags
& Py_TPFLAGS_HAVE_GC
) ==
2997 (b
->tp_flags
& Py_TPFLAGS_HAVE_GC
)));
3001 same_slots_added(PyTypeObject
*a
, PyTypeObject
*b
)
3003 PyTypeObject
*base
= a
->tp_base
;
3005 PyObject
*slots_a
, *slots_b
;
3007 if (base
!= b
->tp_base
)
3009 if (equiv_structs(a
, base
) && equiv_structs(b
, base
))
3011 size
= base
->tp_basicsize
;
3012 if (a
->tp_dictoffset
== size
&& b
->tp_dictoffset
== size
)
3013 size
+= sizeof(PyObject
*);
3014 if (a
->tp_weaklistoffset
== size
&& b
->tp_weaklistoffset
== size
)
3015 size
+= sizeof(PyObject
*);
3017 /* Check slots compliance */
3018 slots_a
= ((PyHeapTypeObject
*)a
)->ht_slots
;
3019 slots_b
= ((PyHeapTypeObject
*)b
)->ht_slots
;
3020 if (slots_a
&& slots_b
) {
3021 if (PyObject_Compare(slots_a
, slots_b
) != 0)
3023 size
+= sizeof(PyObject
*) * PyTuple_GET_SIZE(slots_a
);
3025 return size
== a
->tp_basicsize
&& size
== b
->tp_basicsize
;
3029 compatible_for_assignment(PyTypeObject
* oldto
, PyTypeObject
* newto
, char* attr
)
3031 PyTypeObject
*newbase
, *oldbase
;
3033 if (newto
->tp_dealloc
!= oldto
->tp_dealloc
||
3034 newto
->tp_free
!= oldto
->tp_free
)
3036 PyErr_Format(PyExc_TypeError
,
3038 "'%s' deallocator differs from '%s'",
3046 while (equiv_structs(newbase
, newbase
->tp_base
))
3047 newbase
= newbase
->tp_base
;
3048 while (equiv_structs(oldbase
, oldbase
->tp_base
))
3049 oldbase
= oldbase
->tp_base
;
3050 if (newbase
!= oldbase
&&
3051 (newbase
->tp_base
!= oldbase
->tp_base
||
3052 !same_slots_added(newbase
, oldbase
))) {
3053 PyErr_Format(PyExc_TypeError
,
3055 "'%s' object layout differs from '%s'",
3066 object_set_class(PyObject
*self
, PyObject
*value
, void *closure
)
3068 PyTypeObject
*oldto
= Py_TYPE(self
);
3069 PyTypeObject
*newto
;
3071 if (value
== NULL
) {
3072 PyErr_SetString(PyExc_TypeError
,
3073 "can't delete __class__ attribute");
3076 if (!PyType_Check(value
)) {
3077 PyErr_Format(PyExc_TypeError
,
3078 "__class__ must be set to new-style class, not '%s' object",
3079 Py_TYPE(value
)->tp_name
);
3082 newto
= (PyTypeObject
*)value
;
3083 if (!(newto
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) ||
3084 !(oldto
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
3086 PyErr_Format(PyExc_TypeError
,
3087 "__class__ assignment: only for heap types");
3090 if (compatible_for_assignment(newto
, oldto
, "__class__")) {
3092 Py_TYPE(self
) = newto
;
3101 static PyGetSetDef object_getsets
[] = {
3102 {"__class__", object_get_class
, object_set_class
,
3103 PyDoc_STR("the object's class")},
3108 /* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
3109 We fall back to helpers in copy_reg for:
3110 - pickle protocols < 2
3111 - calculating the list of slot names (done only once per class)
3112 - the __newobj__ function (which is used as a token but never called)
3116 import_copyreg(void)
3118 static PyObject
*copyreg_str
;
3121 copyreg_str
= PyString_InternFromString("copy_reg");
3122 if (copyreg_str
== NULL
)
3126 return PyImport_Import(copyreg_str
);
3130 slotnames(PyObject
*cls
)
3134 PyObject
*slotnames
;
3136 if (!PyType_Check(cls
)) {
3141 clsdict
= ((PyTypeObject
*)cls
)->tp_dict
;
3142 slotnames
= PyDict_GetItemString(clsdict
, "__slotnames__");
3143 if (slotnames
!= NULL
&& PyList_Check(slotnames
)) {
3144 Py_INCREF(slotnames
);
3148 copyreg
= import_copyreg();
3149 if (copyreg
== NULL
)
3152 slotnames
= PyObject_CallMethod(copyreg
, "_slotnames", "O", cls
);
3154 if (slotnames
!= NULL
&&
3155 slotnames
!= Py_None
&&
3156 !PyList_Check(slotnames
))
3158 PyErr_SetString(PyExc_TypeError
,
3159 "copy_reg._slotnames didn't return a list or None");
3160 Py_DECREF(slotnames
);
3168 reduce_2(PyObject
*obj
)
3170 PyObject
*cls
, *getnewargs
;
3171 PyObject
*args
= NULL
, *args2
= NULL
;
3172 PyObject
*getstate
= NULL
, *state
= NULL
, *names
= NULL
;
3173 PyObject
*slots
= NULL
, *listitems
= NULL
, *dictitems
= NULL
;
3174 PyObject
*copyreg
= NULL
, *newobj
= NULL
, *res
= NULL
;
3177 cls
= PyObject_GetAttrString(obj
, "__class__");
3181 getnewargs
= PyObject_GetAttrString(obj
, "__getnewargs__");
3182 if (getnewargs
!= NULL
) {
3183 args
= PyObject_CallObject(getnewargs
, NULL
);
3184 Py_DECREF(getnewargs
);
3185 if (args
!= NULL
&& !PyTuple_Check(args
)) {
3186 PyErr_Format(PyExc_TypeError
,
3187 "__getnewargs__ should return a tuple, "
3188 "not '%.200s'", Py_TYPE(args
)->tp_name
);
3194 args
= PyTuple_New(0);
3199 getstate
= PyObject_GetAttrString(obj
, "__getstate__");
3200 if (getstate
!= NULL
) {
3201 state
= PyObject_CallObject(getstate
, NULL
);
3202 Py_DECREF(getstate
);
3208 state
= PyObject_GetAttrString(obj
, "__dict__");
3209 if (state
== NULL
) {
3214 names
= slotnames(cls
);
3217 if (names
!= Py_None
) {
3218 assert(PyList_Check(names
));
3219 slots
= PyDict_New();
3223 /* Can't pre-compute the list size; the list
3224 is stored on the class so accessible to other
3225 threads, which may be run by DECREF */
3226 for (i
= 0; i
< PyList_GET_SIZE(names
); i
++) {
3227 PyObject
*name
, *value
;
3228 name
= PyList_GET_ITEM(names
, i
);
3229 value
= PyObject_GetAttr(obj
, name
);
3233 int err
= PyDict_SetItem(slots
, name
,
3242 state
= Py_BuildValue("(NO)", state
, slots
);
3249 if (!PyList_Check(obj
)) {
3250 listitems
= Py_None
;
3251 Py_INCREF(listitems
);
3254 listitems
= PyObject_GetIter(obj
);
3255 if (listitems
== NULL
)
3259 if (!PyDict_Check(obj
)) {
3260 dictitems
= Py_None
;
3261 Py_INCREF(dictitems
);
3264 dictitems
= PyObject_CallMethod(obj
, "iteritems", "");
3265 if (dictitems
== NULL
)
3269 copyreg
= import_copyreg();
3270 if (copyreg
== NULL
)
3272 newobj
= PyObject_GetAttrString(copyreg
, "__newobj__");
3276 n
= PyTuple_GET_SIZE(args
);
3277 args2
= PyTuple_New(n
+1);
3280 PyTuple_SET_ITEM(args2
, 0, cls
);
3282 for (i
= 0; i
< n
; i
++) {
3283 PyObject
*v
= PyTuple_GET_ITEM(args
, i
);
3285 PyTuple_SET_ITEM(args2
, i
+1, v
);
3288 res
= PyTuple_Pack(5, newobj
, args2
, state
, listitems
, dictitems
);
3297 Py_XDECREF(listitems
);
3298 Py_XDECREF(dictitems
);
3299 Py_XDECREF(copyreg
);
3305 * There were two problems when object.__reduce__ and object.__reduce_ex__
3306 * were implemented in the same function:
3307 * - trying to pickle an object with a custom __reduce__ method that
3308 * fell back to object.__reduce__ in certain circumstances led to
3309 * infinite recursion at Python level and eventual RuntimeError.
3310 * - Pickling objects that lied about their type by overwriting the
3311 * __class__ descriptor could lead to infinite recursion at C level
3312 * and eventual segfault.
3314 * Because of backwards compatibility, the two methods still have to
3315 * behave in the same way, even if this is not required by the pickle
3316 * protocol. This common functionality was moved to the _common_reduce
3320 _common_reduce(PyObject
*self
, int proto
)
3322 PyObject
*copyreg
, *res
;
3325 return reduce_2(self
);
3327 copyreg
= import_copyreg();
3331 res
= PyEval_CallMethod(copyreg
, "_reduce_ex", "(Oi)", self
, proto
);
3338 object_reduce(PyObject
*self
, PyObject
*args
)
3342 if (!PyArg_ParseTuple(args
, "|i:__reduce__", &proto
))
3345 return _common_reduce(self
, proto
);
3349 object_reduce_ex(PyObject
*self
, PyObject
*args
)
3351 PyObject
*reduce
, *res
;
3354 if (!PyArg_ParseTuple(args
, "|i:__reduce_ex__", &proto
))
3357 reduce
= PyObject_GetAttrString(self
, "__reduce__");
3361 PyObject
*cls
, *clsreduce
, *objreduce
;
3363 cls
= PyObject_GetAttrString(self
, "__class__");
3368 clsreduce
= PyObject_GetAttrString(cls
, "__reduce__");
3370 if (clsreduce
== NULL
) {
3374 objreduce
= PyDict_GetItemString(PyBaseObject_Type
.tp_dict
,
3376 override
= (clsreduce
!= objreduce
);
3377 Py_DECREF(clsreduce
);
3379 res
= PyObject_CallObject(reduce
, NULL
);
3387 return _common_reduce(self
, proto
);
3391 object_subclasshook(PyObject
*cls
, PyObject
*args
)
3393 Py_INCREF(Py_NotImplemented
);
3394 return Py_NotImplemented
;
3397 PyDoc_STRVAR(object_subclasshook_doc
,
3398 "Abstract classes can override this to customize issubclass().\n"
3400 "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3401 "It should return True, False or NotImplemented. If it returns\n"
3402 "NotImplemented, the normal algorithm is used. Otherwise, it\n"
3403 "overrides the normal algorithm (and the outcome is cached).\n");
3406 from PEP 3101, this code implements:
3409 def __format__(self, format_spec):
3410 if isinstance(format_spec, str):
3411 return format(str(self), format_spec)
3412 elif isinstance(format_spec, unicode):
3413 return format(unicode(self), format_spec)
3416 object_format(PyObject
*self
, PyObject
*args
)
3418 PyObject
*format_spec
;
3419 PyObject
*self_as_str
= NULL
;
3420 PyObject
*result
= NULL
;
3421 PyObject
*format_meth
= NULL
;
3423 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
3425 #ifdef Py_USING_UNICODE
3426 if (PyUnicode_Check(format_spec
)) {
3427 self_as_str
= PyObject_Unicode(self
);
3428 } else if (PyString_Check(format_spec
)) {
3430 if (PyString_Check(format_spec
)) {
3432 self_as_str
= PyObject_Str(self
);
3434 PyErr_SetString(PyExc_TypeError
, "argument to __format__ must be unicode or str");
3438 if (self_as_str
!= NULL
) {
3439 /* find the format function */
3440 format_meth
= PyObject_GetAttrString(self_as_str
, "__format__");
3441 if (format_meth
!= NULL
) {
3443 result
= PyObject_CallFunctionObjArgs(format_meth
, format_spec
, NULL
);
3447 Py_XDECREF(self_as_str
);
3448 Py_XDECREF(format_meth
);
3454 object_sizeof(PyObject
*self
, PyObject
*args
)
3456 Py_ssize_t res
, isize
;
3459 isize
= self
->ob_type
->tp_itemsize
;
3461 res
= self
->ob_type
->ob_size
* isize
;
3462 res
+= self
->ob_type
->tp_basicsize
;
3464 return PyInt_FromSsize_t(res
);
3467 static PyMethodDef object_methods
[] = {
3468 {"__reduce_ex__", object_reduce_ex
, METH_VARARGS
,
3469 PyDoc_STR("helper for pickle")},
3470 {"__reduce__", object_reduce
, METH_VARARGS
,
3471 PyDoc_STR("helper for pickle")},
3472 {"__subclasshook__", object_subclasshook
, METH_CLASS
| METH_VARARGS
,
3473 object_subclasshook_doc
},
3474 {"__format__", object_format
, METH_VARARGS
,
3475 PyDoc_STR("default object formatter")},
3476 {"__sizeof__", object_sizeof
, METH_NOARGS
,
3477 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
3482 PyTypeObject PyBaseObject_Type
= {
3483 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
3484 "object", /* tp_name */
3485 sizeof(PyObject
), /* tp_basicsize */
3486 0, /* tp_itemsize */
3487 object_dealloc
, /* tp_dealloc */
3492 object_repr
, /* tp_repr */
3493 0, /* tp_as_number */
3494 0, /* tp_as_sequence */
3495 0, /* tp_as_mapping */
3496 (hashfunc
)_Py_HashPointer
, /* tp_hash */
3498 object_str
, /* tp_str */
3499 PyObject_GenericGetAttr
, /* tp_getattro */
3500 PyObject_GenericSetAttr
, /* tp_setattro */
3501 0, /* tp_as_buffer */
3502 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
3503 PyDoc_STR("The most base type"), /* tp_doc */
3504 0, /* tp_traverse */
3506 0, /* tp_richcompare */
3507 0, /* tp_weaklistoffset */
3509 0, /* tp_iternext */
3510 object_methods
, /* tp_methods */
3512 object_getsets
, /* tp_getset */
3515 0, /* tp_descr_get */
3516 0, /* tp_descr_set */
3517 0, /* tp_dictoffset */
3518 object_init
, /* tp_init */
3519 PyType_GenericAlloc
, /* tp_alloc */
3520 object_new
, /* tp_new */
3521 PyObject_Del
, /* tp_free */
3525 /* Initialize the __dict__ in a type object */
3528 add_methods(PyTypeObject
*type
, PyMethodDef
*meth
)
3530 PyObject
*dict
= type
->tp_dict
;
3532 for (; meth
->ml_name
!= NULL
; meth
++) {
3534 if (PyDict_GetItemString(dict
, meth
->ml_name
) &&
3535 !(meth
->ml_flags
& METH_COEXIST
))
3537 if (meth
->ml_flags
& METH_CLASS
) {
3538 if (meth
->ml_flags
& METH_STATIC
) {
3539 PyErr_SetString(PyExc_ValueError
,
3540 "method cannot be both class and static");
3543 descr
= PyDescr_NewClassMethod(type
, meth
);
3545 else if (meth
->ml_flags
& METH_STATIC
) {
3546 PyObject
*cfunc
= PyCFunction_New(meth
, NULL
);
3549 descr
= PyStaticMethod_New(cfunc
);
3553 descr
= PyDescr_NewMethod(type
, meth
);
3557 if (PyDict_SetItemString(dict
, meth
->ml_name
, descr
) < 0)
3565 add_members(PyTypeObject
*type
, PyMemberDef
*memb
)
3567 PyObject
*dict
= type
->tp_dict
;
3569 for (; memb
->name
!= NULL
; memb
++) {
3571 if (PyDict_GetItemString(dict
, memb
->name
))
3573 descr
= PyDescr_NewMember(type
, memb
);
3576 if (PyDict_SetItemString(dict
, memb
->name
, descr
) < 0)
3584 add_getset(PyTypeObject
*type
, PyGetSetDef
*gsp
)
3586 PyObject
*dict
= type
->tp_dict
;
3588 for (; gsp
->name
!= NULL
; gsp
++) {
3590 if (PyDict_GetItemString(dict
, gsp
->name
))
3592 descr
= PyDescr_NewGetSet(type
, gsp
);
3596 if (PyDict_SetItemString(dict
, gsp
->name
, descr
) < 0)
3603 #define BUFFER_FLAGS (Py_TPFLAGS_HAVE_GETCHARBUFFER | Py_TPFLAGS_HAVE_NEWBUFFER)
3606 inherit_special(PyTypeObject
*type
, PyTypeObject
*base
)
3608 Py_ssize_t oldsize
, newsize
;
3610 /* Special flag magic */
3611 if (!type
->tp_as_buffer
&& base
->tp_as_buffer
) {
3612 type
->tp_flags
&= ~BUFFER_FLAGS
;
3614 base
->tp_flags
& BUFFER_FLAGS
;
3616 if (!type
->tp_as_sequence
&& base
->tp_as_sequence
) {
3617 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_SEQUENCE_IN
;
3618 type
->tp_flags
|= base
->tp_flags
& Py_TPFLAGS_HAVE_SEQUENCE_IN
;
3620 if ((type
->tp_flags
& Py_TPFLAGS_HAVE_INPLACEOPS
) !=
3621 (base
->tp_flags
& Py_TPFLAGS_HAVE_INPLACEOPS
)) {
3622 if ((!type
->tp_as_number
&& base
->tp_as_number
) ||
3623 (!type
->tp_as_sequence
&& base
->tp_as_sequence
)) {
3624 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_INPLACEOPS
;
3625 if (!type
->tp_as_number
&& !type
->tp_as_sequence
) {
3626 type
->tp_flags
|= base
->tp_flags
&
3627 Py_TPFLAGS_HAVE_INPLACEOPS
;
3632 if (!type
->tp_as_number
&& base
->tp_as_number
) {
3633 type
->tp_flags
&= ~Py_TPFLAGS_CHECKTYPES
;
3634 type
->tp_flags
|= base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
;
3637 /* Copying basicsize is connected to the GC flags */
3638 oldsize
= base
->tp_basicsize
;
3639 newsize
= type
->tp_basicsize
? type
->tp_basicsize
: oldsize
;
3640 if (!(type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
3641 (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
3642 (type
->tp_flags
& Py_TPFLAGS_HAVE_RICHCOMPARE
/*GC slots exist*/) &&
3643 (!type
->tp_traverse
&& !type
->tp_clear
)) {
3644 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
3645 if (type
->tp_traverse
== NULL
)
3646 type
->tp_traverse
= base
->tp_traverse
;
3647 if (type
->tp_clear
== NULL
)
3648 type
->tp_clear
= base
->tp_clear
;
3650 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
3651 /* The condition below could use some explanation.
3652 It appears that tp_new is not inherited for static types
3653 whose base class is 'object'; this seems to be a precaution
3654 so that old extension types don't suddenly become
3655 callable (object.__new__ wouldn't insure the invariants
3656 that the extension type's own factory function ensures).
3657 Heap types, of course, are under our control, so they do
3658 inherit tp_new; static extension types that specify some
3659 other built-in type as the default are considered
3660 new-style-aware so they also inherit object.__new__. */
3661 if (base
!= &PyBaseObject_Type
||
3662 (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
3663 if (type
->tp_new
== NULL
)
3664 type
->tp_new
= base
->tp_new
;
3667 type
->tp_basicsize
= newsize
;
3669 /* Copy other non-function slots */
3672 #define COPYVAL(SLOT) \
3673 if (type->SLOT == 0) type->SLOT = base->SLOT
3675 COPYVAL(tp_itemsize
);
3676 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_WEAKREFS
) {
3677 COPYVAL(tp_weaklistoffset
);
3679 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
3680 COPYVAL(tp_dictoffset
);
3683 /* Setup fast subclass flags */
3684 if (PyType_IsSubtype(base
, (PyTypeObject
*)PyExc_BaseException
))
3685 type
->tp_flags
|= Py_TPFLAGS_BASE_EXC_SUBCLASS
;
3686 else if (PyType_IsSubtype(base
, &PyType_Type
))
3687 type
->tp_flags
|= Py_TPFLAGS_TYPE_SUBCLASS
;
3688 else if (PyType_IsSubtype(base
, &PyInt_Type
))
3689 type
->tp_flags
|= Py_TPFLAGS_INT_SUBCLASS
;
3690 else if (PyType_IsSubtype(base
, &PyLong_Type
))
3691 type
->tp_flags
|= Py_TPFLAGS_LONG_SUBCLASS
;
3692 else if (PyType_IsSubtype(base
, &PyString_Type
))
3693 type
->tp_flags
|= Py_TPFLAGS_STRING_SUBCLASS
;
3694 #ifdef Py_USING_UNICODE
3695 else if (PyType_IsSubtype(base
, &PyUnicode_Type
))
3696 type
->tp_flags
|= Py_TPFLAGS_UNICODE_SUBCLASS
;
3698 else if (PyType_IsSubtype(base
, &PyTuple_Type
))
3699 type
->tp_flags
|= Py_TPFLAGS_TUPLE_SUBCLASS
;
3700 else if (PyType_IsSubtype(base
, &PyList_Type
))
3701 type
->tp_flags
|= Py_TPFLAGS_LIST_SUBCLASS
;
3702 else if (PyType_IsSubtype(base
, &PyDict_Type
))
3703 type
->tp_flags
|= Py_TPFLAGS_DICT_SUBCLASS
;
3707 overrides_name(PyTypeObject
*type
, char *name
)
3709 PyObject
*dict
= type
->tp_dict
;
3711 assert(dict
!= NULL
);
3712 if (PyDict_GetItemString(dict
, name
) != NULL
) {
3718 #define OVERRIDES_HASH(x) overrides_name(x, "__hash__")
3719 #define OVERRIDES_CMP(x) overrides_name(x, "__cmp__")
3720 #define OVERRIDES_EQ(x) overrides_name(x, "__eq__")
3723 inherit_slots(PyTypeObject
*type
, PyTypeObject
*base
)
3725 PyTypeObject
*basebase
;
3734 #define SLOTDEFINED(SLOT) \
3735 (base->SLOT != 0 && \
3736 (basebase == NULL || base->SLOT != basebase->SLOT))
3738 #define COPYSLOT(SLOT) \
3739 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
3741 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3742 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3743 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
3744 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
3746 /* This won't inherit indirect slots (from tp_as_number etc.)
3747 if type doesn't provide the space. */
3749 if (type
->tp_as_number
!= NULL
&& base
->tp_as_number
!= NULL
) {
3750 basebase
= base
->tp_base
;
3751 if (basebase
->tp_as_number
== NULL
)
3754 COPYNUM(nb_subtract
);
3755 COPYNUM(nb_multiply
);
3757 COPYNUM(nb_remainder
);
3760 COPYNUM(nb_negative
);
3761 COPYNUM(nb_positive
);
3762 COPYNUM(nb_absolute
);
3763 COPYNUM(nb_nonzero
);
3776 COPYNUM(nb_inplace_add
);
3777 COPYNUM(nb_inplace_subtract
);
3778 COPYNUM(nb_inplace_multiply
);
3779 COPYNUM(nb_inplace_divide
);
3780 COPYNUM(nb_inplace_remainder
);
3781 COPYNUM(nb_inplace_power
);
3782 COPYNUM(nb_inplace_lshift
);
3783 COPYNUM(nb_inplace_rshift
);
3784 COPYNUM(nb_inplace_and
);
3785 COPYNUM(nb_inplace_xor
);
3786 COPYNUM(nb_inplace_or
);
3787 if (base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) {
3788 COPYNUM(nb_true_divide
);
3789 COPYNUM(nb_floor_divide
);
3790 COPYNUM(nb_inplace_true_divide
);
3791 COPYNUM(nb_inplace_floor_divide
);
3793 if (base
->tp_flags
& Py_TPFLAGS_HAVE_INDEX
) {
3798 if (type
->tp_as_sequence
!= NULL
&& base
->tp_as_sequence
!= NULL
) {
3799 basebase
= base
->tp_base
;
3800 if (basebase
->tp_as_sequence
== NULL
)
3807 COPYSEQ(sq_ass_item
);
3808 COPYSEQ(sq_ass_slice
);
3809 COPYSEQ(sq_contains
);
3810 COPYSEQ(sq_inplace_concat
);
3811 COPYSEQ(sq_inplace_repeat
);
3814 if (type
->tp_as_mapping
!= NULL
&& base
->tp_as_mapping
!= NULL
) {
3815 basebase
= base
->tp_base
;
3816 if (basebase
->tp_as_mapping
== NULL
)
3819 COPYMAP(mp_subscript
);
3820 COPYMAP(mp_ass_subscript
);
3823 if (type
->tp_as_buffer
!= NULL
&& base
->tp_as_buffer
!= NULL
) {
3824 basebase
= base
->tp_base
;
3825 if (basebase
->tp_as_buffer
== NULL
)
3827 COPYBUF(bf_getreadbuffer
);
3828 COPYBUF(bf_getwritebuffer
);
3829 COPYBUF(bf_getsegcount
);
3830 COPYBUF(bf_getcharbuffer
);
3831 COPYBUF(bf_getbuffer
);
3832 COPYBUF(bf_releasebuffer
);
3835 basebase
= base
->tp_base
;
3837 COPYSLOT(tp_dealloc
);
3839 if (type
->tp_getattr
== NULL
&& type
->tp_getattro
== NULL
) {
3840 type
->tp_getattr
= base
->tp_getattr
;
3841 type
->tp_getattro
= base
->tp_getattro
;
3843 if (type
->tp_setattr
== NULL
&& type
->tp_setattro
== NULL
) {
3844 type
->tp_setattr
= base
->tp_setattr
;
3845 type
->tp_setattro
= base
->tp_setattro
;
3847 /* tp_compare see tp_richcompare */
3849 /* tp_hash see tp_richcompare */
3852 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_RICHCOMPARE
) {
3853 if (type
->tp_compare
== NULL
&&
3854 type
->tp_richcompare
== NULL
&&
3855 type
->tp_hash
== NULL
)
3857 type
->tp_compare
= base
->tp_compare
;
3858 type
->tp_richcompare
= base
->tp_richcompare
;
3859 type
->tp_hash
= base
->tp_hash
;
3860 /* Check for changes to inherited methods in Py3k*/
3861 if (Py_Py3kWarningFlag
) {
3862 if (base
->tp_hash
&&
3863 (base
->tp_hash
!= PyObject_HashNotImplemented
) &&
3864 !OVERRIDES_HASH(type
)) {
3865 if (OVERRIDES_CMP(type
)) {
3866 PyErr_WarnPy3k("Overriding "
3867 "__cmp__ blocks inheritance "
3868 "of __hash__ in 3.x",
3871 if (OVERRIDES_EQ(type
)) {
3872 PyErr_WarnPy3k("Overriding "
3873 "__eq__ blocks inheritance "
3874 "of __hash__ in 3.x",
3882 COPYSLOT(tp_compare
);
3884 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_ITER
) {
3886 COPYSLOT(tp_iternext
);
3888 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
3889 COPYSLOT(tp_descr_get
);
3890 COPYSLOT(tp_descr_set
);
3891 COPYSLOT(tp_dictoffset
);
3895 if ((type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) ==
3896 (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
)) {
3897 /* They agree about gc. */
3900 else if ((type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
3901 type
->tp_free
== NULL
&&
3902 base
->tp_free
== _PyObject_Del
) {
3903 /* A bit of magic to plug in the correct default
3904 * tp_free function when a derived class adds gc,
3905 * didn't define tp_free, and the base uses the
3906 * default non-gc tp_free.
3908 type
->tp_free
= PyObject_GC_Del
;
3910 /* else they didn't agree about gc, and there isn't something
3911 * obvious to be done -- the type is on its own.
3916 static int add_operators(PyTypeObject
*);
3919 PyType_Ready(PyTypeObject
*type
)
3921 PyObject
*dict
, *bases
;
3925 if (type
->tp_flags
& Py_TPFLAGS_READY
) {
3926 assert(type
->tp_dict
!= NULL
);
3929 assert((type
->tp_flags
& Py_TPFLAGS_READYING
) == 0);
3931 type
->tp_flags
|= Py_TPFLAGS_READYING
;
3933 #ifdef Py_TRACE_REFS
3934 /* PyType_Ready is the closest thing we have to a choke point
3935 * for type objects, so is the best place I can think of to try
3936 * to get type objects into the doubly-linked list of all objects.
3937 * Still, not all type objects go thru PyType_Ready.
3939 _Py_AddToAllObjects((PyObject
*)type
, 0);
3942 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3943 base
= type
->tp_base
;
3944 if (base
== NULL
&& type
!= &PyBaseObject_Type
) {
3945 base
= type
->tp_base
= &PyBaseObject_Type
;
3949 /* Now the only way base can still be NULL is if type is
3950 * &PyBaseObject_Type.
3953 /* Initialize the base class */
3954 if (base
&& base
->tp_dict
== NULL
) {
3955 if (PyType_Ready(base
) < 0)
3959 /* Initialize ob_type if NULL. This means extensions that want to be
3960 compilable separately on Windows can call PyType_Ready() instead of
3961 initializing the ob_type field of their type objects. */
3962 /* The test for base != NULL is really unnecessary, since base is only
3963 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3964 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3966 if (Py_TYPE(type
) == NULL
&& base
!= NULL
)
3967 Py_TYPE(type
) = Py_TYPE(base
);
3969 /* Initialize tp_bases */
3970 bases
= type
->tp_bases
;
3971 if (bases
== NULL
) {
3973 bases
= PyTuple_New(0);
3975 bases
= PyTuple_Pack(1, base
);
3978 type
->tp_bases
= bases
;
3981 /* Initialize tp_dict */
3982 dict
= type
->tp_dict
;
3984 dict
= PyDict_New();
3987 type
->tp_dict
= dict
;
3990 /* Add type-specific descriptors to tp_dict */
3991 if (add_operators(type
) < 0)
3993 if (type
->tp_methods
!= NULL
) {
3994 if (add_methods(type
, type
->tp_methods
) < 0)
3997 if (type
->tp_members
!= NULL
) {
3998 if (add_members(type
, type
->tp_members
) < 0)
4001 if (type
->tp_getset
!= NULL
) {
4002 if (add_getset(type
, type
->tp_getset
) < 0)
4006 /* Calculate method resolution order */
4007 if (mro_internal(type
) < 0) {
4011 /* Inherit special flags from dominant base */
4012 if (type
->tp_base
!= NULL
)
4013 inherit_special(type
, type
->tp_base
);
4015 /* Initialize tp_dict properly */
4016 bases
= type
->tp_mro
;
4017 assert(bases
!= NULL
);
4018 assert(PyTuple_Check(bases
));
4019 n
= PyTuple_GET_SIZE(bases
);
4020 for (i
= 1; i
< n
; i
++) {
4021 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
4022 if (PyType_Check(b
))
4023 inherit_slots(type
, (PyTypeObject
*)b
);
4026 /* Sanity check for tp_free. */
4027 if (PyType_IS_GC(type
) && (type
->tp_flags
& Py_TPFLAGS_BASETYPE
) &&
4028 (type
->tp_free
== NULL
|| type
->tp_free
== PyObject_Del
)) {
4029 /* This base class needs to call tp_free, but doesn't have
4030 * one, or its tp_free is for non-gc'ed objects.
4032 PyErr_Format(PyExc_TypeError
, "type '%.100s' participates in "
4033 "gc and is a base type but has inappropriate "
4039 /* if the type dictionary doesn't contain a __doc__, set it from
4042 if (PyDict_GetItemString(type
->tp_dict
, "__doc__") == NULL
) {
4043 if (type
->tp_doc
!= NULL
) {
4044 PyObject
*doc
= PyString_FromString(type
->tp_doc
);
4047 PyDict_SetItemString(type
->tp_dict
, "__doc__", doc
);
4050 PyDict_SetItemString(type
->tp_dict
,
4051 "__doc__", Py_None
);
4055 /* Some more special stuff */
4056 base
= type
->tp_base
;
4058 if (type
->tp_as_number
== NULL
)
4059 type
->tp_as_number
= base
->tp_as_number
;
4060 if (type
->tp_as_sequence
== NULL
)
4061 type
->tp_as_sequence
= base
->tp_as_sequence
;
4062 if (type
->tp_as_mapping
== NULL
)
4063 type
->tp_as_mapping
= base
->tp_as_mapping
;
4064 if (type
->tp_as_buffer
== NULL
)
4065 type
->tp_as_buffer
= base
->tp_as_buffer
;
4068 /* Link into each base class's list of subclasses */
4069 bases
= type
->tp_bases
;
4070 n
= PyTuple_GET_SIZE(bases
);
4071 for (i
= 0; i
< n
; i
++) {
4072 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
4073 if (PyType_Check(b
) &&
4074 add_subclass((PyTypeObject
*)b
, type
) < 0)
4078 /* All done -- set the ready flag */
4079 assert(type
->tp_dict
!= NULL
);
4081 (type
->tp_flags
& ~Py_TPFLAGS_READYING
) | Py_TPFLAGS_READY
;
4085 type
->tp_flags
&= ~Py_TPFLAGS_READYING
;
4090 add_subclass(PyTypeObject
*base
, PyTypeObject
*type
)
4094 PyObject
*list
, *ref
, *newobj
;
4096 list
= base
->tp_subclasses
;
4098 base
->tp_subclasses
= list
= PyList_New(0);
4102 assert(PyList_Check(list
));
4103 newobj
= PyWeakref_NewRef((PyObject
*)type
, NULL
);
4104 i
= PyList_GET_SIZE(list
);
4106 ref
= PyList_GET_ITEM(list
, i
);
4107 assert(PyWeakref_CheckRef(ref
));
4108 if (PyWeakref_GET_OBJECT(ref
) == Py_None
)
4109 return PyList_SetItem(list
, i
, newobj
);
4111 result
= PyList_Append(list
, newobj
);
4117 remove_subclass(PyTypeObject
*base
, PyTypeObject
*type
)
4120 PyObject
*list
, *ref
;
4122 list
= base
->tp_subclasses
;
4126 assert(PyList_Check(list
));
4127 i
= PyList_GET_SIZE(list
);
4129 ref
= PyList_GET_ITEM(list
, i
);
4130 assert(PyWeakref_CheckRef(ref
));
4131 if (PyWeakref_GET_OBJECT(ref
) == (PyObject
*)type
) {
4132 /* this can't fail, right? */
4133 PySequence_DelItem(list
, i
);
4140 check_num_args(PyObject
*ob
, int n
)
4142 if (!PyTuple_CheckExact(ob
)) {
4143 PyErr_SetString(PyExc_SystemError
,
4144 "PyArg_UnpackTuple() argument list is not a tuple");
4147 if (n
== PyTuple_GET_SIZE(ob
))
4151 "expected %d arguments, got %zd", n
, PyTuple_GET_SIZE(ob
));
4155 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
4157 /* There's a wrapper *function* for each distinct function typedef used
4158 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
4159 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4160 Most tables have only one entry; the tables for binary operators have two
4161 entries, one regular and one with reversed arguments. */
4164 wrap_lenfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4166 lenfunc func
= (lenfunc
)wrapped
;
4169 if (!check_num_args(args
, 0))
4171 res
= (*func
)(self
);
4172 if (res
== -1 && PyErr_Occurred())
4174 return PyInt_FromLong((long)res
);
4178 wrap_inquirypred(PyObject
*self
, PyObject
*args
, void *wrapped
)
4180 inquiry func
= (inquiry
)wrapped
;
4183 if (!check_num_args(args
, 0))
4185 res
= (*func
)(self
);
4186 if (res
== -1 && PyErr_Occurred())
4188 return PyBool_FromLong((long)res
);
4192 wrap_binaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4194 binaryfunc func
= (binaryfunc
)wrapped
;
4197 if (!check_num_args(args
, 1))
4199 other
= PyTuple_GET_ITEM(args
, 0);
4200 return (*func
)(self
, other
);
4204 wrap_binaryfunc_l(PyObject
*self
, PyObject
*args
, void *wrapped
)
4206 binaryfunc func
= (binaryfunc
)wrapped
;
4209 if (!check_num_args(args
, 1))
4211 other
= PyTuple_GET_ITEM(args
, 0);
4212 if (!(self
->ob_type
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) &&
4213 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
4214 Py_INCREF(Py_NotImplemented
);
4215 return Py_NotImplemented
;
4217 return (*func
)(self
, other
);
4221 wrap_binaryfunc_r(PyObject
*self
, PyObject
*args
, void *wrapped
)
4223 binaryfunc func
= (binaryfunc
)wrapped
;
4226 if (!check_num_args(args
, 1))
4228 other
= PyTuple_GET_ITEM(args
, 0);
4229 if (!(self
->ob_type
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) &&
4230 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
4231 Py_INCREF(Py_NotImplemented
);
4232 return Py_NotImplemented
;
4234 return (*func
)(other
, self
);
4238 wrap_coercefunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4240 coercion func
= (coercion
)wrapped
;
4241 PyObject
*other
, *res
;
4244 if (!check_num_args(args
, 1))
4246 other
= PyTuple_GET_ITEM(args
, 0);
4247 ok
= func(&self
, &other
);
4251 Py_INCREF(Py_NotImplemented
);
4252 return Py_NotImplemented
;
4254 res
= PyTuple_New(2);
4260 PyTuple_SET_ITEM(res
, 0, self
);
4261 PyTuple_SET_ITEM(res
, 1, other
);
4266 wrap_ternaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4268 ternaryfunc func
= (ternaryfunc
)wrapped
;
4270 PyObject
*third
= Py_None
;
4272 /* Note: This wrapper only works for __pow__() */
4274 if (!PyArg_UnpackTuple(args
, "", 1, 2, &other
, &third
))
4276 return (*func
)(self
, other
, third
);
4280 wrap_ternaryfunc_r(PyObject
*self
, PyObject
*args
, void *wrapped
)
4282 ternaryfunc func
= (ternaryfunc
)wrapped
;
4284 PyObject
*third
= Py_None
;
4286 /* Note: This wrapper only works for __pow__() */
4288 if (!PyArg_UnpackTuple(args
, "", 1, 2, &other
, &third
))
4290 return (*func
)(other
, self
, third
);
4294 wrap_unaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4296 unaryfunc func
= (unaryfunc
)wrapped
;
4298 if (!check_num_args(args
, 0))
4300 return (*func
)(self
);
4304 wrap_indexargfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4306 ssizeargfunc func
= (ssizeargfunc
)wrapped
;
4310 if (!PyArg_UnpackTuple(args
, "", 1, 1, &o
))
4312 i
= PyNumber_AsSsize_t(o
, PyExc_OverflowError
);
4313 if (i
== -1 && PyErr_Occurred())
4315 return (*func
)(self
, i
);
4319 getindex(PyObject
*self
, PyObject
*arg
)
4323 i
= PyNumber_AsSsize_t(arg
, PyExc_OverflowError
);
4324 if (i
== -1 && PyErr_Occurred())
4327 PySequenceMethods
*sq
= Py_TYPE(self
)->tp_as_sequence
;
4328 if (sq
&& sq
->sq_length
) {
4329 Py_ssize_t n
= (*sq
->sq_length
)(self
);
4339 wrap_sq_item(PyObject
*self
, PyObject
*args
, void *wrapped
)
4341 ssizeargfunc func
= (ssizeargfunc
)wrapped
;
4345 if (PyTuple_GET_SIZE(args
) == 1) {
4346 arg
= PyTuple_GET_ITEM(args
, 0);
4347 i
= getindex(self
, arg
);
4348 if (i
== -1 && PyErr_Occurred())
4350 return (*func
)(self
, i
);
4352 check_num_args(args
, 1);
4353 assert(PyErr_Occurred());
4358 wrap_ssizessizeargfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4360 ssizessizeargfunc func
= (ssizessizeargfunc
)wrapped
;
4363 if (!PyArg_ParseTuple(args
, "nn", &i
, &j
))
4365 return (*func
)(self
, i
, j
);
4369 wrap_sq_setitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
4371 ssizeobjargproc func
= (ssizeobjargproc
)wrapped
;
4374 PyObject
*arg
, *value
;
4376 if (!PyArg_UnpackTuple(args
, "", 2, 2, &arg
, &value
))
4378 i
= getindex(self
, arg
);
4379 if (i
== -1 && PyErr_Occurred())
4381 res
= (*func
)(self
, i
, value
);
4382 if (res
== -1 && PyErr_Occurred())
4389 wrap_sq_delitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
4391 ssizeobjargproc func
= (ssizeobjargproc
)wrapped
;
4396 if (!check_num_args(args
, 1))
4398 arg
= PyTuple_GET_ITEM(args
, 0);
4399 i
= getindex(self
, arg
);
4400 if (i
== -1 && PyErr_Occurred())
4402 res
= (*func
)(self
, i
, NULL
);
4403 if (res
== -1 && PyErr_Occurred())
4410 wrap_ssizessizeobjargproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4412 ssizessizeobjargproc func
= (ssizessizeobjargproc
)wrapped
;
4417 if (!PyArg_ParseTuple(args
, "nnO", &i
, &j
, &value
))
4419 res
= (*func
)(self
, i
, j
, value
);
4420 if (res
== -1 && PyErr_Occurred())
4427 wrap_delslice(PyObject
*self
, PyObject
*args
, void *wrapped
)
4429 ssizessizeobjargproc func
= (ssizessizeobjargproc
)wrapped
;
4433 if (!PyArg_ParseTuple(args
, "nn", &i
, &j
))
4435 res
= (*func
)(self
, i
, j
, NULL
);
4436 if (res
== -1 && PyErr_Occurred())
4442 /* XXX objobjproc is a misnomer; should be objargpred */
4444 wrap_objobjproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4446 objobjproc func
= (objobjproc
)wrapped
;
4450 if (!check_num_args(args
, 1))
4452 value
= PyTuple_GET_ITEM(args
, 0);
4453 res
= (*func
)(self
, value
);
4454 if (res
== -1 && PyErr_Occurred())
4457 return PyBool_FromLong(res
);
4461 wrap_objobjargproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4463 objobjargproc func
= (objobjargproc
)wrapped
;
4465 PyObject
*key
, *value
;
4467 if (!PyArg_UnpackTuple(args
, "", 2, 2, &key
, &value
))
4469 res
= (*func
)(self
, key
, value
);
4470 if (res
== -1 && PyErr_Occurred())
4477 wrap_delitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
4479 objobjargproc func
= (objobjargproc
)wrapped
;
4483 if (!check_num_args(args
, 1))
4485 key
= PyTuple_GET_ITEM(args
, 0);
4486 res
= (*func
)(self
, key
, NULL
);
4487 if (res
== -1 && PyErr_Occurred())
4494 wrap_cmpfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4496 cmpfunc func
= (cmpfunc
)wrapped
;
4500 if (!check_num_args(args
, 1))
4502 other
= PyTuple_GET_ITEM(args
, 0);
4503 if (Py_TYPE(other
)->tp_compare
!= func
&&
4504 !PyType_IsSubtype(Py_TYPE(other
), Py_TYPE(self
))) {
4507 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
4508 Py_TYPE(self
)->tp_name
,
4509 Py_TYPE(self
)->tp_name
,
4510 Py_TYPE(other
)->tp_name
);
4513 res
= (*func
)(self
, other
);
4514 if (PyErr_Occurred())
4516 return PyInt_FromLong((long)res
);
4519 /* Helper to check for object.__setattr__ or __delattr__ applied to a type.
4520 This is called the Carlo Verre hack after its discoverer. */
4522 hackcheck(PyObject
*self
, setattrofunc func
, char *what
)
4524 PyTypeObject
*type
= Py_TYPE(self
);
4525 while (type
&& type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
4526 type
= type
->tp_base
;
4527 /* If type is NULL now, this is a really weird type.
4528 In the spirit of backwards compatibility (?), just shut up. */
4529 if (type
&& type
->tp_setattro
!= func
) {
4530 PyErr_Format(PyExc_TypeError
,
4531 "can't apply this %s to %s object",
4540 wrap_setattr(PyObject
*self
, PyObject
*args
, void *wrapped
)
4542 setattrofunc func
= (setattrofunc
)wrapped
;
4544 PyObject
*name
, *value
;
4546 if (!PyArg_UnpackTuple(args
, "", 2, 2, &name
, &value
))
4548 if (!hackcheck(self
, func
, "__setattr__"))
4550 res
= (*func
)(self
, name
, value
);
4558 wrap_delattr(PyObject
*self
, PyObject
*args
, void *wrapped
)
4560 setattrofunc func
= (setattrofunc
)wrapped
;
4564 if (!check_num_args(args
, 1))
4566 name
= PyTuple_GET_ITEM(args
, 0);
4567 if (!hackcheck(self
, func
, "__delattr__"))
4569 res
= (*func
)(self
, name
, NULL
);
4577 wrap_hashfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4579 hashfunc func
= (hashfunc
)wrapped
;
4582 if (!check_num_args(args
, 0))
4584 res
= (*func
)(self
);
4585 if (res
== -1 && PyErr_Occurred())
4587 return PyInt_FromLong(res
);
4591 wrap_call(PyObject
*self
, PyObject
*args
, void *wrapped
, PyObject
*kwds
)
4593 ternaryfunc func
= (ternaryfunc
)wrapped
;
4595 return (*func
)(self
, args
, kwds
);
4599 wrap_richcmpfunc(PyObject
*self
, PyObject
*args
, void *wrapped
, int op
)
4601 richcmpfunc func
= (richcmpfunc
)wrapped
;
4604 if (!check_num_args(args
, 1))
4606 other
= PyTuple_GET_ITEM(args
, 0);
4607 return (*func
)(self
, other
, op
);
4610 #undef RICHCMP_WRAPPER
4611 #define RICHCMP_WRAPPER(NAME, OP) \
4613 richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4615 return wrap_richcmpfunc(self, args, wrapped, OP); \
4618 RICHCMP_WRAPPER(lt
, Py_LT
)
4619 RICHCMP_WRAPPER(le
, Py_LE
)
4620 RICHCMP_WRAPPER(eq
, Py_EQ
)
4621 RICHCMP_WRAPPER(ne
, Py_NE
)
4622 RICHCMP_WRAPPER(gt
, Py_GT
)
4623 RICHCMP_WRAPPER(ge
, Py_GE
)
4626 wrap_next(PyObject
*self
, PyObject
*args
, void *wrapped
)
4628 unaryfunc func
= (unaryfunc
)wrapped
;
4631 if (!check_num_args(args
, 0))
4633 res
= (*func
)(self
);
4634 if (res
== NULL
&& !PyErr_Occurred())
4635 PyErr_SetNone(PyExc_StopIteration
);
4640 wrap_descr_get(PyObject
*self
, PyObject
*args
, void *wrapped
)
4642 descrgetfunc func
= (descrgetfunc
)wrapped
;
4644 PyObject
*type
= NULL
;
4646 if (!PyArg_UnpackTuple(args
, "", 1, 2, &obj
, &type
))
4650 if (type
== Py_None
)
4652 if (type
== NULL
&&obj
== NULL
) {
4653 PyErr_SetString(PyExc_TypeError
,
4654 "__get__(None, None) is invalid");
4657 return (*func
)(self
, obj
, type
);
4661 wrap_descr_set(PyObject
*self
, PyObject
*args
, void *wrapped
)
4663 descrsetfunc func
= (descrsetfunc
)wrapped
;
4664 PyObject
*obj
, *value
;
4667 if (!PyArg_UnpackTuple(args
, "", 2, 2, &obj
, &value
))
4669 ret
= (*func
)(self
, obj
, value
);
4677 wrap_descr_delete(PyObject
*self
, PyObject
*args
, void *wrapped
)
4679 descrsetfunc func
= (descrsetfunc
)wrapped
;
4683 if (!check_num_args(args
, 1))
4685 obj
= PyTuple_GET_ITEM(args
, 0);
4686 ret
= (*func
)(self
, obj
, NULL
);
4694 wrap_init(PyObject
*self
, PyObject
*args
, void *wrapped
, PyObject
*kwds
)
4696 initproc func
= (initproc
)wrapped
;
4698 if (func(self
, args
, kwds
) < 0)
4705 tp_new_wrapper(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
4707 PyTypeObject
*type
, *subtype
, *staticbase
;
4708 PyObject
*arg0
, *res
;
4710 if (self
== NULL
|| !PyType_Check(self
))
4711 Py_FatalError("__new__() called with non-type 'self'");
4712 type
= (PyTypeObject
*)self
;
4713 if (!PyTuple_Check(args
) || PyTuple_GET_SIZE(args
) < 1) {
4714 PyErr_Format(PyExc_TypeError
,
4715 "%s.__new__(): not enough arguments",
4719 arg0
= PyTuple_GET_ITEM(args
, 0);
4720 if (!PyType_Check(arg0
)) {
4721 PyErr_Format(PyExc_TypeError
,
4722 "%s.__new__(X): X is not a type object (%s)",
4724 Py_TYPE(arg0
)->tp_name
);
4727 subtype
= (PyTypeObject
*)arg0
;
4728 if (!PyType_IsSubtype(subtype
, type
)) {
4729 PyErr_Format(PyExc_TypeError
,
4730 "%s.__new__(%s): %s is not a subtype of %s",
4738 /* Check that the use doesn't do something silly and unsafe like
4739 object.__new__(dict). To do this, we check that the
4740 most derived base that's not a heap type is this type. */
4741 staticbase
= subtype
;
4742 while (staticbase
&& (staticbase
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
4743 staticbase
= staticbase
->tp_base
;
4744 /* If staticbase is NULL now, it is a really weird type.
4745 In the spirit of backwards compatibility (?), just shut up. */
4746 if (staticbase
&& staticbase
->tp_new
!= type
->tp_new
) {
4747 PyErr_Format(PyExc_TypeError
,
4748 "%s.__new__(%s) is not safe, use %s.__new__()",
4751 staticbase
== NULL
? "?" : staticbase
->tp_name
);
4755 args
= PyTuple_GetSlice(args
, 1, PyTuple_GET_SIZE(args
));
4758 res
= type
->tp_new(subtype
, args
, kwds
);
4763 static struct PyMethodDef tp_new_methoddef
[] = {
4764 {"__new__", (PyCFunction
)tp_new_wrapper
, METH_VARARGS
|METH_KEYWORDS
,
4765 PyDoc_STR("T.__new__(S, ...) -> "
4766 "a new object with type S, a subtype of T")},
4771 add_tp_new_wrapper(PyTypeObject
*type
)
4775 if (PyDict_GetItemString(type
->tp_dict
, "__new__") != NULL
)
4777 func
= PyCFunction_New(tp_new_methoddef
, (PyObject
*)type
);
4780 if (PyDict_SetItemString(type
->tp_dict
, "__new__", func
)) {
4788 /* Slot wrappers that call the corresponding __foo__ slot. See comments
4789 below at override_slots() for more explanation. */
4791 #define SLOT0(FUNCNAME, OPSTR) \
4793 FUNCNAME(PyObject *self) \
4795 static PyObject *cache_str; \
4796 return call_method(self, OPSTR, &cache_str, "()"); \
4799 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
4801 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
4803 static PyObject *cache_str; \
4804 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
4807 /* Boolean helper for SLOT1BINFULL().
4808 right.__class__ is a nontrivial subclass of left.__class__. */
4810 method_is_overloaded(PyObject
*left
, PyObject
*right
, char *name
)
4815 b
= PyObject_GetAttrString((PyObject
*)(Py_TYPE(right
)), name
);
4818 /* If right doesn't have it, it's not overloaded */
4822 a
= PyObject_GetAttrString((PyObject
*)(Py_TYPE(left
)), name
);
4826 /* If right has it but left doesn't, it's overloaded */
4830 ok
= PyObject_RichCompareBool(a
, b
, Py_NE
);
4842 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
4844 FUNCNAME(PyObject *self, PyObject *other) \
4846 static PyObject *cache_str, *rcache_str; \
4847 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4848 Py_TYPE(other)->tp_as_number != NULL && \
4849 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4850 if (Py_TYPE(self)->tp_as_number != NULL && \
4851 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4854 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4855 method_is_overloaded(self, other, ROPSTR)) { \
4857 other, ROPSTR, &rcache_str, "(O)", self); \
4858 if (r != Py_NotImplemented) \
4864 self, OPSTR, &cache_str, "(O)", other); \
4865 if (r != Py_NotImplemented || \
4866 Py_TYPE(other) == Py_TYPE(self)) \
4871 return call_maybe( \
4872 other, ROPSTR, &rcache_str, "(O)", self); \
4874 Py_INCREF(Py_NotImplemented); \
4875 return Py_NotImplemented; \
4878 #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4879 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4881 #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4883 FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4885 static PyObject *cache_str; \
4886 return call_method(self, OPSTR, &cache_str, \
4887 "(" ARGCODES ")", arg1, arg2); \
4891 slot_sq_length(PyObject
*self
)
4893 static PyObject
*len_str
;
4894 PyObject
*res
= call_method(self
, "__len__", &len_str
, "()");
4899 len
= PyInt_AsSsize_t(res
);
4902 if (!PyErr_Occurred())
4903 PyErr_SetString(PyExc_ValueError
,
4904 "__len__() should return >= 0");
4910 /* Super-optimized version of slot_sq_item.
4911 Other slots could do the same... */
4913 slot_sq_item(PyObject
*self
, Py_ssize_t i
)
4915 static PyObject
*getitem_str
;
4916 PyObject
*func
, *args
= NULL
, *ival
= NULL
, *retval
= NULL
;
4919 if (getitem_str
== NULL
) {
4920 getitem_str
= PyString_InternFromString("__getitem__");
4921 if (getitem_str
== NULL
)
4924 func
= _PyType_Lookup(Py_TYPE(self
), getitem_str
);
4926 if ((f
= Py_TYPE(func
)->tp_descr_get
) == NULL
)
4929 func
= f(func
, self
, (PyObject
*)(Py_TYPE(self
)));
4934 ival
= PyInt_FromSsize_t(i
);
4936 args
= PyTuple_New(1);
4938 PyTuple_SET_ITEM(args
, 0, ival
);
4939 retval
= PyObject_Call(func
, args
, NULL
);
4947 PyErr_SetObject(PyExc_AttributeError
, getitem_str
);
4956 slot_sq_slice(PyObject
*self
, Py_ssize_t i
, Py_ssize_t j
)
4958 static PyObject
*getslice_str
;
4960 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
4961 "use __getitem__", 1) < 0)
4963 return call_method(self
, "__getslice__", &getslice_str
,
4968 slot_sq_ass_item(PyObject
*self
, Py_ssize_t index
, PyObject
*value
)
4971 static PyObject
*delitem_str
, *setitem_str
;
4974 res
= call_method(self
, "__delitem__", &delitem_str
,
4977 res
= call_method(self
, "__setitem__", &setitem_str
,
4978 "(nO)", index
, value
);
4986 slot_sq_ass_slice(PyObject
*self
, Py_ssize_t i
, Py_ssize_t j
, PyObject
*value
)
4989 static PyObject
*delslice_str
, *setslice_str
;
4991 if (value
== NULL
) {
4992 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been removed; "
4993 "use __delitem__", 1) < 0)
4995 res
= call_method(self
, "__delslice__", &delslice_str
,
4999 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been removed; "
5000 "use __setitem__", 1) < 0)
5002 res
= call_method(self
, "__setslice__", &setslice_str
,
5003 "(nnO)", i
, j
, value
);
5012 slot_sq_contains(PyObject
*self
, PyObject
*value
)
5014 PyObject
*func
, *res
, *args
;
5017 static PyObject
*contains_str
;
5019 func
= lookup_maybe(self
, "__contains__", &contains_str
);
5021 args
= PyTuple_Pack(1, value
);
5025 res
= PyObject_Call(func
, args
, NULL
);
5030 result
= PyObject_IsTrue(res
);
5034 else if (! PyErr_Occurred()) {
5035 /* Possible results: -1 and 1 */
5036 result
= (int)_PySequence_IterSearch(self
, value
,
5037 PY_ITERSEARCH_CONTAINS
);
5042 #define slot_mp_length slot_sq_length
5044 SLOT1(slot_mp_subscript
, "__getitem__", PyObject
*, "O")
5047 slot_mp_ass_subscript(PyObject
*self
, PyObject
*key
, PyObject
*value
)
5050 static PyObject
*delitem_str
, *setitem_str
;
5053 res
= call_method(self
, "__delitem__", &delitem_str
,
5056 res
= call_method(self
, "__setitem__", &setitem_str
,
5057 "(OO)", key
, value
);
5064 SLOT1BIN(slot_nb_add
, nb_add
, "__add__", "__radd__")
5065 SLOT1BIN(slot_nb_subtract
, nb_subtract
, "__sub__", "__rsub__")
5066 SLOT1BIN(slot_nb_multiply
, nb_multiply
, "__mul__", "__rmul__")
5067 SLOT1BIN(slot_nb_divide
, nb_divide
, "__div__", "__rdiv__")
5068 SLOT1BIN(slot_nb_remainder
, nb_remainder
, "__mod__", "__rmod__")
5069 SLOT1BIN(slot_nb_divmod
, nb_divmod
, "__divmod__", "__rdivmod__")
5071 static PyObject
*slot_nb_power(PyObject
*, PyObject
*, PyObject
*);
5073 SLOT1BINFULL(slot_nb_power_binary
, slot_nb_power
,
5074 nb_power
, "__pow__", "__rpow__")
5077 slot_nb_power(PyObject
*self
, PyObject
*other
, PyObject
*modulus
)
5079 static PyObject
*pow_str
;
5081 if (modulus
== Py_None
)
5082 return slot_nb_power_binary(self
, other
);
5083 /* Three-arg power doesn't use __rpow__. But ternary_op
5084 can call this when the second argument's type uses
5085 slot_nb_power, so check before calling self.__pow__. */
5086 if (Py_TYPE(self
)->tp_as_number
!= NULL
&&
5087 Py_TYPE(self
)->tp_as_number
->nb_power
== slot_nb_power
) {
5088 return call_method(self
, "__pow__", &pow_str
,
5089 "(OO)", other
, modulus
);
5091 Py_INCREF(Py_NotImplemented
);
5092 return Py_NotImplemented
;
5095 SLOT0(slot_nb_negative
, "__neg__")
5096 SLOT0(slot_nb_positive
, "__pos__")
5097 SLOT0(slot_nb_absolute
, "__abs__")
5100 slot_nb_nonzero(PyObject
*self
)
5102 PyObject
*func
, *args
;
5103 static PyObject
*nonzero_str
, *len_str
;
5107 func
= lookup_maybe(self
, "__nonzero__", &nonzero_str
);
5109 if (PyErr_Occurred())
5111 func
= lookup_maybe(self
, "__len__", &len_str
);
5113 return PyErr_Occurred() ? -1 : 1;
5116 args
= PyTuple_New(0);
5118 PyObject
*temp
= PyObject_Call(func
, args
, NULL
);
5121 if (PyInt_CheckExact(temp
) || PyBool_Check(temp
))
5122 result
= PyObject_IsTrue(temp
);
5124 PyErr_Format(PyExc_TypeError
,
5126 "bool or int, returned %s",
5127 (using_len
? "__len__"
5129 temp
->ob_type
->tp_name
);
5141 slot_nb_index(PyObject
*self
)
5143 static PyObject
*index_str
;
5144 return call_method(self
, "__index__", &index_str
, "()");
5148 SLOT0(slot_nb_invert
, "__invert__")
5149 SLOT1BIN(slot_nb_lshift
, nb_lshift
, "__lshift__", "__rlshift__")
5150 SLOT1BIN(slot_nb_rshift
, nb_rshift
, "__rshift__", "__rrshift__")
5151 SLOT1BIN(slot_nb_and
, nb_and
, "__and__", "__rand__")
5152 SLOT1BIN(slot_nb_xor
, nb_xor
, "__xor__", "__rxor__")
5153 SLOT1BIN(slot_nb_or
, nb_or
, "__or__", "__ror__")
5156 slot_nb_coerce(PyObject
**a
, PyObject
**b
)
5158 static PyObject
*coerce_str
;
5159 PyObject
*self
= *a
, *other
= *b
;
5161 if (self
->ob_type
->tp_as_number
!= NULL
&&
5162 self
->ob_type
->tp_as_number
->nb_coerce
== slot_nb_coerce
) {
5165 self
, "__coerce__", &coerce_str
, "(O)", other
);
5168 if (r
== Py_NotImplemented
) {
5172 if (!PyTuple_Check(r
) || PyTuple_GET_SIZE(r
) != 2) {
5173 PyErr_SetString(PyExc_TypeError
,
5174 "__coerce__ didn't return a 2-tuple");
5178 *a
= PyTuple_GET_ITEM(r
, 0);
5180 *b
= PyTuple_GET_ITEM(r
, 1);
5186 if (other
->ob_type
->tp_as_number
!= NULL
&&
5187 other
->ob_type
->tp_as_number
->nb_coerce
== slot_nb_coerce
) {
5190 other
, "__coerce__", &coerce_str
, "(O)", self
);
5193 if (r
== Py_NotImplemented
) {
5197 if (!PyTuple_Check(r
) || PyTuple_GET_SIZE(r
) != 2) {
5198 PyErr_SetString(PyExc_TypeError
,
5199 "__coerce__ didn't return a 2-tuple");
5203 *a
= PyTuple_GET_ITEM(r
, 1);
5205 *b
= PyTuple_GET_ITEM(r
, 0);
5213 SLOT0(slot_nb_int
, "__int__")
5214 SLOT0(slot_nb_long
, "__long__")
5215 SLOT0(slot_nb_float
, "__float__")
5216 SLOT0(slot_nb_oct
, "__oct__")
5217 SLOT0(slot_nb_hex
, "__hex__")
5218 SLOT1(slot_nb_inplace_add
, "__iadd__", PyObject
*, "O")
5219 SLOT1(slot_nb_inplace_subtract
, "__isub__", PyObject
*, "O")
5220 SLOT1(slot_nb_inplace_multiply
, "__imul__", PyObject
*, "O")
5221 SLOT1(slot_nb_inplace_divide
, "__idiv__", PyObject
*, "O")
5222 SLOT1(slot_nb_inplace_remainder
, "__imod__", PyObject
*, "O")
5223 /* Can't use SLOT1 here, because nb_inplace_power is ternary */
5225 slot_nb_inplace_power(PyObject
*self
, PyObject
* arg1
, PyObject
*arg2
)
5227 static PyObject
*cache_str
;
5228 return call_method(self
, "__ipow__", &cache_str
, "(" "O" ")", arg1
);
5230 SLOT1(slot_nb_inplace_lshift
, "__ilshift__", PyObject
*, "O")
5231 SLOT1(slot_nb_inplace_rshift
, "__irshift__", PyObject
*, "O")
5232 SLOT1(slot_nb_inplace_and
, "__iand__", PyObject
*, "O")
5233 SLOT1(slot_nb_inplace_xor
, "__ixor__", PyObject
*, "O")
5234 SLOT1(slot_nb_inplace_or
, "__ior__", PyObject
*, "O")
5235 SLOT1BIN(slot_nb_floor_divide
, nb_floor_divide
,
5236 "__floordiv__", "__rfloordiv__")
5237 SLOT1BIN(slot_nb_true_divide
, nb_true_divide
, "__truediv__", "__rtruediv__")
5238 SLOT1(slot_nb_inplace_floor_divide
, "__ifloordiv__", PyObject
*, "O")
5239 SLOT1(slot_nb_inplace_true_divide
, "__itruediv__", PyObject
*, "O")
5242 half_compare(PyObject
*self
, PyObject
*other
)
5244 PyObject
*func
, *args
, *res
;
5245 static PyObject
*cmp_str
;
5248 func
= lookup_method(self
, "__cmp__", &cmp_str
);
5253 args
= PyTuple_Pack(1, other
);
5257 res
= PyObject_Call(func
, args
, NULL
);
5261 if (res
!= Py_NotImplemented
) {
5264 c
= PyInt_AsLong(res
);
5266 if (c
== -1 && PyErr_Occurred())
5268 return (c
< 0) ? -1 : (c
> 0) ? 1 : 0;
5275 /* This slot is published for the benefit of try_3way_compare in object.c */
5277 _PyObject_SlotCompare(PyObject
*self
, PyObject
*other
)
5281 if (Py_TYPE(self
)->tp_compare
== _PyObject_SlotCompare
) {
5282 c
= half_compare(self
, other
);
5286 if (Py_TYPE(other
)->tp_compare
== _PyObject_SlotCompare
) {
5287 c
= half_compare(other
, self
);
5293 return (void *)self
< (void *)other
? -1 :
5294 (void *)self
> (void *)other
? 1 : 0;
5298 slot_tp_repr(PyObject
*self
)
5300 PyObject
*func
, *res
;
5301 static PyObject
*repr_str
;
5303 func
= lookup_method(self
, "__repr__", &repr_str
);
5305 res
= PyEval_CallObject(func
, NULL
);
5310 return PyString_FromFormat("<%s object at %p>",
5311 Py_TYPE(self
)->tp_name
, self
);
5315 slot_tp_str(PyObject
*self
)
5317 PyObject
*func
, *res
;
5318 static PyObject
*str_str
;
5320 func
= lookup_method(self
, "__str__", &str_str
);
5322 res
= PyEval_CallObject(func
, NULL
);
5328 return slot_tp_repr(self
);
5333 slot_tp_hash(PyObject
*self
)
5336 static PyObject
*hash_str
, *eq_str
, *cmp_str
;
5339 func
= lookup_method(self
, "__hash__", &hash_str
);
5341 if (func
!= NULL
&& func
!= Py_None
) {
5342 PyObject
*res
= PyEval_CallObject(func
, NULL
);
5346 if (PyLong_Check(res
))
5347 h
= PyLong_Type
.tp_hash(res
);
5349 h
= PyInt_AsLong(res
);
5353 Py_XDECREF(func
); /* may be None */
5355 func
= lookup_method(self
, "__eq__", &eq_str
);
5358 func
= lookup_method(self
, "__cmp__", &cmp_str
);
5362 return PyObject_HashNotImplemented(self
);
5365 h
= _Py_HashPointer((void *)self
);
5367 if (h
== -1 && !PyErr_Occurred())
5373 slot_tp_call(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5375 static PyObject
*call_str
;
5376 PyObject
*meth
= lookup_method(self
, "__call__", &call_str
);
5382 res
= PyObject_Call(meth
, args
, kwds
);
5388 /* There are two slot dispatch functions for tp_getattro.
5390 - slot_tp_getattro() is used when __getattribute__ is overridden
5391 but no __getattr__ hook is present;
5393 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5395 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5396 detects the absence of __getattr__ and then installs the simpler slot if
5400 slot_tp_getattro(PyObject
*self
, PyObject
*name
)
5402 static PyObject
*getattribute_str
= NULL
;
5403 return call_method(self
, "__getattribute__", &getattribute_str
,
5408 call_attribute(PyObject
*self
, PyObject
*attr
, PyObject
*name
)
5410 PyObject
*res
, *descr
= NULL
;
5411 descrgetfunc f
= Py_TYPE(attr
)->tp_descr_get
;
5414 descr
= f(attr
, self
, (PyObject
*)(Py_TYPE(self
)));
5420 res
= PyObject_CallFunctionObjArgs(attr
, name
, NULL
);
5426 slot_tp_getattr_hook(PyObject
*self
, PyObject
*name
)
5428 PyTypeObject
*tp
= Py_TYPE(self
);
5429 PyObject
*getattr
, *getattribute
, *res
;
5430 static PyObject
*getattribute_str
= NULL
;
5431 static PyObject
*getattr_str
= NULL
;
5433 if (getattr_str
== NULL
) {
5434 getattr_str
= PyString_InternFromString("__getattr__");
5435 if (getattr_str
== NULL
)
5438 if (getattribute_str
== NULL
) {
5440 PyString_InternFromString("__getattribute__");
5441 if (getattribute_str
== NULL
)
5444 /* speed hack: we could use lookup_maybe, but that would resolve the
5445 method fully for each attribute lookup for classes with
5446 __getattr__, even when the attribute is present. So we use
5447 _PyType_Lookup and create the method only when needed, with
5449 getattr
= _PyType_Lookup(tp
, getattr_str
);
5450 if (getattr
== NULL
) {
5451 /* No __getattr__ hook: use a simpler dispatcher */
5452 tp
->tp_getattro
= slot_tp_getattro
;
5453 return slot_tp_getattro(self
, name
);
5456 /* speed hack: we could use lookup_maybe, but that would resolve the
5457 method fully for each attribute lookup for classes with
5458 __getattr__, even when self has the default __getattribute__
5459 method. So we use _PyType_Lookup and create the method only when
5460 needed, with call_attribute. */
5461 getattribute
= _PyType_Lookup(tp
, getattribute_str
);
5462 if (getattribute
== NULL
||
5463 (Py_TYPE(getattribute
) == &PyWrapperDescr_Type
&&
5464 ((PyWrapperDescrObject
*)getattribute
)->d_wrapped
==
5465 (void *)PyObject_GenericGetAttr
))
5466 res
= PyObject_GenericGetAttr(self
, name
);
5468 Py_INCREF(getattribute
);
5469 res
= call_attribute(self
, getattribute
, name
);
5470 Py_DECREF(getattribute
);
5472 if (res
== NULL
&& PyErr_ExceptionMatches(PyExc_AttributeError
)) {
5474 res
= call_attribute(self
, getattr
, name
);
5481 slot_tp_setattro(PyObject
*self
, PyObject
*name
, PyObject
*value
)
5484 static PyObject
*delattr_str
, *setattr_str
;
5487 res
= call_method(self
, "__delattr__", &delattr_str
,
5490 res
= call_method(self
, "__setattr__", &setattr_str
,
5491 "(OO)", name
, value
);
5498 static char *name_op
[] = {
5508 half_richcompare(PyObject
*self
, PyObject
*other
, int op
)
5510 PyObject
*func
, *args
, *res
;
5511 static PyObject
*op_str
[6];
5513 func
= lookup_method(self
, name_op
[op
], &op_str
[op
]);
5516 Py_INCREF(Py_NotImplemented
);
5517 return Py_NotImplemented
;
5519 args
= PyTuple_Pack(1, other
);
5523 res
= PyObject_Call(func
, args
, NULL
);
5531 slot_tp_richcompare(PyObject
*self
, PyObject
*other
, int op
)
5535 if (Py_TYPE(self
)->tp_richcompare
== slot_tp_richcompare
) {
5536 res
= half_richcompare(self
, other
, op
);
5537 if (res
!= Py_NotImplemented
)
5541 if (Py_TYPE(other
)->tp_richcompare
== slot_tp_richcompare
) {
5542 res
= half_richcompare(other
, self
, _Py_SwappedOp
[op
]);
5543 if (res
!= Py_NotImplemented
) {
5548 Py_INCREF(Py_NotImplemented
);
5549 return Py_NotImplemented
;
5553 slot_tp_iter(PyObject
*self
)
5555 PyObject
*func
, *res
;
5556 static PyObject
*iter_str
, *getitem_str
;
5558 func
= lookup_method(self
, "__iter__", &iter_str
);
5561 args
= res
= PyTuple_New(0);
5563 res
= PyObject_Call(func
, args
, NULL
);
5570 func
= lookup_method(self
, "__getitem__", &getitem_str
);
5572 PyErr_Format(PyExc_TypeError
,
5573 "'%.200s' object is not iterable",
5574 Py_TYPE(self
)->tp_name
);
5578 return PySeqIter_New(self
);
5582 slot_tp_iternext(PyObject
*self
)
5584 static PyObject
*next_str
;
5585 return call_method(self
, "next", &next_str
, "()");
5589 slot_tp_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
5591 PyTypeObject
*tp
= Py_TYPE(self
);
5593 static PyObject
*get_str
= NULL
;
5595 if (get_str
== NULL
) {
5596 get_str
= PyString_InternFromString("__get__");
5597 if (get_str
== NULL
)
5600 get
= _PyType_Lookup(tp
, get_str
);
5602 /* Avoid further slowdowns */
5603 if (tp
->tp_descr_get
== slot_tp_descr_get
)
5604 tp
->tp_descr_get
= NULL
;
5612 return PyObject_CallFunctionObjArgs(get
, self
, obj
, type
, NULL
);
5616 slot_tp_descr_set(PyObject
*self
, PyObject
*target
, PyObject
*value
)
5619 static PyObject
*del_str
, *set_str
;
5622 res
= call_method(self
, "__delete__", &del_str
,
5625 res
= call_method(self
, "__set__", &set_str
,
5626 "(OO)", target
, value
);
5634 slot_tp_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5636 static PyObject
*init_str
;
5637 PyObject
*meth
= lookup_method(self
, "__init__", &init_str
);
5642 res
= PyObject_Call(meth
, args
, kwds
);
5646 if (res
!= Py_None
) {
5647 PyErr_Format(PyExc_TypeError
,
5648 "__init__() should return None, not '%.200s'",
5649 Py_TYPE(res
)->tp_name
);
5658 slot_tp_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
5660 static PyObject
*new_str
;
5662 PyObject
*newargs
, *x
;
5665 if (new_str
== NULL
) {
5666 new_str
= PyString_InternFromString("__new__");
5667 if (new_str
== NULL
)
5670 func
= PyObject_GetAttr((PyObject
*)type
, new_str
);
5673 assert(PyTuple_Check(args
));
5674 n
= PyTuple_GET_SIZE(args
);
5675 newargs
= PyTuple_New(n
+1);
5676 if (newargs
== NULL
)
5679 PyTuple_SET_ITEM(newargs
, 0, (PyObject
*)type
);
5680 for (i
= 0; i
< n
; i
++) {
5681 x
= PyTuple_GET_ITEM(args
, i
);
5683 PyTuple_SET_ITEM(newargs
, i
+1, x
);
5685 x
= PyObject_Call(func
, newargs
, kwds
);
5692 slot_tp_del(PyObject
*self
)
5694 static PyObject
*del_str
= NULL
;
5695 PyObject
*del
, *res
;
5696 PyObject
*error_type
, *error_value
, *error_traceback
;
5698 /* Temporarily resurrect the object. */
5699 assert(self
->ob_refcnt
== 0);
5700 self
->ob_refcnt
= 1;
5702 /* Save the current exception, if any. */
5703 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
5705 /* Execute __del__ method, if any. */
5706 del
= lookup_maybe(self
, "__del__", &del_str
);
5708 res
= PyEval_CallObject(del
, NULL
);
5710 PyErr_WriteUnraisable(del
);
5716 /* Restore the saved exception. */
5717 PyErr_Restore(error_type
, error_value
, error_traceback
);
5719 /* Undo the temporary resurrection; can't use DECREF here, it would
5720 * cause a recursive call.
5722 assert(self
->ob_refcnt
> 0);
5723 if (--self
->ob_refcnt
== 0)
5724 return; /* this is the normal path out */
5726 /* __del__ resurrected it! Make it look like the original Py_DECREF
5730 Py_ssize_t refcnt
= self
->ob_refcnt
;
5731 _Py_NewReference(self
);
5732 self
->ob_refcnt
= refcnt
;
5734 assert(!PyType_IS_GC(Py_TYPE(self
)) ||
5735 _Py_AS_GC(self
)->gc
.gc_refs
!= _PyGC_REFS_UNTRACKED
);
5736 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5737 * we need to undo that. */
5739 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5740 * chain, so no more to do there.
5741 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5742 * _Py_NewReference bumped tp_allocs: both of those need to be
5746 --Py_TYPE(self
)->tp_frees
;
5747 --Py_TYPE(self
)->tp_allocs
;
5752 /* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
5753 functions. The offsets here are relative to the 'PyHeapTypeObject'
5754 structure, which incorporates the additional structures used for numbers,
5755 sequences and mappings.
5756 Note that multiple names may map to the same slot (e.g. __eq__,
5757 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
5758 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5759 terminated with an all-zero entry. (This table is further initialized and
5760 sorted in init_slotdefs() below.) */
5762 typedef struct wrapperbase slotdef
;
5775 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5776 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5778 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5779 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5780 PyDoc_STR(DOC), FLAGS}
5781 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5782 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5784 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5785 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5786 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5787 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5788 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5789 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5790 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5791 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5792 "x." NAME "() <==> " DOC)
5793 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5794 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5795 "x." NAME "(y) <==> x" DOC "y")
5796 #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5797 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5798 "x." NAME "(y) <==> x" DOC "y")
5799 #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5800 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5801 "x." NAME "(y) <==> y" DOC "x")
5802 #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5803 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5804 "x." NAME "(y) <==> " DOC)
5805 #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5806 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5807 "x." NAME "(y) <==> " DOC)
5809 static slotdef slotdefs
[] = {
5810 SQSLOT("__len__", sq_length
, slot_sq_length
, wrap_lenfunc
,
5811 "x.__len__() <==> len(x)"),
5812 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5813 The logic in abstract.c always falls back to nb_add/nb_multiply in
5814 this case. Defining both the nb_* and the sq_* slots to call the
5815 user-defined methods has unexpected side-effects, as shown by
5816 test_descr.notimplemented() */
5817 SQSLOT("__add__", sq_concat
, NULL
, wrap_binaryfunc
,
5818 "x.__add__(y) <==> x+y"),
5819 SQSLOT("__mul__", sq_repeat
, NULL
, wrap_indexargfunc
,
5820 "x.__mul__(n) <==> x*n"),
5821 SQSLOT("__rmul__", sq_repeat
, NULL
, wrap_indexargfunc
,
5822 "x.__rmul__(n) <==> n*x"),
5823 SQSLOT("__getitem__", sq_item
, slot_sq_item
, wrap_sq_item
,
5824 "x.__getitem__(y) <==> x[y]"),
5825 SQSLOT("__getslice__", sq_slice
, slot_sq_slice
, wrap_ssizessizeargfunc
,
5826 "x.__getslice__(i, j) <==> x[i:j]\n\
5828 Use of negative indices is not supported."),
5829 SQSLOT("__setitem__", sq_ass_item
, slot_sq_ass_item
, wrap_sq_setitem
,
5830 "x.__setitem__(i, y) <==> x[i]=y"),
5831 SQSLOT("__delitem__", sq_ass_item
, slot_sq_ass_item
, wrap_sq_delitem
,
5832 "x.__delitem__(y) <==> del x[y]"),
5833 SQSLOT("__setslice__", sq_ass_slice
, slot_sq_ass_slice
,
5834 wrap_ssizessizeobjargproc
,
5835 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5837 Use of negative indices is not supported."),
5838 SQSLOT("__delslice__", sq_ass_slice
, slot_sq_ass_slice
, wrap_delslice
,
5839 "x.__delslice__(i, j) <==> del x[i:j]\n\
5841 Use of negative indices is not supported."),
5842 SQSLOT("__contains__", sq_contains
, slot_sq_contains
, wrap_objobjproc
,
5843 "x.__contains__(y) <==> y in x"),
5844 SQSLOT("__iadd__", sq_inplace_concat
, NULL
,
5845 wrap_binaryfunc
, "x.__iadd__(y) <==> x+=y"),
5846 SQSLOT("__imul__", sq_inplace_repeat
, NULL
,
5847 wrap_indexargfunc
, "x.__imul__(y) <==> x*=y"),
5849 MPSLOT("__len__", mp_length
, slot_mp_length
, wrap_lenfunc
,
5850 "x.__len__() <==> len(x)"),
5851 MPSLOT("__getitem__", mp_subscript
, slot_mp_subscript
,
5853 "x.__getitem__(y) <==> x[y]"),
5854 MPSLOT("__setitem__", mp_ass_subscript
, slot_mp_ass_subscript
,
5856 "x.__setitem__(i, y) <==> x[i]=y"),
5857 MPSLOT("__delitem__", mp_ass_subscript
, slot_mp_ass_subscript
,
5859 "x.__delitem__(y) <==> del x[y]"),
5861 BINSLOT("__add__", nb_add
, slot_nb_add
,
5863 RBINSLOT("__radd__", nb_add
, slot_nb_add
,
5865 BINSLOT("__sub__", nb_subtract
, slot_nb_subtract
,
5867 RBINSLOT("__rsub__", nb_subtract
, slot_nb_subtract
,
5869 BINSLOT("__mul__", nb_multiply
, slot_nb_multiply
,
5871 RBINSLOT("__rmul__", nb_multiply
, slot_nb_multiply
,
5873 BINSLOT("__div__", nb_divide
, slot_nb_divide
,
5875 RBINSLOT("__rdiv__", nb_divide
, slot_nb_divide
,
5877 BINSLOT("__mod__", nb_remainder
, slot_nb_remainder
,
5879 RBINSLOT("__rmod__", nb_remainder
, slot_nb_remainder
,
5881 BINSLOTNOTINFIX("__divmod__", nb_divmod
, slot_nb_divmod
,
5883 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod
, slot_nb_divmod
,
5885 NBSLOT("__pow__", nb_power
, slot_nb_power
, wrap_ternaryfunc
,
5886 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5887 NBSLOT("__rpow__", nb_power
, slot_nb_power
, wrap_ternaryfunc_r
,
5888 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5889 UNSLOT("__neg__", nb_negative
, slot_nb_negative
, wrap_unaryfunc
, "-x"),
5890 UNSLOT("__pos__", nb_positive
, slot_nb_positive
, wrap_unaryfunc
, "+x"),
5891 UNSLOT("__abs__", nb_absolute
, slot_nb_absolute
, wrap_unaryfunc
,
5893 UNSLOT("__nonzero__", nb_nonzero
, slot_nb_nonzero
, wrap_inquirypred
,
5895 UNSLOT("__invert__", nb_invert
, slot_nb_invert
, wrap_unaryfunc
, "~x"),
5896 BINSLOT("__lshift__", nb_lshift
, slot_nb_lshift
, "<<"),
5897 RBINSLOT("__rlshift__", nb_lshift
, slot_nb_lshift
, "<<"),
5898 BINSLOT("__rshift__", nb_rshift
, slot_nb_rshift
, ">>"),
5899 RBINSLOT("__rrshift__", nb_rshift
, slot_nb_rshift
, ">>"),
5900 BINSLOT("__and__", nb_and
, slot_nb_and
, "&"),
5901 RBINSLOT("__rand__", nb_and
, slot_nb_and
, "&"),
5902 BINSLOT("__xor__", nb_xor
, slot_nb_xor
, "^"),
5903 RBINSLOT("__rxor__", nb_xor
, slot_nb_xor
, "^"),
5904 BINSLOT("__or__", nb_or
, slot_nb_or
, "|"),
5905 RBINSLOT("__ror__", nb_or
, slot_nb_or
, "|"),
5906 NBSLOT("__coerce__", nb_coerce
, slot_nb_coerce
, wrap_coercefunc
,
5907 "x.__coerce__(y) <==> coerce(x, y)"),
5908 UNSLOT("__int__", nb_int
, slot_nb_int
, wrap_unaryfunc
,
5910 UNSLOT("__long__", nb_long
, slot_nb_long
, wrap_unaryfunc
,
5912 UNSLOT("__float__", nb_float
, slot_nb_float
, wrap_unaryfunc
,
5914 UNSLOT("__oct__", nb_oct
, slot_nb_oct
, wrap_unaryfunc
,
5916 UNSLOT("__hex__", nb_hex
, slot_nb_hex
, wrap_unaryfunc
,
5918 NBSLOT("__index__", nb_index
, slot_nb_index
, wrap_unaryfunc
,
5919 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5920 IBSLOT("__iadd__", nb_inplace_add
, slot_nb_inplace_add
,
5921 wrap_binaryfunc
, "+"),
5922 IBSLOT("__isub__", nb_inplace_subtract
, slot_nb_inplace_subtract
,
5923 wrap_binaryfunc
, "-"),
5924 IBSLOT("__imul__", nb_inplace_multiply
, slot_nb_inplace_multiply
,
5925 wrap_binaryfunc
, "*"),
5926 IBSLOT("__idiv__", nb_inplace_divide
, slot_nb_inplace_divide
,
5927 wrap_binaryfunc
, "/"),
5928 IBSLOT("__imod__", nb_inplace_remainder
, slot_nb_inplace_remainder
,
5929 wrap_binaryfunc
, "%"),
5930 IBSLOT("__ipow__", nb_inplace_power
, slot_nb_inplace_power
,
5931 wrap_binaryfunc
, "**"),
5932 IBSLOT("__ilshift__", nb_inplace_lshift
, slot_nb_inplace_lshift
,
5933 wrap_binaryfunc
, "<<"),
5934 IBSLOT("__irshift__", nb_inplace_rshift
, slot_nb_inplace_rshift
,
5935 wrap_binaryfunc
, ">>"),
5936 IBSLOT("__iand__", nb_inplace_and
, slot_nb_inplace_and
,
5937 wrap_binaryfunc
, "&"),
5938 IBSLOT("__ixor__", nb_inplace_xor
, slot_nb_inplace_xor
,
5939 wrap_binaryfunc
, "^"),
5940 IBSLOT("__ior__", nb_inplace_or
, slot_nb_inplace_or
,
5941 wrap_binaryfunc
, "|"),
5942 BINSLOT("__floordiv__", nb_floor_divide
, slot_nb_floor_divide
, "//"),
5943 RBINSLOT("__rfloordiv__", nb_floor_divide
, slot_nb_floor_divide
, "//"),
5944 BINSLOT("__truediv__", nb_true_divide
, slot_nb_true_divide
, "/"),
5945 RBINSLOT("__rtruediv__", nb_true_divide
, slot_nb_true_divide
, "/"),
5946 IBSLOT("__ifloordiv__", nb_inplace_floor_divide
,
5947 slot_nb_inplace_floor_divide
, wrap_binaryfunc
, "//"),
5948 IBSLOT("__itruediv__", nb_inplace_true_divide
,
5949 slot_nb_inplace_true_divide
, wrap_binaryfunc
, "/"),
5951 TPSLOT("__str__", tp_str
, slot_tp_str
, wrap_unaryfunc
,
5952 "x.__str__() <==> str(x)"),
5953 TPSLOT("__str__", tp_print
, NULL
, NULL
, ""),
5954 TPSLOT("__repr__", tp_repr
, slot_tp_repr
, wrap_unaryfunc
,
5955 "x.__repr__() <==> repr(x)"),
5956 TPSLOT("__repr__", tp_print
, NULL
, NULL
, ""),
5957 TPSLOT("__cmp__", tp_compare
, _PyObject_SlotCompare
, wrap_cmpfunc
,
5958 "x.__cmp__(y) <==> cmp(x,y)"),
5959 TPSLOT("__hash__", tp_hash
, slot_tp_hash
, wrap_hashfunc
,
5960 "x.__hash__() <==> hash(x)"),
5961 FLSLOT("__call__", tp_call
, slot_tp_call
, (wrapperfunc
)wrap_call
,
5962 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS
),
5963 TPSLOT("__getattribute__", tp_getattro
, slot_tp_getattr_hook
,
5964 wrap_binaryfunc
, "x.__getattribute__('name') <==> x.name"),
5965 TPSLOT("__getattribute__", tp_getattr
, NULL
, NULL
, ""),
5966 TPSLOT("__getattr__", tp_getattro
, slot_tp_getattr_hook
, NULL
, ""),
5967 TPSLOT("__getattr__", tp_getattr
, NULL
, NULL
, ""),
5968 TPSLOT("__setattr__", tp_setattro
, slot_tp_setattro
, wrap_setattr
,
5969 "x.__setattr__('name', value) <==> x.name = value"),
5970 TPSLOT("__setattr__", tp_setattr
, NULL
, NULL
, ""),
5971 TPSLOT("__delattr__", tp_setattro
, slot_tp_setattro
, wrap_delattr
,
5972 "x.__delattr__('name') <==> del x.name"),
5973 TPSLOT("__delattr__", tp_setattr
, NULL
, NULL
, ""),
5974 TPSLOT("__lt__", tp_richcompare
, slot_tp_richcompare
, richcmp_lt
,
5975 "x.__lt__(y) <==> x<y"),
5976 TPSLOT("__le__", tp_richcompare
, slot_tp_richcompare
, richcmp_le
,
5977 "x.__le__(y) <==> x<=y"),
5978 TPSLOT("__eq__", tp_richcompare
, slot_tp_richcompare
, richcmp_eq
,
5979 "x.__eq__(y) <==> x==y"),
5980 TPSLOT("__ne__", tp_richcompare
, slot_tp_richcompare
, richcmp_ne
,
5981 "x.__ne__(y) <==> x!=y"),
5982 TPSLOT("__gt__", tp_richcompare
, slot_tp_richcompare
, richcmp_gt
,
5983 "x.__gt__(y) <==> x>y"),
5984 TPSLOT("__ge__", tp_richcompare
, slot_tp_richcompare
, richcmp_ge
,
5985 "x.__ge__(y) <==> x>=y"),
5986 TPSLOT("__iter__", tp_iter
, slot_tp_iter
, wrap_unaryfunc
,
5987 "x.__iter__() <==> iter(x)"),
5988 TPSLOT("next", tp_iternext
, slot_tp_iternext
, wrap_next
,
5989 "x.next() -> the next value, or raise StopIteration"),
5990 TPSLOT("__get__", tp_descr_get
, slot_tp_descr_get
, wrap_descr_get
,
5991 "descr.__get__(obj[, type]) -> value"),
5992 TPSLOT("__set__", tp_descr_set
, slot_tp_descr_set
, wrap_descr_set
,
5993 "descr.__set__(obj, value)"),
5994 TPSLOT("__delete__", tp_descr_set
, slot_tp_descr_set
,
5995 wrap_descr_delete
, "descr.__delete__(obj)"),
5996 FLSLOT("__init__", tp_init
, slot_tp_init
, (wrapperfunc
)wrap_init
,
5997 "x.__init__(...) initializes x; "
5998 "see x.__class__.__doc__ for signature",
5999 PyWrapperFlag_KEYWORDS
),
6000 TPSLOT("__new__", tp_new
, slot_tp_new
, NULL
, ""),
6001 TPSLOT("__del__", tp_del
, slot_tp_del
, NULL
, ""),
6005 /* Given a type pointer and an offset gotten from a slotdef entry, return a
6006 pointer to the actual slot. This is not quite the same as simply adding
6007 the offset to the type pointer, since it takes care to indirect through the
6008 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6009 indirection pointer is NULL. */
6011 slotptr(PyTypeObject
*type
, int ioffset
)
6014 long offset
= ioffset
;
6016 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6017 assert(offset
>= 0);
6018 assert((size_t)offset
< offsetof(PyHeapTypeObject
, as_buffer
));
6019 if ((size_t)offset
>= offsetof(PyHeapTypeObject
, as_sequence
)) {
6020 ptr
= (char *)type
->tp_as_sequence
;
6021 offset
-= offsetof(PyHeapTypeObject
, as_sequence
);
6023 else if ((size_t)offset
>= offsetof(PyHeapTypeObject
, as_mapping
)) {
6024 ptr
= (char *)type
->tp_as_mapping
;
6025 offset
-= offsetof(PyHeapTypeObject
, as_mapping
);
6027 else if ((size_t)offset
>= offsetof(PyHeapTypeObject
, as_number
)) {
6028 ptr
= (char *)type
->tp_as_number
;
6029 offset
-= offsetof(PyHeapTypeObject
, as_number
);
6036 return (void **)ptr
;
6039 /* Length of array of slotdef pointers used to store slots with the
6040 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6041 the same __name__, for any __name__. Since that's a static property, it is
6042 appropriate to declare fixed-size arrays for this. */
6043 #define MAX_EQUIV 10
6045 /* Return a slot pointer for a given name, but ONLY if the attribute has
6046 exactly one slot function. The name must be an interned string. */
6048 resolve_slotdups(PyTypeObject
*type
, PyObject
*name
)
6050 /* XXX Maybe this could be optimized more -- but is it worth it? */
6052 /* pname and ptrs act as a little cache */
6053 static PyObject
*pname
;
6054 static slotdef
*ptrs
[MAX_EQUIV
];
6058 if (pname
!= name
) {
6059 /* Collect all slotdefs that match name into ptrs. */
6062 for (p
= slotdefs
; p
->name_strobj
; p
++) {
6063 if (p
->name_strobj
== name
)
6069 /* Look in all matching slots of the type; if exactly one of these has
6070 a filled-in slot, return its value. Otherwise return NULL. */
6072 for (pp
= ptrs
; *pp
; pp
++) {
6073 ptr
= slotptr(type
, (*pp
)->offset
);
6074 if (ptr
== NULL
|| *ptr
== NULL
)
6083 /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
6084 does some incredibly complex thinking and then sticks something into the
6085 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6086 interests, and then stores a generic wrapper or a specific function into
6087 the slot.) Return a pointer to the next slotdef with a different offset,
6088 because that's convenient for fixup_slot_dispatchers(). */
6090 update_one_slot(PyTypeObject
*type
, slotdef
*p
)
6093 PyWrapperDescrObject
*d
;
6094 void *generic
= NULL
, *specific
= NULL
;
6095 int use_generic
= 0;
6096 int offset
= p
->offset
;
6097 void **ptr
= slotptr(type
, offset
);
6102 } while (p
->offset
== offset
);
6106 descr
= _PyType_Lookup(type
, p
->name_strobj
);
6107 if (descr
== NULL
) {
6108 if (ptr
== (void**)&type
->tp_iternext
) {
6109 specific
= _PyObject_NextNotImplemented
;
6113 if (Py_TYPE(descr
) == &PyWrapperDescr_Type
) {
6114 void **tptr
= resolve_slotdups(type
, p
->name_strobj
);
6115 if (tptr
== NULL
|| tptr
== ptr
)
6116 generic
= p
->function
;
6117 d
= (PyWrapperDescrObject
*)descr
;
6118 if (d
->d_base
->wrapper
== p
->wrapper
&&
6119 PyType_IsSubtype(type
, d
->d_type
))
6121 if (specific
== NULL
||
6122 specific
== d
->d_wrapped
)
6123 specific
= d
->d_wrapped
;
6128 else if (Py_TYPE(descr
) == &PyCFunction_Type
&&
6129 PyCFunction_GET_FUNCTION(descr
) ==
6130 (PyCFunction
)tp_new_wrapper
&&
6131 ptr
== (void**)&type
->tp_new
)
6133 /* The __new__ wrapper is not a wrapper descriptor,
6134 so must be special-cased differently.
6135 If we don't do this, creating an instance will
6136 always use slot_tp_new which will look up
6137 __new__ in the MRO which will call tp_new_wrapper
6138 which will look through the base classes looking
6139 for a static base and call its tp_new (usually
6140 PyType_GenericNew), after performing various
6141 sanity checks and constructing a new argument
6142 list. Cut all that nonsense short -- this speeds
6143 up instance creation tremendously. */
6144 specific
= (void *)type
->tp_new
;
6145 /* XXX I'm not 100% sure that there isn't a hole
6146 in this reasoning that requires additional
6147 sanity checks. I'll buy the first person to
6148 point out a bug in this reasoning a beer. */
6150 else if (descr
== Py_None
&&
6151 ptr
== (void**)&type
->tp_hash
) {
6152 /* We specifically allow __hash__ to be set to None
6153 to prevent inheritance of the default
6154 implementation from object.__hash__ */
6155 specific
= PyObject_HashNotImplemented
;
6159 generic
= p
->function
;
6161 } while ((++p
)->offset
== offset
);
6162 if (specific
&& !use_generic
)
6169 /* In the type, update the slots whose slotdefs are gathered in the pp array.
6170 This is a callback for update_subclasses(). */
6172 update_slots_callback(PyTypeObject
*type
, void *data
)
6174 slotdef
**pp
= (slotdef
**)data
;
6177 update_one_slot(type
, *pp
);
6181 /* Comparison function for qsort() to compare slotdefs by their offset, and
6182 for equal offset by their address (to force a stable sort). */
6184 slotdef_cmp(const void *aa
, const void *bb
)
6186 const slotdef
*a
= (const slotdef
*)aa
, *b
= (const slotdef
*)bb
;
6187 int c
= a
->offset
- b
->offset
;
6191 /* Cannot use a-b, as this gives off_t,
6192 which may lose precision when converted to int. */
6193 return (a
> b
) ? 1 : (a
< b
) ? -1 : 0;
6196 /* Initialize the slotdefs table by adding interned string objects for the
6197 names and sorting the entries. */
6202 static int initialized
= 0;
6206 for (p
= slotdefs
; p
->name
; p
++) {
6207 p
->name_strobj
= PyString_InternFromString(p
->name
);
6208 if (!p
->name_strobj
)
6209 Py_FatalError("Out of memory interning slotdef names");
6211 qsort((void *)slotdefs
, (size_t)(p
-slotdefs
), sizeof(slotdef
),
6216 /* Update the slots after assignment to a class (type) attribute. */
6218 update_slot(PyTypeObject
*type
, PyObject
*name
)
6220 slotdef
*ptrs
[MAX_EQUIV
];
6225 /* Clear the VALID_VERSION flag of 'type' and all its
6226 subclasses. This could possibly be unified with the
6227 update_subclasses() recursion below, but carefully:
6228 they each have their own conditions on which to stop
6229 recursing into subclasses. */
6230 PyType_Modified(type
);
6234 for (p
= slotdefs
; p
->name
; p
++) {
6235 /* XXX assume name is interned! */
6236 if (p
->name_strobj
== name
)
6240 for (pp
= ptrs
; *pp
; pp
++) {
6243 while (p
> slotdefs
&& (p
-1)->offset
== offset
)
6247 if (ptrs
[0] == NULL
)
6248 return 0; /* Not an attribute that affects any slots */
6249 return update_subclasses(type
, name
,
6250 update_slots_callback
, (void *)ptrs
);
6253 /* Store the proper functions in the slot dispatches at class (type)
6254 definition time, based upon which operations the class overrides in its
6257 fixup_slot_dispatchers(PyTypeObject
*type
)
6262 for (p
= slotdefs
; p
->name
; )
6263 p
= update_one_slot(type
, p
);
6267 update_all_slots(PyTypeObject
* type
)
6272 for (p
= slotdefs
; p
->name
; p
++) {
6273 /* update_slot returns int but can't actually fail */
6274 update_slot(type
, p
->name_strobj
);
6278 /* recurse_down_subclasses() and update_subclasses() are mutually
6279 recursive functions to call a callback for all subclasses,
6280 but refraining from recursing into subclasses that define 'name'. */
6283 update_subclasses(PyTypeObject
*type
, PyObject
*name
,
6284 update_callback callback
, void *data
)
6286 if (callback(type
, data
) < 0)
6288 return recurse_down_subclasses(type
, name
, callback
, data
);
6292 recurse_down_subclasses(PyTypeObject
*type
, PyObject
*name
,
6293 update_callback callback
, void *data
)
6295 PyTypeObject
*subclass
;
6296 PyObject
*ref
, *subclasses
, *dict
;
6299 subclasses
= type
->tp_subclasses
;
6300 if (subclasses
== NULL
)
6302 assert(PyList_Check(subclasses
));
6303 n
= PyList_GET_SIZE(subclasses
);
6304 for (i
= 0; i
< n
; i
++) {
6305 ref
= PyList_GET_ITEM(subclasses
, i
);
6306 assert(PyWeakref_CheckRef(ref
));
6307 subclass
= (PyTypeObject
*)PyWeakref_GET_OBJECT(ref
);
6308 assert(subclass
!= NULL
);
6309 if ((PyObject
*)subclass
== Py_None
)
6311 assert(PyType_Check(subclass
));
6312 /* Avoid recursing down into unaffected classes */
6313 dict
= subclass
->tp_dict
;
6314 if (dict
!= NULL
&& PyDict_Check(dict
) &&
6315 PyDict_GetItem(dict
, name
) != NULL
)
6317 if (update_subclasses(subclass
, name
, callback
, data
) < 0)
6323 /* This function is called by PyType_Ready() to populate the type's
6324 dictionary with method descriptors for function slots. For each
6325 function slot (like tp_repr) that's defined in the type, one or more
6326 corresponding descriptors are added in the type's tp_dict dictionary
6327 under the appropriate name (like __repr__). Some function slots
6328 cause more than one descriptor to be added (for example, the nb_add
6329 slot adds both __add__ and __radd__ descriptors) and some function
6330 slots compete for the same descriptor (for example both sq_item and
6331 mp_subscript generate a __getitem__ descriptor).
6333 In the latter case, the first slotdef entry encoutered wins. Since
6334 slotdef entries are sorted by the offset of the slot in the
6335 PyHeapTypeObject, this gives us some control over disambiguating
6336 between competing slots: the members of PyHeapTypeObject are listed
6337 from most general to least general, so the most general slot is
6338 preferred. In particular, because as_mapping comes before as_sequence,
6339 for a type that defines both mp_subscript and sq_item, mp_subscript
6342 This only adds new descriptors and doesn't overwrite entries in
6343 tp_dict that were previously defined. The descriptors contain a
6344 reference to the C function they must call, so that it's safe if they
6345 are copied into a subtype's __dict__ and the subtype has a different
6346 C function in its slot -- calling the method defined by the
6347 descriptor will call the C function that was used to create it,
6348 rather than the C function present in the slot when it is called.
6349 (This is important because a subtype may have a C function in the
6350 slot that calls the method from the dictionary, and we want to avoid
6351 infinite recursion here.) */
6354 add_operators(PyTypeObject
*type
)
6356 PyObject
*dict
= type
->tp_dict
;
6362 for (p
= slotdefs
; p
->name
; p
++) {
6363 if (p
->wrapper
== NULL
)
6365 ptr
= slotptr(type
, p
->offset
);
6368 if (PyDict_GetItem(dict
, p
->name_strobj
))
6370 if (*ptr
== PyObject_HashNotImplemented
) {
6371 /* Classes may prevent the inheritance of the tp_hash
6372 slot by storing PyObject_HashNotImplemented in it. Make it
6373 visible as a None value for the __hash__ attribute. */
6374 if (PyDict_SetItem(dict
, p
->name_strobj
, Py_None
) < 0)
6378 descr
= PyDescr_NewWrapper(type
, p
, *ptr
);
6381 if (PyDict_SetItem(dict
, p
->name_strobj
, descr
) < 0)
6386 if (type
->tp_new
!= NULL
) {
6387 if (add_tp_new_wrapper(type
) < 0)
6394 /* Cooperative 'super' */
6400 PyTypeObject
*obj_type
;
6403 static PyMemberDef super_members
[] = {
6404 {"__thisclass__", T_OBJECT
, offsetof(superobject
, type
), READONLY
,
6405 "the class invoking super()"},
6406 {"__self__", T_OBJECT
, offsetof(superobject
, obj
), READONLY
,
6407 "the instance invoking super(); may be None"},
6408 {"__self_class__", T_OBJECT
, offsetof(superobject
, obj_type
), READONLY
,
6409 "the type of the instance invoking super(); may be None"},
6414 super_dealloc(PyObject
*self
)
6416 superobject
*su
= (superobject
*)self
;
6418 _PyObject_GC_UNTRACK(self
);
6419 Py_XDECREF(su
->obj
);
6420 Py_XDECREF(su
->type
);
6421 Py_XDECREF(su
->obj_type
);
6422 Py_TYPE(self
)->tp_free(self
);
6426 super_repr(PyObject
*self
)
6428 superobject
*su
= (superobject
*)self
;
6431 return PyString_FromFormat(
6432 "<super: <class '%s'>, <%s object>>",
6433 su
->type
? su
->type
->tp_name
: "NULL",
6434 su
->obj_type
->tp_name
);
6436 return PyString_FromFormat(
6437 "<super: <class '%s'>, NULL>",
6438 su
->type
? su
->type
->tp_name
: "NULL");
6442 super_getattro(PyObject
*self
, PyObject
*name
)
6444 superobject
*su
= (superobject
*)self
;
6445 int skip
= su
->obj_type
== NULL
;
6448 /* We want __class__ to return the class of the super object
6449 (i.e. super, or a subclass), not the class of su->obj. */
6450 skip
= (PyString_Check(name
) &&
6451 PyString_GET_SIZE(name
) == 9 &&
6452 strcmp(PyString_AS_STRING(name
), "__class__") == 0);
6456 PyObject
*mro
, *res
, *tmp
, *dict
;
6457 PyTypeObject
*starttype
;
6461 starttype
= su
->obj_type
;
6462 mro
= starttype
->tp_mro
;
6467 assert(PyTuple_Check(mro
));
6468 n
= PyTuple_GET_SIZE(mro
);
6470 for (i
= 0; i
< n
; i
++) {
6471 if ((PyObject
*)(su
->type
) == PyTuple_GET_ITEM(mro
, i
))
6476 for (; i
< n
; i
++) {
6477 tmp
= PyTuple_GET_ITEM(mro
, i
);
6478 if (PyType_Check(tmp
))
6479 dict
= ((PyTypeObject
*)tmp
)->tp_dict
;
6480 else if (PyClass_Check(tmp
))
6481 dict
= ((PyClassObject
*)tmp
)->cl_dict
;
6484 res
= PyDict_GetItem(dict
, name
);
6487 f
= Py_TYPE(res
)->tp_descr_get
;
6490 /* Only pass 'obj' param if
6491 this is instance-mode super
6494 (su
->obj
== (PyObject
*)
6498 (PyObject
*)starttype
);
6506 return PyObject_GenericGetAttr(self
, name
);
6509 static PyTypeObject
*
6510 supercheck(PyTypeObject
*type
, PyObject
*obj
)
6512 /* Check that a super() call makes sense. Return a type object.
6514 obj can be a new-style class, or an instance of one:
6516 - If it is a class, it must be a subclass of 'type'. This case is
6517 used for class methods; the return value is obj.
6519 - If it is an instance, it must be an instance of 'type'. This is
6520 the normal case; the return value is obj.__class__.
6522 But... when obj is an instance, we want to allow for the case where
6523 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6524 This will allow using super() with a proxy for obj.
6527 /* Check for first bullet above (special case) */
6528 if (PyType_Check(obj
) && PyType_IsSubtype((PyTypeObject
*)obj
, type
)) {
6530 return (PyTypeObject
*)obj
;
6534 if (PyType_IsSubtype(Py_TYPE(obj
), type
)) {
6535 Py_INCREF(Py_TYPE(obj
));
6536 return Py_TYPE(obj
);
6539 /* Try the slow way */
6540 static PyObject
*class_str
= NULL
;
6541 PyObject
*class_attr
;
6543 if (class_str
== NULL
) {
6544 class_str
= PyString_FromString("__class__");
6545 if (class_str
== NULL
)
6549 class_attr
= PyObject_GetAttr(obj
, class_str
);
6551 if (class_attr
!= NULL
&&
6552 PyType_Check(class_attr
) &&
6553 (PyTypeObject
*)class_attr
!= Py_TYPE(obj
))
6555 int ok
= PyType_IsSubtype(
6556 (PyTypeObject
*)class_attr
, type
);
6558 return (PyTypeObject
*)class_attr
;
6561 if (class_attr
== NULL
)
6564 Py_DECREF(class_attr
);
6567 PyErr_SetString(PyExc_TypeError
,
6568 "super(type, obj): "
6569 "obj must be an instance or subtype of type");
6574 super_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
6576 superobject
*su
= (superobject
*)self
;
6577 superobject
*newobj
;
6579 if (obj
== NULL
|| obj
== Py_None
|| su
->obj
!= NULL
) {
6580 /* Not binding to an object, or already bound */
6584 if (Py_TYPE(su
) != &PySuper_Type
)
6585 /* If su is an instance of a (strict) subclass of super,
6587 return PyObject_CallFunctionObjArgs((PyObject
*)Py_TYPE(su
),
6588 su
->type
, obj
, NULL
);
6590 /* Inline the common case */
6591 PyTypeObject
*obj_type
= supercheck(su
->type
, obj
);
6592 if (obj_type
== NULL
)
6594 newobj
= (superobject
*)PySuper_Type
.tp_new(&PySuper_Type
,
6598 Py_INCREF(su
->type
);
6600 newobj
->type
= su
->type
;
6602 newobj
->obj_type
= obj_type
;
6603 return (PyObject
*)newobj
;
6608 super_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
6610 superobject
*su
= (superobject
*)self
;
6612 PyObject
*obj
= NULL
;
6613 PyTypeObject
*obj_type
= NULL
;
6615 if (!_PyArg_NoKeywords("super", kwds
))
6617 if (!PyArg_ParseTuple(args
, "O!|O:super", &PyType_Type
, &type
, &obj
))
6622 obj_type
= supercheck(type
, obj
);
6623 if (obj_type
== NULL
)
6630 su
->obj_type
= obj_type
;
6634 PyDoc_STRVAR(super_doc
,
6635 "super(type) -> unbound super object\n"
6636 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
6637 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
6638 "Typical use to call a cooperative superclass method:\n"
6640 " def meth(self, arg):\n"
6641 " super(C, self).meth(arg)");
6644 super_traverse(PyObject
*self
, visitproc visit
, void *arg
)
6646 superobject
*su
= (superobject
*)self
;
6650 Py_VISIT(su
->obj_type
);
6655 PyTypeObject PySuper_Type
= {
6656 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
6657 "super", /* tp_name */
6658 sizeof(superobject
), /* tp_basicsize */
6659 0, /* tp_itemsize */
6661 super_dealloc
, /* tp_dealloc */
6666 super_repr
, /* tp_repr */
6667 0, /* tp_as_number */
6668 0, /* tp_as_sequence */
6669 0, /* tp_as_mapping */
6673 super_getattro
, /* tp_getattro */
6674 0, /* tp_setattro */
6675 0, /* tp_as_buffer */
6676 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
6677 Py_TPFLAGS_BASETYPE
, /* tp_flags */
6678 super_doc
, /* tp_doc */
6679 super_traverse
, /* tp_traverse */
6681 0, /* tp_richcompare */
6682 0, /* tp_weaklistoffset */
6684 0, /* tp_iternext */
6686 super_members
, /* tp_members */
6690 super_descr_get
, /* tp_descr_get */
6691 0, /* tp_descr_set */
6692 0, /* tp_dictoffset */
6693 super_init
, /* tp_init */
6694 PyType_GenericAlloc
, /* tp_alloc */
6695 PyType_GenericNew
, /* tp_new */
6696 PyObject_GC_Del
, /* tp_free */