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;
35 static void type_modified(PyTypeObject
*);
38 PyType_ClearCache(void)
41 unsigned int cur_version_tag
= next_version_tag
- 1;
43 for (i
= 0; i
< (1 << MCACHE_SIZE_EXP
); i
++) {
44 method_cache
[i
].version
= 0;
45 Py_CLEAR(method_cache
[i
].name
);
46 method_cache
[i
].value
= NULL
;
49 /* mark all version tags as invalid */
50 type_modified(&PyBaseObject_Type
);
51 return cur_version_tag
;
55 type_modified(PyTypeObject
*type
)
57 /* Invalidate any cached data for the specified type and all
58 subclasses. This function is called after the base
59 classes, mro, or attributes of the type are altered.
63 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
64 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
65 objects coming from non-recompiled extension modules)
67 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
68 it must first be set on all super types.
70 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
71 type (so it must first clear it on all subclasses). The
72 tp_version_tag value is meaningless unless this flag is set.
73 We don't assign new version tags eagerly, but only as
79 if (!PyType_HasFeature(type
, Py_TPFLAGS_VALID_VERSION_TAG
))
82 raw
= type
->tp_subclasses
;
84 n
= PyList_GET_SIZE(raw
);
85 for (i
= 0; i
< n
; i
++) {
86 ref
= PyList_GET_ITEM(raw
, i
);
87 ref
= PyWeakref_GET_OBJECT(ref
);
89 type_modified((PyTypeObject
*)ref
);
93 type
->tp_flags
&= ~Py_TPFLAGS_VALID_VERSION_TAG
;
97 type_mro_modified(PyTypeObject
*type
, PyObject
*bases
) {
99 Check that all base classes or elements of the mro of type are
100 able to be cached. This function is called after the base
101 classes or mro of the type are altered.
103 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
104 inherits from an old-style class, either directly or if it
105 appears in the MRO of a new-style class. No support either for
106 custom MROs that include types that are not officially super
109 Called from mro_internal, which will subsequently be called on
110 each subclass when their mro is recursively updated.
115 if (!PyType_HasFeature(type
, Py_TPFLAGS_HAVE_VERSION_TAG
))
118 n
= PyTuple_GET_SIZE(bases
);
119 for (i
= 0; i
< n
; i
++) {
120 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
123 if (!PyType_Check(b
) ) {
128 cls
= (PyTypeObject
*)b
;
130 if (!PyType_HasFeature(cls
, Py_TPFLAGS_HAVE_VERSION_TAG
) ||
131 !PyType_IsSubtype(type
, cls
)) {
138 type
->tp_flags
&= ~(Py_TPFLAGS_HAVE_VERSION_TAG
|
139 Py_TPFLAGS_VALID_VERSION_TAG
);
143 assign_version_tag(PyTypeObject
*type
)
145 /* Ensure that the tp_version_tag is valid and set
146 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
147 must first be done on all super classes. Return 0 if this
148 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
153 if (PyType_HasFeature(type
, Py_TPFLAGS_VALID_VERSION_TAG
))
155 if (!PyType_HasFeature(type
, Py_TPFLAGS_HAVE_VERSION_TAG
))
157 if (!PyType_HasFeature(type
, Py_TPFLAGS_READY
))
160 type
->tp_version_tag
= next_version_tag
++;
161 /* for stress-testing: next_version_tag &= 0xFF; */
163 if (type
->tp_version_tag
== 0) {
164 /* wrap-around or just starting Python - clear the whole
165 cache by filling names with references to Py_None.
166 Values are also set to NULL for added protection, as they
167 are borrowed reference */
168 for (i
= 0; i
< (1 << MCACHE_SIZE_EXP
); i
++) {
169 method_cache
[i
].value
= NULL
;
170 Py_XDECREF(method_cache
[i
].name
);
171 method_cache
[i
].name
= Py_None
;
174 /* mark all version tags as invalid */
175 type_modified(&PyBaseObject_Type
);
178 bases
= type
->tp_bases
;
179 n
= PyTuple_GET_SIZE(bases
);
180 for (i
= 0; i
< n
; i
++) {
181 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
182 assert(PyType_Check(b
));
183 if (!assign_version_tag((PyTypeObject
*)b
))
186 type
->tp_flags
|= Py_TPFLAGS_VALID_VERSION_TAG
;
191 static PyMemberDef type_members
[] = {
192 {"__basicsize__", T_INT
, offsetof(PyTypeObject
,tp_basicsize
),READONLY
},
193 {"__itemsize__", T_INT
, offsetof(PyTypeObject
, tp_itemsize
), READONLY
},
194 {"__flags__", T_LONG
, offsetof(PyTypeObject
, tp_flags
), READONLY
},
195 {"__weakrefoffset__", T_LONG
,
196 offsetof(PyTypeObject
, tp_weaklistoffset
), READONLY
},
197 {"__base__", T_OBJECT
, offsetof(PyTypeObject
, tp_base
), READONLY
},
198 {"__dictoffset__", T_LONG
,
199 offsetof(PyTypeObject
, tp_dictoffset
), READONLY
},
200 {"__mro__", T_OBJECT
, offsetof(PyTypeObject
, tp_mro
), READONLY
},
205 type_name(PyTypeObject
*type
, void *context
)
209 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
210 PyHeapTypeObject
* et
= (PyHeapTypeObject
*)type
;
212 Py_INCREF(et
->ht_name
);
216 s
= strrchr(type
->tp_name
, '.');
221 return PyString_FromString(s
);
226 type_set_name(PyTypeObject
*type
, PyObject
*value
, void *context
)
228 PyHeapTypeObject
* et
;
230 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
231 PyErr_Format(PyExc_TypeError
,
232 "can't set %s.__name__", type
->tp_name
);
236 PyErr_Format(PyExc_TypeError
,
237 "can't delete %s.__name__", type
->tp_name
);
240 if (!PyString_Check(value
)) {
241 PyErr_Format(PyExc_TypeError
,
242 "can only assign string to %s.__name__, not '%s'",
243 type
->tp_name
, Py_TYPE(value
)->tp_name
);
246 if (strlen(PyString_AS_STRING(value
))
247 != (size_t)PyString_GET_SIZE(value
)) {
248 PyErr_Format(PyExc_ValueError
,
249 "__name__ must not contain null bytes");
253 et
= (PyHeapTypeObject
*)type
;
257 Py_DECREF(et
->ht_name
);
260 type
->tp_name
= PyString_AS_STRING(value
);
266 type_module(PyTypeObject
*type
, void *context
)
271 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) {
272 mod
= PyDict_GetItemString(type
->tp_dict
, "__module__");
274 PyErr_Format(PyExc_AttributeError
, "__module__");
281 s
= strrchr(type
->tp_name
, '.');
283 return PyString_FromStringAndSize(
284 type
->tp_name
, (Py_ssize_t
)(s
- type
->tp_name
));
285 return PyString_FromString("__builtin__");
290 type_set_module(PyTypeObject
*type
, PyObject
*value
, void *context
)
292 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
293 PyErr_Format(PyExc_TypeError
,
294 "can't set %s.__module__", type
->tp_name
);
298 PyErr_Format(PyExc_TypeError
,
299 "can't delete %s.__module__", type
->tp_name
);
305 return PyDict_SetItemString(type
->tp_dict
, "__module__", value
);
309 type_abstractmethods(PyTypeObject
*type
, void *context
)
311 PyObject
*mod
= PyDict_GetItemString(type
->tp_dict
,
312 "__abstractmethods__");
314 PyErr_Format(PyExc_AttributeError
, "__abstractmethods__");
322 type_set_abstractmethods(PyTypeObject
*type
, PyObject
*value
, void *context
)
324 /* __abstractmethods__ should only be set once on a type, in
325 abc.ABCMeta.__new__, so this function doesn't do anything
326 special to update subclasses.
328 int res
= PyDict_SetItemString(type
->tp_dict
,
329 "__abstractmethods__", value
);
332 if (value
&& PyObject_IsTrue(value
)) {
333 type
->tp_flags
|= Py_TPFLAGS_IS_ABSTRACT
;
336 type
->tp_flags
&= ~Py_TPFLAGS_IS_ABSTRACT
;
343 type_get_bases(PyTypeObject
*type
, void *context
)
345 Py_INCREF(type
->tp_bases
);
346 return type
->tp_bases
;
349 static PyTypeObject
*best_base(PyObject
*);
350 static int mro_internal(PyTypeObject
*);
351 static int compatible_for_assignment(PyTypeObject
*, PyTypeObject
*, char *);
352 static int add_subclass(PyTypeObject
*, PyTypeObject
*);
353 static void remove_subclass(PyTypeObject
*, PyTypeObject
*);
354 static void update_all_slots(PyTypeObject
*);
356 typedef int (*update_callback
)(PyTypeObject
*, void *);
357 static int update_subclasses(PyTypeObject
*type
, PyObject
*name
,
358 update_callback callback
, void *data
);
359 static int recurse_down_subclasses(PyTypeObject
*type
, PyObject
*name
,
360 update_callback callback
, void *data
);
363 mro_subclasses(PyTypeObject
*type
, PyObject
* temp
)
365 PyTypeObject
*subclass
;
366 PyObject
*ref
, *subclasses
, *old_mro
;
369 subclasses
= type
->tp_subclasses
;
370 if (subclasses
== NULL
)
372 assert(PyList_Check(subclasses
));
373 n
= PyList_GET_SIZE(subclasses
);
374 for (i
= 0; i
< n
; i
++) {
375 ref
= PyList_GET_ITEM(subclasses
, i
);
376 assert(PyWeakref_CheckRef(ref
));
377 subclass
= (PyTypeObject
*)PyWeakref_GET_OBJECT(ref
);
378 assert(subclass
!= NULL
);
379 if ((PyObject
*)subclass
== Py_None
)
381 assert(PyType_Check(subclass
));
382 old_mro
= subclass
->tp_mro
;
383 if (mro_internal(subclass
) < 0) {
384 subclass
->tp_mro
= old_mro
;
389 tuple
= PyTuple_Pack(2, subclass
, old_mro
);
393 if (PyList_Append(temp
, tuple
) < 0)
397 if (mro_subclasses(subclass
, temp
) < 0)
404 type_set_bases(PyTypeObject
*type
, PyObject
*value
, void *context
)
409 PyTypeObject
*new_base
, *old_base
;
410 PyObject
*old_bases
, *old_mro
;
412 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
413 PyErr_Format(PyExc_TypeError
,
414 "can't set %s.__bases__", type
->tp_name
);
418 PyErr_Format(PyExc_TypeError
,
419 "can't delete %s.__bases__", type
->tp_name
);
422 if (!PyTuple_Check(value
)) {
423 PyErr_Format(PyExc_TypeError
,
424 "can only assign tuple to %s.__bases__, not %s",
425 type
->tp_name
, Py_TYPE(value
)->tp_name
);
428 if (PyTuple_GET_SIZE(value
) == 0) {
429 PyErr_Format(PyExc_TypeError
,
430 "can only assign non-empty tuple to %s.__bases__, not ()",
434 for (i
= 0; i
< PyTuple_GET_SIZE(value
); i
++) {
435 ob
= PyTuple_GET_ITEM(value
, i
);
436 if (!PyClass_Check(ob
) && !PyType_Check(ob
)) {
439 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
440 type
->tp_name
, Py_TYPE(ob
)->tp_name
);
443 if (PyType_Check(ob
)) {
444 if (PyType_IsSubtype((PyTypeObject
*)ob
, type
)) {
445 PyErr_SetString(PyExc_TypeError
,
446 "a __bases__ item causes an inheritance cycle");
452 new_base
= best_base(value
);
458 if (!compatible_for_assignment(type
->tp_base
, new_base
, "__bases__"))
464 old_bases
= type
->tp_bases
;
465 old_base
= type
->tp_base
;
466 old_mro
= type
->tp_mro
;
468 type
->tp_bases
= value
;
469 type
->tp_base
= new_base
;
471 if (mro_internal(type
) < 0) {
475 temp
= PyList_New(0);
479 r
= mro_subclasses(type
, temp
);
482 for (i
= 0; i
< PyList_Size(temp
); i
++) {
485 PyArg_UnpackTuple(PyList_GET_ITEM(temp
, i
),
486 "", 2, 2, &cls
, &mro
);
498 /* any base that was in __bases__ but now isn't, we
499 need to remove |type| from its tp_subclasses.
500 conversely, any class now in __bases__ that wasn't
501 needs to have |type| added to its subclasses. */
503 /* for now, sod that: just remove from all old_bases,
504 add to all new_bases */
506 for (i
= PyTuple_GET_SIZE(old_bases
) - 1; i
>= 0; i
--) {
507 ob
= PyTuple_GET_ITEM(old_bases
, i
);
508 if (PyType_Check(ob
)) {
510 (PyTypeObject
*)ob
, type
);
514 for (i
= PyTuple_GET_SIZE(value
) - 1; i
>= 0; i
--) {
515 ob
= PyTuple_GET_ITEM(value
, i
);
516 if (PyType_Check(ob
)) {
517 if (add_subclass((PyTypeObject
*)ob
, type
) < 0)
522 update_all_slots(type
);
524 Py_DECREF(old_bases
);
531 Py_DECREF(type
->tp_bases
);
532 Py_DECREF(type
->tp_base
);
533 if (type
->tp_mro
!= old_mro
) {
534 Py_DECREF(type
->tp_mro
);
537 type
->tp_bases
= old_bases
;
538 type
->tp_base
= old_base
;
539 type
->tp_mro
= old_mro
;
545 type_dict(PyTypeObject
*type
, void *context
)
547 if (type
->tp_dict
== NULL
) {
551 return PyDictProxy_New(type
->tp_dict
);
555 type_get_doc(PyTypeObject
*type
, void *context
)
558 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) && type
->tp_doc
!= NULL
)
559 return PyString_FromString(type
->tp_doc
);
560 result
= PyDict_GetItemString(type
->tp_dict
, "__doc__");
561 if (result
== NULL
) {
565 else if (Py_TYPE(result
)->tp_descr_get
) {
566 result
= Py_TYPE(result
)->tp_descr_get(result
, NULL
,
575 static PyGetSetDef type_getsets
[] = {
576 {"__name__", (getter
)type_name
, (setter
)type_set_name
, NULL
},
577 {"__bases__", (getter
)type_get_bases
, (setter
)type_set_bases
, NULL
},
578 {"__module__", (getter
)type_module
, (setter
)type_set_module
, NULL
},
579 {"__abstractmethods__", (getter
)type_abstractmethods
,
580 (setter
)type_set_abstractmethods
, NULL
},
581 {"__dict__", (getter
)type_dict
, NULL
, NULL
},
582 {"__doc__", (getter
)type_get_doc
, NULL
, NULL
},
587 type_compare(PyObject
*v
, PyObject
*w
)
589 /* This is called with type objects only. So we
590 can just compare the addresses. */
591 Py_uintptr_t vv
= (Py_uintptr_t
)v
;
592 Py_uintptr_t ww
= (Py_uintptr_t
)w
;
593 return (vv
< ww
) ? -1 : (vv
> ww
) ? 1 : 0;
597 type_richcompare(PyObject
*v
, PyObject
*w
, int op
)
603 /* Make sure both arguments are types. */
604 if (!PyType_Check(v
) || !PyType_Check(w
)) {
605 result
= Py_NotImplemented
;
609 /* Py3K warning if comparison isn't == or != */
610 if (Py_Py3kWarningFlag
&& op
!= Py_EQ
&& op
!= Py_NE
&&
611 PyErr_WarnEx(PyExc_DeprecationWarning
,
612 "type inequality comparisons not supported "
617 /* Compare addresses */
618 vv
= (Py_uintptr_t
)v
;
619 ww
= (Py_uintptr_t
)w
;
621 case Py_LT
: c
= vv
< ww
; break;
622 case Py_LE
: c
= vv
<= ww
; break;
623 case Py_EQ
: c
= vv
== ww
; break;
624 case Py_NE
: c
= vv
!= ww
; break;
625 case Py_GT
: c
= vv
> ww
; break;
626 case Py_GE
: c
= vv
>= ww
; break;
628 result
= Py_NotImplemented
;
631 result
= c
? Py_True
: Py_False
;
633 /* incref and return */
640 type_repr(PyTypeObject
*type
)
642 PyObject
*mod
, *name
, *rtn
;
645 mod
= type_module(type
, NULL
);
648 else if (!PyString_Check(mod
)) {
652 name
= type_name(type
, NULL
);
656 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
661 if (mod
!= NULL
&& strcmp(PyString_AS_STRING(mod
), "__builtin__")) {
662 rtn
= PyString_FromFormat("<%s '%s.%s'>",
664 PyString_AS_STRING(mod
),
665 PyString_AS_STRING(name
));
668 rtn
= PyString_FromFormat("<%s '%s'>", kind
, type
->tp_name
);
676 type_call(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
680 if (type
->tp_new
== NULL
) {
681 PyErr_Format(PyExc_TypeError
,
682 "cannot create '%.100s' instances",
687 obj
= type
->tp_new(type
, args
, kwds
);
689 /* Ugly exception: when the call was type(something),
690 don't call tp_init on the result. */
691 if (type
== &PyType_Type
&&
692 PyTuple_Check(args
) && PyTuple_GET_SIZE(args
) == 1 &&
694 (PyDict_Check(kwds
) && PyDict_Size(kwds
) == 0)))
696 /* If the returned object is not an instance of type,
697 it won't be initialized. */
698 if (!PyType_IsSubtype(obj
->ob_type
, type
))
701 if (PyType_HasFeature(type
, Py_TPFLAGS_HAVE_CLASS
) &&
702 type
->tp_init
!= NULL
&&
703 type
->tp_init(obj
, args
, kwds
) < 0) {
712 PyType_GenericAlloc(PyTypeObject
*type
, Py_ssize_t nitems
)
715 const size_t size
= _PyObject_VAR_SIZE(type
, nitems
+1);
716 /* note that we need to add one, for the sentinel */
718 if (PyType_IS_GC(type
))
719 obj
= _PyObject_GC_Malloc(size
);
721 obj
= (PyObject
*)PyObject_MALLOC(size
);
724 return PyErr_NoMemory();
726 memset(obj
, '\0', size
);
728 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
731 if (type
->tp_itemsize
== 0)
732 PyObject_INIT(obj
, type
);
734 (void) PyObject_INIT_VAR((PyVarObject
*)obj
, type
, nitems
);
736 if (PyType_IS_GC(type
))
737 _PyObject_GC_TRACK(obj
);
742 PyType_GenericNew(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
744 return type
->tp_alloc(type
, 0);
747 /* Helpers for subtyping */
750 traverse_slots(PyTypeObject
*type
, PyObject
*self
, visitproc visit
, void *arg
)
756 mp
= PyHeapType_GET_MEMBERS((PyHeapTypeObject
*)type
);
757 for (i
= 0; i
< n
; i
++, mp
++) {
758 if (mp
->type
== T_OBJECT_EX
) {
759 char *addr
= (char *)self
+ mp
->offset
;
760 PyObject
*obj
= *(PyObject
**)addr
;
762 int err
= visit(obj
, arg
);
772 subtype_traverse(PyObject
*self
, visitproc visit
, void *arg
)
774 PyTypeObject
*type
, *base
;
775 traverseproc basetraverse
;
777 /* Find the nearest base with a different tp_traverse,
778 and traverse slots while we're at it */
779 type
= Py_TYPE(self
);
781 while ((basetraverse
= base
->tp_traverse
) == subtype_traverse
) {
783 int err
= traverse_slots(base
, self
, visit
, arg
);
787 base
= base
->tp_base
;
791 if (type
->tp_dictoffset
!= base
->tp_dictoffset
) {
792 PyObject
**dictptr
= _PyObject_GetDictPtr(self
);
793 if (dictptr
&& *dictptr
)
797 if (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
798 /* For a heaptype, the instances count as references
799 to the type. Traverse the type so the collector
800 can find cycles involving this link. */
804 return basetraverse(self
, visit
, arg
);
809 clear_slots(PyTypeObject
*type
, PyObject
*self
)
815 mp
= PyHeapType_GET_MEMBERS((PyHeapTypeObject
*)type
);
816 for (i
= 0; i
< n
; i
++, mp
++) {
817 if (mp
->type
== T_OBJECT_EX
&& !(mp
->flags
& READONLY
)) {
818 char *addr
= (char *)self
+ mp
->offset
;
819 PyObject
*obj
= *(PyObject
**)addr
;
821 *(PyObject
**)addr
= NULL
;
829 subtype_clear(PyObject
*self
)
831 PyTypeObject
*type
, *base
;
834 /* Find the nearest base with a different tp_clear
835 and clear slots while we're at it */
836 type
= Py_TYPE(self
);
838 while ((baseclear
= base
->tp_clear
) == subtype_clear
) {
840 clear_slots(base
, self
);
841 base
= base
->tp_base
;
845 /* There's no need to clear the instance dict (if any);
846 the collector will call its tp_clear handler. */
849 return baseclear(self
);
854 subtype_dealloc(PyObject
*self
)
856 PyTypeObject
*type
, *base
;
857 destructor basedealloc
;
859 /* Extract the type; we expect it to be a heap type */
860 type
= Py_TYPE(self
);
861 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
863 /* Test whether the type has GC exactly once */
865 if (!PyType_IS_GC(type
)) {
866 /* It's really rare to find a dynamic type that doesn't have
867 GC; it can only happen when deriving from 'object' and not
868 adding any slots or instance variables. This allows
869 certain simplifications: there's no need to call
870 clear_slots(), or DECREF the dict, or clear weakrefs. */
872 /* Maybe call finalizer; exit early if resurrected */
875 if (self
->ob_refcnt
> 0)
879 /* Find the nearest base with a different tp_dealloc */
881 while ((basedealloc
= base
->tp_dealloc
) == subtype_dealloc
) {
882 assert(Py_SIZE(base
) == 0);
883 base
= base
->tp_base
;
887 /* Call the base tp_dealloc() */
891 /* Can't reference self beyond this point */
898 /* We get here only if the type has GC */
900 /* UnTrack and re-Track around the trashcan macro, alas */
901 /* See explanation at end of function for full disclosure */
902 PyObject_GC_UnTrack(self
);
903 ++_PyTrash_delete_nesting
;
904 Py_TRASHCAN_SAFE_BEGIN(self
);
905 --_PyTrash_delete_nesting
;
906 /* DO NOT restore GC tracking at this point. weakref callbacks
907 * (if any, and whether directly here or indirectly in something we
908 * call) may trigger GC, and if self is tracked at that point, it
909 * will look like trash to GC and GC will try to delete self again.
912 /* Find the nearest base with a different tp_dealloc */
914 while ((basedealloc
= base
->tp_dealloc
) == subtype_dealloc
) {
915 base
= base
->tp_base
;
919 /* If we added a weaklist, we clear it. Do this *before* calling
920 the finalizer (__del__), clearing slots, or clearing the instance
923 if (type
->tp_weaklistoffset
&& !base
->tp_weaklistoffset
)
924 PyObject_ClearWeakRefs(self
);
926 /* Maybe call finalizer; exit early if resurrected */
928 _PyObject_GC_TRACK(self
);
930 if (self
->ob_refcnt
> 0)
931 goto endlabel
; /* resurrected */
933 _PyObject_GC_UNTRACK(self
);
934 /* New weakrefs could be created during the finalizer call.
935 If this occurs, clear them out without calling their
936 finalizers since they might rely on part of the object
937 being finalized that has already been destroyed. */
938 if (type
->tp_weaklistoffset
&& !base
->tp_weaklistoffset
) {
939 /* Modeled after GET_WEAKREFS_LISTPTR() */
940 PyWeakReference
**list
= (PyWeakReference
**) \
941 PyObject_GET_WEAKREFS_LISTPTR(self
);
943 _PyWeakref_ClearRef(*list
);
947 /* Clear slots up to the nearest base with a different tp_dealloc */
949 while ((basedealloc
= base
->tp_dealloc
) == subtype_dealloc
) {
951 clear_slots(base
, self
);
952 base
= base
->tp_base
;
956 /* If we added a dict, DECREF it */
957 if (type
->tp_dictoffset
&& !base
->tp_dictoffset
) {
958 PyObject
**dictptr
= _PyObject_GetDictPtr(self
);
959 if (dictptr
!= NULL
) {
960 PyObject
*dict
= *dictptr
;
968 /* Call the base tp_dealloc(); first retrack self if
969 * basedealloc knows about gc.
971 if (PyType_IS_GC(base
))
972 _PyObject_GC_TRACK(self
);
976 /* Can't reference self beyond this point */
980 ++_PyTrash_delete_nesting
;
981 Py_TRASHCAN_SAFE_END(self
);
982 --_PyTrash_delete_nesting
;
984 /* Explanation of the weirdness around the trashcan macros:
986 Q. What do the trashcan macros do?
988 A. Read the comment titled "Trashcan mechanism" in object.h.
989 For one, this explains why there must be a call to GC-untrack
990 before the trashcan begin macro. Without understanding the
991 trashcan code, the answers to the following questions don't make
994 Q. Why do we GC-untrack before the trashcan and then immediately
995 GC-track again afterward?
997 A. In the case that the base class is GC-aware, the base class
998 probably GC-untracks the object. If it does that using the
999 UNTRACK macro, this will crash when the object is already
1000 untracked. Because we don't know what the base class does, the
1001 only safe thing is to make sure the object is tracked when we
1002 call the base class dealloc. But... The trashcan begin macro
1003 requires that the object is *untracked* before it is called. So
1010 Q. Why did the last question say "immediately GC-track again"?
1011 It's nowhere near immediately.
1013 A. Because the code *used* to re-track immediately. Bad Idea.
1014 self has a refcount of 0, and if gc ever gets its hands on it
1015 (which can happen if any weakref callback gets invoked), it
1016 looks like trash to gc too, and gc also tries to delete self
1017 then. But we're already deleting self. Double dealloction is
1020 Q. Why the bizarre (net-zero) manipulation of
1021 _PyTrash_delete_nesting around the trashcan macros?
1023 A. Some base classes (e.g. list) also use the trashcan mechanism.
1024 The following scenario used to be possible:
1026 - suppose the trashcan level is one below the trashcan limit
1028 - subtype_dealloc() is called
1030 - the trashcan limit is not yet reached, so the trashcan level
1031 is incremented and the code between trashcan begin and end is
1034 - this destroys much of the object's contents, including its
1037 - basedealloc() is called; this is really list_dealloc(), or
1038 some other type which also uses the trashcan macros
1040 - the trashcan limit is now reached, so the object is put on the
1041 trashcan's to-be-deleted-later list
1043 - basedealloc() returns
1045 - subtype_dealloc() decrefs the object's type
1047 - subtype_dealloc() returns
1049 - later, the trashcan code starts deleting the objects from its
1050 to-be-deleted-later list
1052 - subtype_dealloc() is called *AGAIN* for the same object
1054 - at the very least (if the destroyed slots and __dict__ don't
1055 cause problems) the object's type gets decref'ed a second
1056 time, which is *BAD*!!!
1058 The remedy is to make sure that if the code between trashcan
1059 begin and end in subtype_dealloc() is called, the code between
1060 trashcan begin and end in basedealloc() will also be called.
1061 This is done by decrementing the level after passing into the
1062 trashcan block, and incrementing it just before leaving the
1065 But now it's possible that a chain of objects consisting solely
1066 of objects whose deallocator is subtype_dealloc() will defeat
1067 the trashcan mechanism completely: the decremented level means
1068 that the effective level never reaches the limit. Therefore, we
1069 *increment* the level *before* entering the trashcan block, and
1070 matchingly decrement it after leaving. This means the trashcan
1071 code will trigger a little early, but that's no big deal.
1073 Q. Are there any live examples of code in need of all this
1076 A. Yes. See SF bug 668433 for code that crashed (when Python was
1077 compiled in debug mode) before the trashcan level manipulations
1078 were added. For more discussion, see SF patches 581742, 575073
1083 static PyTypeObject
*solid_base(PyTypeObject
*type
);
1085 /* type test with subclassing support */
1088 PyType_IsSubtype(PyTypeObject
*a
, PyTypeObject
*b
)
1092 if (!(a
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
))
1093 return b
== a
|| b
== &PyBaseObject_Type
;
1097 /* Deal with multiple inheritance without recursion
1098 by walking the MRO tuple */
1100 assert(PyTuple_Check(mro
));
1101 n
= PyTuple_GET_SIZE(mro
);
1102 for (i
= 0; i
< n
; i
++) {
1103 if (PyTuple_GET_ITEM(mro
, i
) == (PyObject
*)b
)
1109 /* a is not completely initilized yet; follow tp_base */
1114 } while (a
!= NULL
);
1115 return b
== &PyBaseObject_Type
;
1119 /* Internal routines to do a method lookup in the type
1120 without looking in the instance dictionary
1121 (so we can't use PyObject_GetAttr) but still binding
1122 it to the instance. The arguments are the object,
1123 the method name as a C string, and the address of a
1124 static variable used to cache the interned Python string.
1128 - lookup_maybe() returns NULL without raising an exception
1129 when the _PyType_Lookup() call fails;
1131 - lookup_method() always raises an exception upon errors.
1135 lookup_maybe(PyObject
*self
, char *attrstr
, PyObject
**attrobj
)
1139 if (*attrobj
== NULL
) {
1140 *attrobj
= PyString_InternFromString(attrstr
);
1141 if (*attrobj
== NULL
)
1144 res
= _PyType_Lookup(Py_TYPE(self
), *attrobj
);
1147 if ((f
= Py_TYPE(res
)->tp_descr_get
) == NULL
)
1150 res
= f(res
, self
, (PyObject
*)(Py_TYPE(self
)));
1156 lookup_method(PyObject
*self
, char *attrstr
, PyObject
**attrobj
)
1158 PyObject
*res
= lookup_maybe(self
, attrstr
, attrobj
);
1159 if (res
== NULL
&& !PyErr_Occurred())
1160 PyErr_SetObject(PyExc_AttributeError
, *attrobj
);
1164 /* A variation of PyObject_CallMethod that uses lookup_method()
1165 instead of PyObject_GetAttrString(). This uses the same convention
1166 as lookup_method to cache the interned name string object. */
1169 call_method(PyObject
*o
, char *name
, PyObject
**nameobj
, char *format
, ...)
1172 PyObject
*args
, *func
= 0, *retval
;
1173 va_start(va
, format
);
1175 func
= lookup_maybe(o
, name
, nameobj
);
1178 if (!PyErr_Occurred())
1179 PyErr_SetObject(PyExc_AttributeError
, *nameobj
);
1183 if (format
&& *format
)
1184 args
= Py_VaBuildValue(format
, va
);
1186 args
= PyTuple_New(0);
1193 assert(PyTuple_Check(args
));
1194 retval
= PyObject_Call(func
, args
, NULL
);
1202 /* Clone of call_method() that returns NotImplemented when the lookup fails. */
1205 call_maybe(PyObject
*o
, char *name
, PyObject
**nameobj
, char *format
, ...)
1208 PyObject
*args
, *func
= 0, *retval
;
1209 va_start(va
, format
);
1211 func
= lookup_maybe(o
, name
, nameobj
);
1214 if (!PyErr_Occurred()) {
1215 Py_INCREF(Py_NotImplemented
);
1216 return Py_NotImplemented
;
1221 if (format
&& *format
)
1222 args
= Py_VaBuildValue(format
, va
);
1224 args
= PyTuple_New(0);
1231 assert(PyTuple_Check(args
));
1232 retval
= PyObject_Call(func
, args
, NULL
);
1241 fill_classic_mro(PyObject
*mro
, PyObject
*cls
)
1243 PyObject
*bases
, *base
;
1246 assert(PyList_Check(mro
));
1247 assert(PyClass_Check(cls
));
1248 i
= PySequence_Contains(mro
, cls
);
1252 if (PyList_Append(mro
, cls
) < 0)
1255 bases
= ((PyClassObject
*)cls
)->cl_bases
;
1256 assert(bases
&& PyTuple_Check(bases
));
1257 n
= PyTuple_GET_SIZE(bases
);
1258 for (i
= 0; i
< n
; i
++) {
1259 base
= PyTuple_GET_ITEM(bases
, i
);
1260 if (fill_classic_mro(mro
, base
) < 0)
1267 classic_mro(PyObject
*cls
)
1271 assert(PyClass_Check(cls
));
1272 mro
= PyList_New(0);
1274 if (fill_classic_mro(mro
, cls
) == 0)
1282 Method resolution order algorithm C3 described in
1283 "A Monotonic Superclass Linearization for Dylan",
1284 by Kim Barrett, Bob Cassel, Paul Haahr,
1285 David A. Moon, Keith Playford, and P. Tucker Withington.
1288 Some notes about the rules implied by C3:
1291 It isn't legal to repeat a class in a list of base classes.
1293 The next three properties are the 3 constraints in "C3".
1295 Local precendece order.
1296 If A precedes B in C's MRO, then A will precede B in the MRO of all
1300 The MRO of a class must be an extension without reordering of the
1301 MRO of each of its superclasses.
1303 Extended Precedence Graph (EPG).
1304 Linearization is consistent if there is a path in the EPG from
1305 each class to all its successors in the linearization. See
1306 the paper for definition of EPG.
1310 tail_contains(PyObject
*list
, int whence
, PyObject
*o
) {
1312 size
= PyList_GET_SIZE(list
);
1314 for (j
= whence
+1; j
< size
; j
++) {
1315 if (PyList_GET_ITEM(list
, j
) == o
)
1322 class_name(PyObject
*cls
)
1324 PyObject
*name
= PyObject_GetAttrString(cls
, "__name__");
1328 name
= PyObject_Repr(cls
);
1332 if (!PyString_Check(name
)) {
1340 check_duplicates(PyObject
*list
)
1343 /* Let's use a quadratic time algorithm,
1344 assuming that the bases lists is short.
1346 n
= PyList_GET_SIZE(list
);
1347 for (i
= 0; i
< n
; i
++) {
1348 PyObject
*o
= PyList_GET_ITEM(list
, i
);
1349 for (j
= i
+ 1; j
< n
; j
++) {
1350 if (PyList_GET_ITEM(list
, j
) == o
) {
1352 PyErr_Format(PyExc_TypeError
,
1353 "duplicate base class %s",
1354 o
? PyString_AS_STRING(o
) : "?");
1363 /* Raise a TypeError for an MRO order disagreement.
1365 It's hard to produce a good error message. In the absence of better
1366 insight into error reporting, report the classes that were candidates
1367 to be put next into the MRO. There is some conflict between the
1368 order in which they should be put in the MRO, but it's hard to
1369 diagnose what constraint can't be satisfied.
1373 set_mro_error(PyObject
*to_merge
, int *remain
)
1375 Py_ssize_t i
, n
, off
, to_merge_size
;
1378 PyObject
*set
= PyDict_New();
1381 to_merge_size
= PyList_GET_SIZE(to_merge
);
1382 for (i
= 0; i
< to_merge_size
; i
++) {
1383 PyObject
*L
= PyList_GET_ITEM(to_merge
, i
);
1384 if (remain
[i
] < PyList_GET_SIZE(L
)) {
1385 PyObject
*c
= PyList_GET_ITEM(L
, remain
[i
]);
1386 if (PyDict_SetItem(set
, c
, Py_None
) < 0) {
1392 n
= PyDict_Size(set
);
1394 off
= PyOS_snprintf(buf
, sizeof(buf
), "Cannot create a \
1395 consistent method resolution\norder (MRO) for bases");
1397 while (PyDict_Next(set
, &i
, &k
, &v
) && (size_t)off
< sizeof(buf
)) {
1398 PyObject
*name
= class_name(k
);
1399 off
+= PyOS_snprintf(buf
+ off
, sizeof(buf
) - off
, " %s",
1400 name
? PyString_AS_STRING(name
) : "?");
1402 if (--n
&& (size_t)(off
+1) < sizeof(buf
)) {
1407 PyErr_SetString(PyExc_TypeError
, buf
);
1412 pmerge(PyObject
*acc
, PyObject
* to_merge
) {
1413 Py_ssize_t i
, j
, to_merge_size
, empty_cnt
;
1417 to_merge_size
= PyList_GET_SIZE(to_merge
);
1419 /* remain stores an index into each sublist of to_merge.
1420 remain[i] is the index of the next base in to_merge[i]
1421 that is not included in acc.
1423 remain
= (int *)PyMem_MALLOC(SIZEOF_INT
*to_merge_size
);
1426 for (i
= 0; i
< to_merge_size
; i
++)
1431 for (i
= 0; i
< to_merge_size
; i
++) {
1432 PyObject
*candidate
;
1434 PyObject
*cur_list
= PyList_GET_ITEM(to_merge
, i
);
1436 if (remain
[i
] >= PyList_GET_SIZE(cur_list
)) {
1441 /* Choose next candidate for MRO.
1443 The input sequences alone can determine the choice.
1444 If not, choose the class which appears in the MRO
1445 of the earliest direct superclass of the new class.
1448 candidate
= PyList_GET_ITEM(cur_list
, remain
[i
]);
1449 for (j
= 0; j
< to_merge_size
; j
++) {
1450 PyObject
*j_lst
= PyList_GET_ITEM(to_merge
, j
);
1451 if (tail_contains(j_lst
, remain
[j
], candidate
)) {
1452 goto skip
; /* continue outer loop */
1455 ok
= PyList_Append(acc
, candidate
);
1460 for (j
= 0; j
< to_merge_size
; j
++) {
1461 PyObject
*j_lst
= PyList_GET_ITEM(to_merge
, j
);
1462 if (remain
[j
] < PyList_GET_SIZE(j_lst
) &&
1463 PyList_GET_ITEM(j_lst
, remain
[j
]) == candidate
) {
1471 if (empty_cnt
== to_merge_size
) {
1475 set_mro_error(to_merge
, remain
);
1481 mro_implementation(PyTypeObject
*type
)
1485 PyObject
*bases
, *result
;
1486 PyObject
*to_merge
, *bases_aslist
;
1488 if (type
->tp_dict
== NULL
) {
1489 if (PyType_Ready(type
) < 0)
1493 /* Find a superclass linearization that honors the constraints
1494 of the explicit lists of bases and the constraints implied by
1497 to_merge is a list of lists, where each list is a superclass
1498 linearization implied by a base class. The last element of
1499 to_merge is the declared list of bases.
1502 bases
= type
->tp_bases
;
1503 n
= PyTuple_GET_SIZE(bases
);
1505 to_merge
= PyList_New(n
+1);
1506 if (to_merge
== NULL
)
1509 for (i
= 0; i
< n
; i
++) {
1510 PyObject
*base
= PyTuple_GET_ITEM(bases
, i
);
1511 PyObject
*parentMRO
;
1512 if (PyType_Check(base
))
1513 parentMRO
= PySequence_List(
1514 ((PyTypeObject
*)base
)->tp_mro
);
1516 parentMRO
= classic_mro(base
);
1517 if (parentMRO
== NULL
) {
1518 Py_DECREF(to_merge
);
1522 PyList_SET_ITEM(to_merge
, i
, parentMRO
);
1525 bases_aslist
= PySequence_List(bases
);
1526 if (bases_aslist
== NULL
) {
1527 Py_DECREF(to_merge
);
1530 /* This is just a basic sanity check. */
1531 if (check_duplicates(bases_aslist
) < 0) {
1532 Py_DECREF(to_merge
);
1533 Py_DECREF(bases_aslist
);
1536 PyList_SET_ITEM(to_merge
, n
, bases_aslist
);
1538 result
= Py_BuildValue("[O]", (PyObject
*)type
);
1539 if (result
== NULL
) {
1540 Py_DECREF(to_merge
);
1544 ok
= pmerge(result
, to_merge
);
1545 Py_DECREF(to_merge
);
1555 mro_external(PyObject
*self
)
1557 PyTypeObject
*type
= (PyTypeObject
*)self
;
1559 return mro_implementation(type
);
1563 mro_internal(PyTypeObject
*type
)
1565 PyObject
*mro
, *result
, *tuple
;
1568 if (Py_TYPE(type
) == &PyType_Type
) {
1569 result
= mro_implementation(type
);
1572 static PyObject
*mro_str
;
1574 mro
= lookup_method((PyObject
*)type
, "mro", &mro_str
);
1577 result
= PyObject_CallObject(mro
, NULL
);
1582 tuple
= PySequence_Tuple(result
);
1589 PyTypeObject
*solid
;
1591 solid
= solid_base(type
);
1593 len
= PyTuple_GET_SIZE(tuple
);
1595 for (i
= 0; i
< len
; i
++) {
1597 cls
= PyTuple_GET_ITEM(tuple
, i
);
1598 if (PyClass_Check(cls
))
1600 else if (!PyType_Check(cls
)) {
1601 PyErr_Format(PyExc_TypeError
,
1602 "mro() returned a non-class ('%.500s')",
1603 Py_TYPE(cls
)->tp_name
);
1607 t
= (PyTypeObject
*)cls
;
1608 if (!PyType_IsSubtype(solid
, solid_base(t
))) {
1609 PyErr_Format(PyExc_TypeError
,
1610 "mro() returned base with unsuitable layout ('%.500s')",
1617 type
->tp_mro
= tuple
;
1619 type_mro_modified(type
, type
->tp_mro
);
1620 /* corner case: the old-style super class might have been hidden
1621 from the custom MRO */
1622 type_mro_modified(type
, type
->tp_bases
);
1624 type_modified(type
);
1630 /* Calculate the best base amongst multiple base classes.
1631 This is the first one that's on the path to the "solid base". */
1633 static PyTypeObject
*
1634 best_base(PyObject
*bases
)
1637 PyTypeObject
*base
, *winner
, *candidate
, *base_i
;
1638 PyObject
*base_proto
;
1640 assert(PyTuple_Check(bases
));
1641 n
= PyTuple_GET_SIZE(bases
);
1645 for (i
= 0; i
< n
; i
++) {
1646 base_proto
= PyTuple_GET_ITEM(bases
, i
);
1647 if (PyClass_Check(base_proto
))
1649 if (!PyType_Check(base_proto
)) {
1652 "bases must be types");
1655 base_i
= (PyTypeObject
*)base_proto
;
1656 if (base_i
->tp_dict
== NULL
) {
1657 if (PyType_Ready(base_i
) < 0)
1660 candidate
= solid_base(base_i
);
1661 if (winner
== NULL
) {
1665 else if (PyType_IsSubtype(winner
, candidate
))
1667 else if (PyType_IsSubtype(candidate
, winner
)) {
1674 "multiple bases have "
1675 "instance lay-out conflict");
1680 PyErr_SetString(PyExc_TypeError
,
1681 "a new-style class can't have only classic bases");
1686 extra_ivars(PyTypeObject
*type
, PyTypeObject
*base
)
1688 size_t t_size
= type
->tp_basicsize
;
1689 size_t b_size
= base
->tp_basicsize
;
1691 assert(t_size
>= b_size
); /* Else type smaller than base! */
1692 if (type
->tp_itemsize
|| base
->tp_itemsize
) {
1693 /* If itemsize is involved, stricter rules */
1694 return t_size
!= b_size
||
1695 type
->tp_itemsize
!= base
->tp_itemsize
;
1697 if (type
->tp_weaklistoffset
&& base
->tp_weaklistoffset
== 0 &&
1698 type
->tp_weaklistoffset
+ sizeof(PyObject
*) == t_size
&&
1699 type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
1700 t_size
-= sizeof(PyObject
*);
1701 if (type
->tp_dictoffset
&& base
->tp_dictoffset
== 0 &&
1702 type
->tp_dictoffset
+ sizeof(PyObject
*) == t_size
&&
1703 type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
1704 t_size
-= sizeof(PyObject
*);
1706 return t_size
!= b_size
;
1709 static PyTypeObject
*
1710 solid_base(PyTypeObject
*type
)
1715 base
= solid_base(type
->tp_base
);
1717 base
= &PyBaseObject_Type
;
1718 if (extra_ivars(type
, base
))
1724 static void object_dealloc(PyObject
*);
1725 static int object_init(PyObject
*, PyObject
*, PyObject
*);
1726 static int update_slot(PyTypeObject
*, PyObject
*);
1727 static void fixup_slot_dispatchers(PyTypeObject
*);
1730 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1731 * inherited from various builtin types. The builtin base usually provides
1732 * its own __dict__ descriptor, so we use that when we can.
1734 static PyTypeObject
*
1735 get_builtin_base_with_dict(PyTypeObject
*type
)
1737 while (type
->tp_base
!= NULL
) {
1738 if (type
->tp_dictoffset
!= 0 &&
1739 !(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
1741 type
= type
->tp_base
;
1747 get_dict_descriptor(PyTypeObject
*type
)
1749 static PyObject
*dict_str
;
1752 if (dict_str
== NULL
) {
1753 dict_str
= PyString_InternFromString("__dict__");
1754 if (dict_str
== NULL
)
1757 descr
= _PyType_Lookup(type
, dict_str
);
1758 if (descr
== NULL
|| !PyDescr_IsData(descr
))
1765 raise_dict_descr_error(PyObject
*obj
)
1767 PyErr_Format(PyExc_TypeError
,
1768 "this __dict__ descriptor does not support "
1769 "'%.200s' objects", obj
->ob_type
->tp_name
);
1773 subtype_dict(PyObject
*obj
, void *context
)
1779 base
= get_builtin_base_with_dict(obj
->ob_type
);
1782 PyObject
*descr
= get_dict_descriptor(base
);
1783 if (descr
== NULL
) {
1784 raise_dict_descr_error(obj
);
1787 func
= descr
->ob_type
->tp_descr_get
;
1789 raise_dict_descr_error(obj
);
1792 return func(descr
, obj
, (PyObject
*)(obj
->ob_type
));
1795 dictptr
= _PyObject_GetDictPtr(obj
);
1796 if (dictptr
== NULL
) {
1797 PyErr_SetString(PyExc_AttributeError
,
1798 "This object has no __dict__");
1803 *dictptr
= dict
= PyDict_New();
1809 subtype_setdict(PyObject
*obj
, PyObject
*value
, void *context
)
1815 base
= get_builtin_base_with_dict(obj
->ob_type
);
1818 PyObject
*descr
= get_dict_descriptor(base
);
1819 if (descr
== NULL
) {
1820 raise_dict_descr_error(obj
);
1823 func
= descr
->ob_type
->tp_descr_set
;
1825 raise_dict_descr_error(obj
);
1828 return func(descr
, obj
, value
);
1831 dictptr
= _PyObject_GetDictPtr(obj
);
1832 if (dictptr
== NULL
) {
1833 PyErr_SetString(PyExc_AttributeError
,
1834 "This object has no __dict__");
1837 if (value
!= NULL
&& !PyDict_Check(value
)) {
1838 PyErr_Format(PyExc_TypeError
,
1839 "__dict__ must be set to a dictionary, "
1840 "not a '%.200s'", Py_TYPE(value
)->tp_name
);
1851 subtype_getweakref(PyObject
*obj
, void *context
)
1853 PyObject
**weaklistptr
;
1856 if (Py_TYPE(obj
)->tp_weaklistoffset
== 0) {
1857 PyErr_SetString(PyExc_AttributeError
,
1858 "This object has no __weakref__");
1861 assert(Py_TYPE(obj
)->tp_weaklistoffset
> 0);
1862 assert(Py_TYPE(obj
)->tp_weaklistoffset
+ sizeof(PyObject
*) <=
1863 (size_t)(Py_TYPE(obj
)->tp_basicsize
));
1864 weaklistptr
= (PyObject
**)
1865 ((char *)obj
+ Py_TYPE(obj
)->tp_weaklistoffset
);
1866 if (*weaklistptr
== NULL
)
1869 result
= *weaklistptr
;
1874 /* Three variants on the subtype_getsets list. */
1876 static PyGetSetDef subtype_getsets_full
[] = {
1877 {"__dict__", subtype_dict
, subtype_setdict
,
1878 PyDoc_STR("dictionary for instance variables (if defined)")},
1879 {"__weakref__", subtype_getweakref
, NULL
,
1880 PyDoc_STR("list of weak references to the object (if defined)")},
1884 static PyGetSetDef subtype_getsets_dict_only
[] = {
1885 {"__dict__", subtype_dict
, subtype_setdict
,
1886 PyDoc_STR("dictionary for instance variables (if defined)")},
1890 static PyGetSetDef subtype_getsets_weakref_only
[] = {
1891 {"__weakref__", subtype_getweakref
, NULL
,
1892 PyDoc_STR("list of weak references to the object (if defined)")},
1897 valid_identifier(PyObject
*s
)
1902 if (!PyString_Check(s
)) {
1903 PyErr_Format(PyExc_TypeError
,
1904 "__slots__ items must be strings, not '%.200s'",
1905 Py_TYPE(s
)->tp_name
);
1908 p
= (unsigned char *) PyString_AS_STRING(s
);
1909 n
= PyString_GET_SIZE(s
);
1910 /* We must reject an empty name. As a hack, we bump the
1911 length to 1 so that the loop will balk on the trailing \0. */
1914 for (i
= 0; i
< n
; i
++, p
++) {
1915 if (!(i
== 0 ? isalpha(*p
) : isalnum(*p
)) && *p
!= '_') {
1916 PyErr_SetString(PyExc_TypeError
,
1917 "__slots__ must be identifiers");
1924 #ifdef Py_USING_UNICODE
1925 /* Replace Unicode objects in slots. */
1928 _unicode_to_string(PyObject
*slots
, Py_ssize_t nslots
)
1930 PyObject
*tmp
= NULL
;
1931 PyObject
*slot_name
, *new_name
;
1934 for (i
= 0; i
< nslots
; i
++) {
1935 if (PyUnicode_Check(slot_name
= PyTuple_GET_ITEM(slots
, i
))) {
1937 tmp
= PySequence_List(slots
);
1941 new_name
= _PyUnicode_AsDefaultEncodedString(slot_name
,
1943 if (new_name
== NULL
) {
1947 Py_INCREF(new_name
);
1948 PyList_SET_ITEM(tmp
, i
, new_name
);
1949 Py_DECREF(slot_name
);
1953 slots
= PyList_AsTuple(tmp
);
1962 object_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
);
1965 type_init(PyObject
*cls
, PyObject
*args
, PyObject
*kwds
)
1969 assert(args
!= NULL
&& PyTuple_Check(args
));
1970 assert(kwds
== NULL
|| PyDict_Check(kwds
));
1972 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
) != 0) {
1973 PyErr_SetString(PyExc_TypeError
,
1974 "type.__init__() takes no keyword arguments");
1978 if (args
!= NULL
&& PyTuple_Check(args
) &&
1979 (PyTuple_GET_SIZE(args
) != 1 && PyTuple_GET_SIZE(args
) != 3)) {
1980 PyErr_SetString(PyExc_TypeError
,
1981 "type.__init__() takes 1 or 3 arguments");
1985 /* Call object.__init__(self) now. */
1986 /* XXX Could call super(type, cls).__init__() but what's the point? */
1987 args
= PyTuple_GetSlice(args
, 0, 0);
1988 res
= object_init(cls
, args
, NULL
);
1994 type_new(PyTypeObject
*metatype
, PyObject
*args
, PyObject
*kwds
)
1996 PyObject
*name
, *bases
, *dict
;
1997 static char *kwlist
[] = {"name", "bases", "dict", 0};
1998 PyObject
*slots
, *tmp
, *newslots
;
1999 PyTypeObject
*type
, *base
, *tmptype
, *winner
;
2000 PyHeapTypeObject
*et
;
2002 Py_ssize_t i
, nbases
, nslots
, slotoffset
, add_dict
, add_weak
;
2003 int j
, may_add_dict
, may_add_weak
;
2005 assert(args
!= NULL
&& PyTuple_Check(args
));
2006 assert(kwds
== NULL
|| PyDict_Check(kwds
));
2008 /* Special case: type(x) should return x->ob_type */
2010 const Py_ssize_t nargs
= PyTuple_GET_SIZE(args
);
2011 const Py_ssize_t nkwds
= kwds
== NULL
? 0 : PyDict_Size(kwds
);
2013 if (PyType_CheckExact(metatype
) && nargs
== 1 && nkwds
== 0) {
2014 PyObject
*x
= PyTuple_GET_ITEM(args
, 0);
2015 Py_INCREF(Py_TYPE(x
));
2016 return (PyObject
*) Py_TYPE(x
);
2019 /* SF bug 475327 -- if that didn't trigger, we need 3
2020 arguments. but PyArg_ParseTupleAndKeywords below may give
2021 a msg saying type() needs exactly 3. */
2022 if (nargs
+ nkwds
!= 3) {
2023 PyErr_SetString(PyExc_TypeError
,
2024 "type() takes 1 or 3 arguments");
2029 /* Check arguments: (name, bases, dict) */
2030 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "SO!O!:type", kwlist
,
2032 &PyTuple_Type
, &bases
,
2033 &PyDict_Type
, &dict
))
2036 /* Determine the proper metatype to deal with this,
2037 and check for metatype conflicts while we're at it.
2038 Note that if some other metatype wins to contract,
2039 it's possible that its instances are not types. */
2040 nbases
= PyTuple_GET_SIZE(bases
);
2042 for (i
= 0; i
< nbases
; i
++) {
2043 tmp
= PyTuple_GET_ITEM(bases
, i
);
2044 tmptype
= tmp
->ob_type
;
2045 if (tmptype
== &PyClass_Type
)
2046 continue; /* Special case classic classes */
2047 if (PyType_IsSubtype(winner
, tmptype
))
2049 if (PyType_IsSubtype(tmptype
, winner
)) {
2053 PyErr_SetString(PyExc_TypeError
,
2054 "metaclass conflict: "
2055 "the metaclass of a derived class "
2056 "must be a (non-strict) subclass "
2057 "of the metaclasses of all its bases");
2060 if (winner
!= metatype
) {
2061 if (winner
->tp_new
!= type_new
) /* Pass it to the winner */
2062 return winner
->tp_new(winner
, args
, kwds
);
2066 /* Adjust for empty tuple bases */
2068 bases
= PyTuple_Pack(1, &PyBaseObject_Type
);
2076 /* XXX From here until type is allocated, "return NULL" leaks bases! */
2078 /* Calculate best base, and check that all bases are type objects */
2079 base
= best_base(bases
);
2084 if (!PyType_HasFeature(base
, Py_TPFLAGS_BASETYPE
)) {
2085 PyErr_Format(PyExc_TypeError
,
2086 "type '%.100s' is not an acceptable base type",
2092 /* Check for a __slots__ sequence variable in dict, and count it */
2093 slots
= PyDict_GetItemString(dict
, "__slots__");
2097 may_add_dict
= base
->tp_dictoffset
== 0;
2098 may_add_weak
= base
->tp_weaklistoffset
== 0 && base
->tp_itemsize
== 0;
2099 if (slots
== NULL
) {
2110 /* Make it into a tuple */
2111 if (PyString_Check(slots
) || PyUnicode_Check(slots
))
2112 slots
= PyTuple_Pack(1, slots
);
2114 slots
= PySequence_Tuple(slots
);
2115 if (slots
== NULL
) {
2119 assert(PyTuple_Check(slots
));
2121 /* Are slots allowed? */
2122 nslots
= PyTuple_GET_SIZE(slots
);
2123 if (nslots
> 0 && base
->tp_itemsize
!= 0) {
2124 PyErr_Format(PyExc_TypeError
,
2125 "nonempty __slots__ "
2126 "not supported for subtype of '%s'",
2134 #ifdef Py_USING_UNICODE
2135 tmp
= _unicode_to_string(slots
, nslots
);
2143 /* Check for valid slot names and two special cases */
2144 for (i
= 0; i
< nslots
; i
++) {
2145 PyObject
*tmp
= PyTuple_GET_ITEM(slots
, i
);
2147 if (!valid_identifier(tmp
))
2149 assert(PyString_Check(tmp
));
2150 s
= PyString_AS_STRING(tmp
);
2151 if (strcmp(s
, "__dict__") == 0) {
2152 if (!may_add_dict
|| add_dict
) {
2153 PyErr_SetString(PyExc_TypeError
,
2154 "__dict__ slot disallowed: "
2155 "we already got one");
2160 if (strcmp(s
, "__weakref__") == 0) {
2161 if (!may_add_weak
|| add_weak
) {
2162 PyErr_SetString(PyExc_TypeError
,
2163 "__weakref__ slot disallowed: "
2164 "either we already got one, "
2165 "or __itemsize__ != 0");
2172 /* Copy slots into a list, mangle names and sort them.
2173 Sorted names are needed for __class__ assignment.
2174 Convert them back to tuple at the end.
2176 newslots
= PyList_New(nslots
- add_dict
- add_weak
);
2177 if (newslots
== NULL
)
2179 for (i
= j
= 0; i
< nslots
; i
++) {
2181 tmp
= PyTuple_GET_ITEM(slots
, i
);
2182 s
= PyString_AS_STRING(tmp
);
2183 if ((add_dict
&& strcmp(s
, "__dict__") == 0) ||
2184 (add_weak
&& strcmp(s
, "__weakref__") == 0))
2186 tmp
=_Py_Mangle(name
, tmp
);
2189 PyList_SET_ITEM(newslots
, j
, tmp
);
2192 assert(j
== nslots
- add_dict
- add_weak
);
2195 if (PyList_Sort(newslots
) == -1) {
2197 Py_DECREF(newslots
);
2200 slots
= PyList_AsTuple(newslots
);
2201 Py_DECREF(newslots
);
2202 if (slots
== NULL
) {
2207 /* Secondary bases may provide weakrefs or dict */
2209 ((may_add_dict
&& !add_dict
) ||
2210 (may_add_weak
&& !add_weak
))) {
2211 for (i
= 0; i
< nbases
; i
++) {
2212 tmp
= PyTuple_GET_ITEM(bases
, i
);
2213 if (tmp
== (PyObject
*)base
)
2214 continue; /* Skip primary base */
2215 if (PyClass_Check(tmp
)) {
2216 /* Classic base class provides both */
2217 if (may_add_dict
&& !add_dict
)
2219 if (may_add_weak
&& !add_weak
)
2223 assert(PyType_Check(tmp
));
2224 tmptype
= (PyTypeObject
*)tmp
;
2225 if (may_add_dict
&& !add_dict
&&
2226 tmptype
->tp_dictoffset
!= 0)
2228 if (may_add_weak
&& !add_weak
&&
2229 tmptype
->tp_weaklistoffset
!= 0)
2231 if (may_add_dict
&& !add_dict
)
2233 if (may_add_weak
&& !add_weak
)
2235 /* Nothing more to check */
2241 /* XXX From here until type is safely allocated,
2242 "return NULL" may leak slots! */
2244 /* Allocate the type object */
2245 type
= (PyTypeObject
*)metatype
->tp_alloc(metatype
, nslots
);
2252 /* Keep name and slots alive in the extended type object */
2253 et
= (PyHeapTypeObject
*)type
;
2256 et
->ht_slots
= slots
;
2258 /* Initialize tp_flags */
2259 type
->tp_flags
= Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HEAPTYPE
|
2260 Py_TPFLAGS_BASETYPE
;
2261 if (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
)
2262 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
2264 /* It's a new-style number unless it specifically inherits any
2265 old-style numeric behavior */
2266 if ((base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) ||
2267 (base
->tp_as_number
== NULL
))
2268 type
->tp_flags
|= Py_TPFLAGS_CHECKTYPES
;
2270 /* Initialize essential fields */
2271 type
->tp_as_number
= &et
->as_number
;
2272 type
->tp_as_sequence
= &et
->as_sequence
;
2273 type
->tp_as_mapping
= &et
->as_mapping
;
2274 type
->tp_as_buffer
= &et
->as_buffer
;
2275 type
->tp_name
= PyString_AS_STRING(name
);
2277 /* Set tp_base and tp_bases */
2278 type
->tp_bases
= bases
;
2280 type
->tp_base
= base
;
2282 /* Initialize tp_dict from passed-in dict */
2283 type
->tp_dict
= dict
= PyDict_Copy(dict
);
2289 /* Set __module__ in the dict */
2290 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
2291 tmp
= PyEval_GetGlobals();
2293 tmp
= PyDict_GetItemString(tmp
, "__name__");
2295 if (PyDict_SetItemString(dict
, "__module__",
2302 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2303 and is a string. The __doc__ accessor will first look for tp_doc;
2304 if that fails, it will still look into __dict__.
2307 PyObject
*doc
= PyDict_GetItemString(dict
, "__doc__");
2308 if (doc
!= NULL
&& PyString_Check(doc
)) {
2309 const size_t n
= (size_t)PyString_GET_SIZE(doc
);
2310 char *tp_doc
= (char *)PyObject_MALLOC(n
+1);
2311 if (tp_doc
== NULL
) {
2315 memcpy(tp_doc
, PyString_AS_STRING(doc
), n
+1);
2316 type
->tp_doc
= tp_doc
;
2320 /* Special-case __new__: if it's a plain function,
2321 make it a static function */
2322 tmp
= PyDict_GetItemString(dict
, "__new__");
2323 if (tmp
!= NULL
&& PyFunction_Check(tmp
)) {
2324 tmp
= PyStaticMethod_New(tmp
);
2329 PyDict_SetItemString(dict
, "__new__", tmp
);
2333 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2334 mp
= PyHeapType_GET_MEMBERS(et
);
2335 slotoffset
= base
->tp_basicsize
;
2336 if (slots
!= NULL
) {
2337 for (i
= 0; i
< nslots
; i
++, mp
++) {
2338 mp
->name
= PyString_AS_STRING(
2339 PyTuple_GET_ITEM(slots
, i
));
2340 mp
->type
= T_OBJECT_EX
;
2341 mp
->offset
= slotoffset
;
2343 /* __dict__ and __weakref__ are already filtered out */
2344 assert(strcmp(mp
->name
, "__dict__") != 0);
2345 assert(strcmp(mp
->name
, "__weakref__") != 0);
2347 slotoffset
+= sizeof(PyObject
*);
2351 if (base
->tp_itemsize
)
2352 type
->tp_dictoffset
= -(long)sizeof(PyObject
*);
2354 type
->tp_dictoffset
= slotoffset
;
2355 slotoffset
+= sizeof(PyObject
*);
2358 assert(!base
->tp_itemsize
);
2359 type
->tp_weaklistoffset
= slotoffset
;
2360 slotoffset
+= sizeof(PyObject
*);
2362 type
->tp_basicsize
= slotoffset
;
2363 type
->tp_itemsize
= base
->tp_itemsize
;
2364 type
->tp_members
= PyHeapType_GET_MEMBERS(et
);
2366 if (type
->tp_weaklistoffset
&& type
->tp_dictoffset
)
2367 type
->tp_getset
= subtype_getsets_full
;
2368 else if (type
->tp_weaklistoffset
&& !type
->tp_dictoffset
)
2369 type
->tp_getset
= subtype_getsets_weakref_only
;
2370 else if (!type
->tp_weaklistoffset
&& type
->tp_dictoffset
)
2371 type
->tp_getset
= subtype_getsets_dict_only
;
2373 type
->tp_getset
= NULL
;
2375 /* Special case some slots */
2376 if (type
->tp_dictoffset
!= 0 || nslots
> 0) {
2377 if (base
->tp_getattr
== NULL
&& base
->tp_getattro
== NULL
)
2378 type
->tp_getattro
= PyObject_GenericGetAttr
;
2379 if (base
->tp_setattr
== NULL
&& base
->tp_setattro
== NULL
)
2380 type
->tp_setattro
= PyObject_GenericSetAttr
;
2382 type
->tp_dealloc
= subtype_dealloc
;
2384 /* Enable GC unless there are really no instance variables possible */
2385 if (!(type
->tp_basicsize
== sizeof(PyObject
) &&
2386 type
->tp_itemsize
== 0))
2387 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
2389 /* Always override allocation strategy to use regular heap */
2390 type
->tp_alloc
= PyType_GenericAlloc
;
2391 if (type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) {
2392 type
->tp_free
= PyObject_GC_Del
;
2393 type
->tp_traverse
= subtype_traverse
;
2394 type
->tp_clear
= subtype_clear
;
2397 type
->tp_free
= PyObject_Del
;
2399 /* Initialize the rest */
2400 if (PyType_Ready(type
) < 0) {
2405 /* Put the proper slots in place */
2406 fixup_slot_dispatchers(type
);
2408 return (PyObject
*)type
;
2411 /* Internal API to look for a name through the MRO.
2412 This returns a borrowed reference, and doesn't set an exception! */
2414 _PyType_Lookup(PyTypeObject
*type
, PyObject
*name
)
2417 PyObject
*mro
, *res
, *base
, *dict
;
2420 if (MCACHE_CACHEABLE_NAME(name
) &&
2421 PyType_HasFeature(type
, Py_TPFLAGS_VALID_VERSION_TAG
)) {
2423 h
= MCACHE_HASH_METHOD(type
, name
);
2424 if (method_cache
[h
].version
== type
->tp_version_tag
&&
2425 method_cache
[h
].name
== name
)
2426 return method_cache
[h
].value
;
2429 /* Look in tp_dict of types in MRO */
2432 /* If mro is NULL, the type is either not yet initialized
2433 by PyType_Ready(), or already cleared by type_clear().
2434 Either way the safest thing to do is to return NULL. */
2439 assert(PyTuple_Check(mro
));
2440 n
= PyTuple_GET_SIZE(mro
);
2441 for (i
= 0; i
< n
; i
++) {
2442 base
= PyTuple_GET_ITEM(mro
, i
);
2443 if (PyClass_Check(base
))
2444 dict
= ((PyClassObject
*)base
)->cl_dict
;
2446 assert(PyType_Check(base
));
2447 dict
= ((PyTypeObject
*)base
)->tp_dict
;
2449 assert(dict
&& PyDict_Check(dict
));
2450 res
= PyDict_GetItem(dict
, name
);
2455 if (MCACHE_CACHEABLE_NAME(name
) && assign_version_tag(type
)) {
2456 h
= MCACHE_HASH_METHOD(type
, name
);
2457 method_cache
[h
].version
= type
->tp_version_tag
;
2458 method_cache
[h
].value
= res
; /* borrowed */
2460 Py_DECREF(method_cache
[h
].name
);
2461 method_cache
[h
].name
= name
;
2466 /* This is similar to PyObject_GenericGetAttr(),
2467 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2469 type_getattro(PyTypeObject
*type
, PyObject
*name
)
2471 PyTypeObject
*metatype
= Py_TYPE(type
);
2472 PyObject
*meta_attribute
, *attribute
;
2473 descrgetfunc meta_get
;
2475 /* Initialize this type (we'll assume the metatype is initialized) */
2476 if (type
->tp_dict
== NULL
) {
2477 if (PyType_Ready(type
) < 0)
2481 /* No readable descriptor found yet */
2484 /* Look for the attribute in the metatype */
2485 meta_attribute
= _PyType_Lookup(metatype
, name
);
2487 if (meta_attribute
!= NULL
) {
2488 meta_get
= Py_TYPE(meta_attribute
)->tp_descr_get
;
2490 if (meta_get
!= NULL
&& PyDescr_IsData(meta_attribute
)) {
2491 /* Data descriptors implement tp_descr_set to intercept
2492 * writes. Assume the attribute is not overridden in
2493 * type's tp_dict (and bases): call the descriptor now.
2495 return meta_get(meta_attribute
, (PyObject
*)type
,
2496 (PyObject
*)metatype
);
2498 Py_INCREF(meta_attribute
);
2501 /* No data descriptor found on metatype. Look in tp_dict of this
2502 * type and its bases */
2503 attribute
= _PyType_Lookup(type
, name
);
2504 if (attribute
!= NULL
) {
2505 /* Implement descriptor functionality, if any */
2506 descrgetfunc local_get
= Py_TYPE(attribute
)->tp_descr_get
;
2508 Py_XDECREF(meta_attribute
);
2510 if (local_get
!= NULL
) {
2511 /* NULL 2nd argument indicates the descriptor was
2512 * found on the target object itself (or a base) */
2513 return local_get(attribute
, (PyObject
*)NULL
,
2517 Py_INCREF(attribute
);
2521 /* No attribute found in local __dict__ (or bases): use the
2522 * descriptor from the metatype, if any */
2523 if (meta_get
!= NULL
) {
2525 res
= meta_get(meta_attribute
, (PyObject
*)type
,
2526 (PyObject
*)metatype
);
2527 Py_DECREF(meta_attribute
);
2531 /* If an ordinary attribute was found on the metatype, return it now */
2532 if (meta_attribute
!= NULL
) {
2533 return meta_attribute
;
2537 PyErr_Format(PyExc_AttributeError
,
2538 "type object '%.50s' has no attribute '%.400s'",
2539 type
->tp_name
, PyString_AS_STRING(name
));
2544 type_setattro(PyTypeObject
*type
, PyObject
*name
, PyObject
*value
)
2546 if (!(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
2549 "can't set attributes of built-in/extension type '%s'",
2553 if (PyObject_GenericSetAttr((PyObject
*)type
, name
, value
) < 0)
2555 return update_slot(type
, name
);
2559 type_dealloc(PyTypeObject
*type
)
2561 PyHeapTypeObject
*et
;
2563 /* Assert this is a heap-allocated type object */
2564 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
2565 _PyObject_GC_UNTRACK(type
);
2566 PyObject_ClearWeakRefs((PyObject
*)type
);
2567 et
= (PyHeapTypeObject
*)type
;
2568 Py_XDECREF(type
->tp_base
);
2569 Py_XDECREF(type
->tp_dict
);
2570 Py_XDECREF(type
->tp_bases
);
2571 Py_XDECREF(type
->tp_mro
);
2572 Py_XDECREF(type
->tp_cache
);
2573 Py_XDECREF(type
->tp_subclasses
);
2574 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2575 * of most other objects. It's okay to cast it to char *.
2577 PyObject_Free((char *)type
->tp_doc
);
2578 Py_XDECREF(et
->ht_name
);
2579 Py_XDECREF(et
->ht_slots
);
2580 Py_TYPE(type
)->tp_free((PyObject
*)type
);
2584 type_subclasses(PyTypeObject
*type
, PyObject
*args_ignored
)
2586 PyObject
*list
, *raw
, *ref
;
2589 list
= PyList_New(0);
2592 raw
= type
->tp_subclasses
;
2595 assert(PyList_Check(raw
));
2596 n
= PyList_GET_SIZE(raw
);
2597 for (i
= 0; i
< n
; i
++) {
2598 ref
= PyList_GET_ITEM(raw
, i
);
2599 assert(PyWeakref_CheckRef(ref
));
2600 ref
= PyWeakref_GET_OBJECT(ref
);
2601 if (ref
!= Py_None
) {
2602 if (PyList_Append(list
, ref
) < 0) {
2611 static PyMethodDef type_methods
[] = {
2612 {"mro", (PyCFunction
)mro_external
, METH_NOARGS
,
2613 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2614 {"__subclasses__", (PyCFunction
)type_subclasses
, METH_NOARGS
,
2615 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2619 PyDoc_STRVAR(type_doc
,
2620 "type(object) -> the object's type\n"
2621 "type(name, bases, dict) -> a new type");
2624 type_traverse(PyTypeObject
*type
, visitproc visit
, void *arg
)
2626 /* Because of type_is_gc(), the collector only calls this
2628 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
2630 Py_VISIT(type
->tp_dict
);
2631 Py_VISIT(type
->tp_cache
);
2632 Py_VISIT(type
->tp_mro
);
2633 Py_VISIT(type
->tp_bases
);
2634 Py_VISIT(type
->tp_base
);
2636 /* There's no need to visit type->tp_subclasses or
2637 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2638 in cycles; tp_subclasses is a list of weak references,
2639 and slots is a tuple of strings. */
2645 type_clear(PyTypeObject
*type
)
2647 /* Because of type_is_gc(), the collector only calls this
2649 assert(type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
);
2651 /* The only field we need to clear is tp_mro, which is part of a
2652 hard cycle (its first element is the class itself) that won't
2653 be broken otherwise (it's a tuple and tuples don't have a
2654 tp_clear handler). None of the other fields need to be
2655 cleared, and here's why:
2658 It is a dict, so the collector will call its tp_clear.
2661 Not used; if it were, it would be a dict.
2664 If these are involved in a cycle, there must be at least
2665 one other, mutable object in the cycle, e.g. a base
2666 class's dict; the cycle will be broken that way.
2669 A list of weak references can't be part of a cycle; and
2670 lists have their own tp_clear.
2672 slots (in PyHeapTypeObject):
2673 A tuple of strings can't be part of a cycle.
2676 Py_CLEAR(type
->tp_mro
);
2682 type_is_gc(PyTypeObject
*type
)
2684 return type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
;
2687 PyTypeObject PyType_Type
= {
2688 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
2689 "type", /* tp_name */
2690 sizeof(PyHeapTypeObject
), /* tp_basicsize */
2691 sizeof(PyMemberDef
), /* tp_itemsize */
2692 (destructor
)type_dealloc
, /* tp_dealloc */
2696 type_compare
, /* tp_compare */
2697 (reprfunc
)type_repr
, /* tp_repr */
2698 0, /* tp_as_number */
2699 0, /* tp_as_sequence */
2700 0, /* tp_as_mapping */
2701 (hashfunc
)_Py_HashPointer
, /* tp_hash */
2702 (ternaryfunc
)type_call
, /* tp_call */
2704 (getattrofunc
)type_getattro
, /* tp_getattro */
2705 (setattrofunc
)type_setattro
, /* tp_setattro */
2706 0, /* tp_as_buffer */
2707 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
2708 Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_TYPE_SUBCLASS
, /* tp_flags */
2709 type_doc
, /* tp_doc */
2710 (traverseproc
)type_traverse
, /* tp_traverse */
2711 (inquiry
)type_clear
, /* tp_clear */
2712 type_richcompare
, /* tp_richcompare */
2713 offsetof(PyTypeObject
, tp_weaklist
), /* tp_weaklistoffset */
2715 0, /* tp_iternext */
2716 type_methods
, /* tp_methods */
2717 type_members
, /* tp_members */
2718 type_getsets
, /* tp_getset */
2721 0, /* tp_descr_get */
2722 0, /* tp_descr_set */
2723 offsetof(PyTypeObject
, tp_dict
), /* tp_dictoffset */
2724 type_init
, /* tp_init */
2726 type_new
, /* tp_new */
2727 PyObject_GC_Del
, /* tp_free */
2728 (inquiry
)type_is_gc
, /* tp_is_gc */
2732 /* The base type of all types (eventually)... except itself. */
2734 /* You may wonder why object.__new__() only complains about arguments
2735 when object.__init__() is not overridden, and vice versa.
2737 Consider the use cases:
2739 1. When neither is overridden, we want to hear complaints about
2740 excess (i.e., any) arguments, since their presence could
2741 indicate there's a bug.
2743 2. When defining an Immutable type, we are likely to override only
2744 __new__(), since __init__() is called too late to initialize an
2745 Immutable object. Since __new__() defines the signature for the
2746 type, it would be a pain to have to override __init__() just to
2747 stop it from complaining about excess arguments.
2749 3. When defining a Mutable type, we are likely to override only
2750 __init__(). So here the converse reasoning applies: we don't
2751 want to have to override __new__() just to stop it from
2754 4. When __init__() is overridden, and the subclass __init__() calls
2755 object.__init__(), the latter should complain about excess
2756 arguments; ditto for __new__().
2758 Use cases 2 and 3 make it unattractive to unconditionally check for
2759 excess arguments. The best solution that addresses all four use
2760 cases is as follows: __init__() complains about excess arguments
2761 unless __new__() is overridden and __init__() is not overridden
2762 (IOW, if __init__() is overridden or __new__() is not overridden);
2763 symmetrically, __new__() complains about excess arguments unless
2764 __init__() is overridden and __new__() is not overridden
2765 (IOW, if __new__() is overridden or __init__() is not overridden).
2767 However, for backwards compatibility, this breaks too much code.
2768 Therefore, in 2.6, we'll *warn* about excess arguments when both
2769 methods are overridden; for all other cases we'll use the above
2776 object_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
2779 excess_args(PyObject
*args
, PyObject
*kwds
)
2781 return PyTuple_GET_SIZE(args
) ||
2782 (kwds
&& PyDict_Check(kwds
) && PyDict_Size(kwds
));
2786 object_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2789 if (excess_args(args
, kwds
)) {
2790 PyTypeObject
*type
= Py_TYPE(self
);
2791 if (type
->tp_init
!= object_init
&&
2792 type
->tp_new
!= object_new
)
2794 err
= PyErr_WarnEx(PyExc_DeprecationWarning
,
2795 "object.__init__() takes no parameters",
2798 else if (type
->tp_init
!= object_init
||
2799 type
->tp_new
== object_new
)
2801 PyErr_SetString(PyExc_TypeError
,
2802 "object.__init__() takes no parameters");
2810 object_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2813 if (excess_args(args
, kwds
)) {
2814 if (type
->tp_new
!= object_new
&&
2815 type
->tp_init
!= object_init
)
2817 err
= PyErr_WarnEx(PyExc_DeprecationWarning
,
2818 "object.__new__() takes no parameters",
2821 else if (type
->tp_new
!= object_new
||
2822 type
->tp_init
== object_init
)
2824 PyErr_SetString(PyExc_TypeError
,
2825 "object.__new__() takes no parameters");
2832 if (type
->tp_flags
& Py_TPFLAGS_IS_ABSTRACT
) {
2833 static PyObject
*comma
= NULL
;
2834 PyObject
*abstract_methods
= NULL
;
2837 PyObject
*sorted_methods
= NULL
;
2838 PyObject
*joined
= NULL
;
2839 const char *joined_str
;
2841 /* Compute ", ".join(sorted(type.__abstractmethods__))
2843 abstract_methods
= type_abstractmethods(type
, NULL
);
2844 if (abstract_methods
== NULL
)
2846 builtins
= PyEval_GetBuiltins();
2847 if (builtins
== NULL
)
2849 sorted
= PyDict_GetItemString(builtins
, "sorted");
2852 sorted_methods
= PyObject_CallFunctionObjArgs(sorted
,
2855 if (sorted_methods
== NULL
)
2857 if (comma
== NULL
) {
2858 comma
= PyString_InternFromString(", ");
2862 joined
= PyObject_CallMethod(comma
, "join",
2863 "O", sorted_methods
);
2866 joined_str
= PyString_AsString(joined
);
2867 if (joined_str
== NULL
)
2870 PyErr_Format(PyExc_TypeError
,
2871 "Can't instantiate abstract class %s "
2872 "with abstract methods %s",
2877 Py_XDECREF(sorted_methods
);
2878 Py_XDECREF(abstract_methods
);
2881 return type
->tp_alloc(type
, 0);
2885 object_dealloc(PyObject
*self
)
2887 Py_TYPE(self
)->tp_free(self
);
2891 object_repr(PyObject
*self
)
2894 PyObject
*mod
, *name
, *rtn
;
2896 type
= Py_TYPE(self
);
2897 mod
= type_module(type
, NULL
);
2900 else if (!PyString_Check(mod
)) {
2904 name
= type_name(type
, NULL
);
2907 if (mod
!= NULL
&& strcmp(PyString_AS_STRING(mod
), "__builtin__"))
2908 rtn
= PyString_FromFormat("<%s.%s object at %p>",
2909 PyString_AS_STRING(mod
),
2910 PyString_AS_STRING(name
),
2913 rtn
= PyString_FromFormat("<%s object at %p>",
2914 type
->tp_name
, self
);
2921 object_str(PyObject
*self
)
2925 f
= Py_TYPE(self
)->tp_repr
;
2932 object_get_class(PyObject
*self
, void *closure
)
2934 Py_INCREF(Py_TYPE(self
));
2935 return (PyObject
*)(Py_TYPE(self
));
2939 equiv_structs(PyTypeObject
*a
, PyTypeObject
*b
)
2944 a
->tp_basicsize
== b
->tp_basicsize
&&
2945 a
->tp_itemsize
== b
->tp_itemsize
&&
2946 a
->tp_dictoffset
== b
->tp_dictoffset
&&
2947 a
->tp_weaklistoffset
== b
->tp_weaklistoffset
&&
2948 ((a
->tp_flags
& Py_TPFLAGS_HAVE_GC
) ==
2949 (b
->tp_flags
& Py_TPFLAGS_HAVE_GC
)));
2953 same_slots_added(PyTypeObject
*a
, PyTypeObject
*b
)
2955 PyTypeObject
*base
= a
->tp_base
;
2957 PyObject
*slots_a
, *slots_b
;
2959 if (base
!= b
->tp_base
)
2961 if (equiv_structs(a
, base
) && equiv_structs(b
, base
))
2963 size
= base
->tp_basicsize
;
2964 if (a
->tp_dictoffset
== size
&& b
->tp_dictoffset
== size
)
2965 size
+= sizeof(PyObject
*);
2966 if (a
->tp_weaklistoffset
== size
&& b
->tp_weaklistoffset
== size
)
2967 size
+= sizeof(PyObject
*);
2969 /* Check slots compliance */
2970 slots_a
= ((PyHeapTypeObject
*)a
)->ht_slots
;
2971 slots_b
= ((PyHeapTypeObject
*)b
)->ht_slots
;
2972 if (slots_a
&& slots_b
) {
2973 if (PyObject_Compare(slots_a
, slots_b
) != 0)
2975 size
+= sizeof(PyObject
*) * PyTuple_GET_SIZE(slots_a
);
2977 return size
== a
->tp_basicsize
&& size
== b
->tp_basicsize
;
2981 compatible_for_assignment(PyTypeObject
* oldto
, PyTypeObject
* newto
, char* attr
)
2983 PyTypeObject
*newbase
, *oldbase
;
2985 if (newto
->tp_dealloc
!= oldto
->tp_dealloc
||
2986 newto
->tp_free
!= oldto
->tp_free
)
2988 PyErr_Format(PyExc_TypeError
,
2990 "'%s' deallocator differs from '%s'",
2998 while (equiv_structs(newbase
, newbase
->tp_base
))
2999 newbase
= newbase
->tp_base
;
3000 while (equiv_structs(oldbase
, oldbase
->tp_base
))
3001 oldbase
= oldbase
->tp_base
;
3002 if (newbase
!= oldbase
&&
3003 (newbase
->tp_base
!= oldbase
->tp_base
||
3004 !same_slots_added(newbase
, oldbase
))) {
3005 PyErr_Format(PyExc_TypeError
,
3007 "'%s' object layout differs from '%s'",
3018 object_set_class(PyObject
*self
, PyObject
*value
, void *closure
)
3020 PyTypeObject
*oldto
= Py_TYPE(self
);
3021 PyTypeObject
*newto
;
3023 if (value
== NULL
) {
3024 PyErr_SetString(PyExc_TypeError
,
3025 "can't delete __class__ attribute");
3028 if (!PyType_Check(value
)) {
3029 PyErr_Format(PyExc_TypeError
,
3030 "__class__ must be set to new-style class, not '%s' object",
3031 Py_TYPE(value
)->tp_name
);
3034 newto
= (PyTypeObject
*)value
;
3035 if (!(newto
->tp_flags
& Py_TPFLAGS_HEAPTYPE
) ||
3036 !(oldto
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
3038 PyErr_Format(PyExc_TypeError
,
3039 "__class__ assignment: only for heap types");
3042 if (compatible_for_assignment(newto
, oldto
, "__class__")) {
3044 Py_TYPE(self
) = newto
;
3053 static PyGetSetDef object_getsets
[] = {
3054 {"__class__", object_get_class
, object_set_class
,
3055 PyDoc_STR("the object's class")},
3060 /* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
3061 We fall back to helpers in copyreg for:
3062 - pickle protocols < 2
3063 - calculating the list of slot names (done only once per class)
3064 - the __newobj__ function (which is used as a token but never called)
3068 import_copyreg(void)
3070 static PyObject
*copyreg_str
;
3073 copyreg_str
= PyString_InternFromString("copyreg");
3074 if (copyreg_str
== NULL
)
3078 return PyImport_Import(copyreg_str
);
3082 slotnames(PyObject
*cls
)
3086 PyObject
*slotnames
;
3088 if (!PyType_Check(cls
)) {
3093 clsdict
= ((PyTypeObject
*)cls
)->tp_dict
;
3094 slotnames
= PyDict_GetItemString(clsdict
, "__slotnames__");
3095 if (slotnames
!= NULL
&& PyList_Check(slotnames
)) {
3096 Py_INCREF(slotnames
);
3100 copyreg
= import_copyreg();
3101 if (copyreg
== NULL
)
3104 slotnames
= PyObject_CallMethod(copyreg
, "_slotnames", "O", cls
);
3106 if (slotnames
!= NULL
&&
3107 slotnames
!= Py_None
&&
3108 !PyList_Check(slotnames
))
3110 PyErr_SetString(PyExc_TypeError
,
3111 "copy_reg._slotnames didn't return a list or None");
3112 Py_DECREF(slotnames
);
3120 reduce_2(PyObject
*obj
)
3122 PyObject
*cls
, *getnewargs
;
3123 PyObject
*args
= NULL
, *args2
= NULL
;
3124 PyObject
*getstate
= NULL
, *state
= NULL
, *names
= NULL
;
3125 PyObject
*slots
= NULL
, *listitems
= NULL
, *dictitems
= NULL
;
3126 PyObject
*copyreg
= NULL
, *newobj
= NULL
, *res
= NULL
;
3129 cls
= PyObject_GetAttrString(obj
, "__class__");
3133 getnewargs
= PyObject_GetAttrString(obj
, "__getnewargs__");
3134 if (getnewargs
!= NULL
) {
3135 args
= PyObject_CallObject(getnewargs
, NULL
);
3136 Py_DECREF(getnewargs
);
3137 if (args
!= NULL
&& !PyTuple_Check(args
)) {
3138 PyErr_Format(PyExc_TypeError
,
3139 "__getnewargs__ should return a tuple, "
3140 "not '%.200s'", Py_TYPE(args
)->tp_name
);
3146 args
= PyTuple_New(0);
3151 getstate
= PyObject_GetAttrString(obj
, "__getstate__");
3152 if (getstate
!= NULL
) {
3153 state
= PyObject_CallObject(getstate
, NULL
);
3154 Py_DECREF(getstate
);
3160 state
= PyObject_GetAttrString(obj
, "__dict__");
3161 if (state
== NULL
) {
3166 names
= slotnames(cls
);
3169 if (names
!= Py_None
) {
3170 assert(PyList_Check(names
));
3171 slots
= PyDict_New();
3175 /* Can't pre-compute the list size; the list
3176 is stored on the class so accessible to other
3177 threads, which may be run by DECREF */
3178 for (i
= 0; i
< PyList_GET_SIZE(names
); i
++) {
3179 PyObject
*name
, *value
;
3180 name
= PyList_GET_ITEM(names
, i
);
3181 value
= PyObject_GetAttr(obj
, name
);
3185 int err
= PyDict_SetItem(slots
, name
,
3194 state
= Py_BuildValue("(NO)", state
, slots
);
3201 if (!PyList_Check(obj
)) {
3202 listitems
= Py_None
;
3203 Py_INCREF(listitems
);
3206 listitems
= PyObject_GetIter(obj
);
3207 if (listitems
== NULL
)
3211 if (!PyDict_Check(obj
)) {
3212 dictitems
= Py_None
;
3213 Py_INCREF(dictitems
);
3216 dictitems
= PyObject_CallMethod(obj
, "iteritems", "");
3217 if (dictitems
== NULL
)
3221 copyreg
= import_copyreg();
3222 if (copyreg
== NULL
)
3224 newobj
= PyObject_GetAttrString(copyreg
, "__newobj__");
3228 n
= PyTuple_GET_SIZE(args
);
3229 args2
= PyTuple_New(n
+1);
3232 PyTuple_SET_ITEM(args2
, 0, cls
);
3234 for (i
= 0; i
< n
; i
++) {
3235 PyObject
*v
= PyTuple_GET_ITEM(args
, i
);
3237 PyTuple_SET_ITEM(args2
, i
+1, v
);
3240 res
= PyTuple_Pack(5, newobj
, args2
, state
, listitems
, dictitems
);
3249 Py_XDECREF(listitems
);
3250 Py_XDECREF(dictitems
);
3251 Py_XDECREF(copyreg
);
3257 * There were two problems when object.__reduce__ and object.__reduce_ex__
3258 * were implemented in the same function:
3259 * - trying to pickle an object with a custom __reduce__ method that
3260 * fell back to object.__reduce__ in certain circumstances led to
3261 * infinite recursion at Python level and eventual RuntimeError.
3262 * - Pickling objects that lied about their type by overwriting the
3263 * __class__ descriptor could lead to infinite recursion at C level
3264 * and eventual segfault.
3266 * Because of backwards compatibility, the two methods still have to
3267 * behave in the same way, even if this is not required by the pickle
3268 * protocol. This common functionality was moved to the _common_reduce
3272 _common_reduce(PyObject
*self
, int proto
)
3274 PyObject
*copyreg
, *res
;
3277 return reduce_2(self
);
3279 copyreg
= import_copyreg();
3283 res
= PyEval_CallMethod(copyreg
, "_reduce_ex", "(Oi)", self
, proto
);
3290 object_reduce(PyObject
*self
, PyObject
*args
)
3294 if (!PyArg_ParseTuple(args
, "|i:__reduce__", &proto
))
3297 return _common_reduce(self
, proto
);
3301 object_reduce_ex(PyObject
*self
, PyObject
*args
)
3303 PyObject
*reduce
, *res
;
3306 if (!PyArg_ParseTuple(args
, "|i:__reduce_ex__", &proto
))
3309 reduce
= PyObject_GetAttrString(self
, "__reduce__");
3313 PyObject
*cls
, *clsreduce
, *objreduce
;
3315 cls
= PyObject_GetAttrString(self
, "__class__");
3320 clsreduce
= PyObject_GetAttrString(cls
, "__reduce__");
3322 if (clsreduce
== NULL
) {
3326 objreduce
= PyDict_GetItemString(PyBaseObject_Type
.tp_dict
,
3328 override
= (clsreduce
!= objreduce
);
3329 Py_DECREF(clsreduce
);
3331 res
= PyObject_CallObject(reduce
, NULL
);
3339 return _common_reduce(self
, proto
);
3343 object_subclasshook(PyObject
*cls
, PyObject
*args
)
3345 Py_INCREF(Py_NotImplemented
);
3346 return Py_NotImplemented
;
3349 PyDoc_STRVAR(object_subclasshook_doc
,
3350 "Abstract classes can override this to customize issubclass().\n"
3352 "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3353 "It should return True, False or NotImplemented. If it returns\n"
3354 "NotImplemented, the normal algorithm is used. Otherwise, it\n"
3355 "overrides the normal algorithm (and the outcome is cached).\n");
3358 from PEP 3101, this code implements:
3361 def __format__(self, format_spec):
3362 if isinstance(format_spec, str):
3363 return format(str(self), format_spec)
3364 elif isinstance(format_spec, unicode):
3365 return format(unicode(self), format_spec)
3368 object_format(PyObject
*self
, PyObject
*args
)
3370 PyObject
*format_spec
;
3371 PyObject
*self_as_str
= NULL
;
3372 PyObject
*result
= NULL
;
3373 PyObject
*format_meth
= NULL
;
3375 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
3377 if (PyUnicode_Check(format_spec
)) {
3378 self_as_str
= PyObject_Unicode(self
);
3379 } else if (PyString_Check(format_spec
)) {
3380 self_as_str
= PyObject_Str(self
);
3382 PyErr_SetString(PyExc_TypeError
, "argument to __format__ must be unicode or str");
3386 if (self_as_str
!= NULL
) {
3387 /* find the format function */
3388 format_meth
= PyObject_GetAttrString(self_as_str
, "__format__");
3389 if (format_meth
!= NULL
) {
3391 result
= PyObject_CallFunctionObjArgs(format_meth
, format_spec
, NULL
);
3395 Py_XDECREF(self_as_str
);
3396 Py_XDECREF(format_meth
);
3401 static PyMethodDef object_methods
[] = {
3402 {"__reduce_ex__", object_reduce_ex
, METH_VARARGS
,
3403 PyDoc_STR("helper for pickle")},
3404 {"__reduce__", object_reduce
, METH_VARARGS
,
3405 PyDoc_STR("helper for pickle")},
3406 {"__subclasshook__", object_subclasshook
, METH_CLASS
| METH_VARARGS
,
3407 object_subclasshook_doc
},
3408 {"__format__", object_format
, METH_VARARGS
,
3409 PyDoc_STR("default object formatter")},
3414 PyTypeObject PyBaseObject_Type
= {
3415 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
3416 "object", /* tp_name */
3417 sizeof(PyObject
), /* tp_basicsize */
3418 0, /* tp_itemsize */
3419 object_dealloc
, /* tp_dealloc */
3424 object_repr
, /* tp_repr */
3425 0, /* tp_as_number */
3426 0, /* tp_as_sequence */
3427 0, /* tp_as_mapping */
3428 (hashfunc
)_Py_HashPointer
, /* tp_hash */
3430 object_str
, /* tp_str */
3431 PyObject_GenericGetAttr
, /* tp_getattro */
3432 PyObject_GenericSetAttr
, /* tp_setattro */
3433 0, /* tp_as_buffer */
3434 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
3435 PyDoc_STR("The most base type"), /* tp_doc */
3436 0, /* tp_traverse */
3438 0, /* tp_richcompare */
3439 0, /* tp_weaklistoffset */
3441 0, /* tp_iternext */
3442 object_methods
, /* tp_methods */
3444 object_getsets
, /* tp_getset */
3447 0, /* tp_descr_get */
3448 0, /* tp_descr_set */
3449 0, /* tp_dictoffset */
3450 object_init
, /* tp_init */
3451 PyType_GenericAlloc
, /* tp_alloc */
3452 object_new
, /* tp_new */
3453 PyObject_Del
, /* tp_free */
3457 /* Initialize the __dict__ in a type object */
3460 add_methods(PyTypeObject
*type
, PyMethodDef
*meth
)
3462 PyObject
*dict
= type
->tp_dict
;
3464 for (; meth
->ml_name
!= NULL
; meth
++) {
3466 if (PyDict_GetItemString(dict
, meth
->ml_name
) &&
3467 !(meth
->ml_flags
& METH_COEXIST
))
3469 if (meth
->ml_flags
& METH_CLASS
) {
3470 if (meth
->ml_flags
& METH_STATIC
) {
3471 PyErr_SetString(PyExc_ValueError
,
3472 "method cannot be both class and static");
3475 descr
= PyDescr_NewClassMethod(type
, meth
);
3477 else if (meth
->ml_flags
& METH_STATIC
) {
3478 PyObject
*cfunc
= PyCFunction_New(meth
, NULL
);
3481 descr
= PyStaticMethod_New(cfunc
);
3485 descr
= PyDescr_NewMethod(type
, meth
);
3489 if (PyDict_SetItemString(dict
, meth
->ml_name
, descr
) < 0)
3497 add_members(PyTypeObject
*type
, PyMemberDef
*memb
)
3499 PyObject
*dict
= type
->tp_dict
;
3501 for (; memb
->name
!= NULL
; memb
++) {
3503 if (PyDict_GetItemString(dict
, memb
->name
))
3505 descr
= PyDescr_NewMember(type
, memb
);
3508 if (PyDict_SetItemString(dict
, memb
->name
, descr
) < 0)
3516 add_getset(PyTypeObject
*type
, PyGetSetDef
*gsp
)
3518 PyObject
*dict
= type
->tp_dict
;
3520 for (; gsp
->name
!= NULL
; gsp
++) {
3522 if (PyDict_GetItemString(dict
, gsp
->name
))
3524 descr
= PyDescr_NewGetSet(type
, gsp
);
3528 if (PyDict_SetItemString(dict
, gsp
->name
, descr
) < 0)
3536 inherit_special(PyTypeObject
*type
, PyTypeObject
*base
)
3538 Py_ssize_t oldsize
, newsize
;
3540 /* Special flag magic */
3541 if (!type
->tp_as_buffer
&& base
->tp_as_buffer
) {
3542 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_GETCHARBUFFER
;
3544 base
->tp_flags
& Py_TPFLAGS_HAVE_GETCHARBUFFER
;
3546 if (!type
->tp_as_sequence
&& base
->tp_as_sequence
) {
3547 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_SEQUENCE_IN
;
3548 type
->tp_flags
|= base
->tp_flags
& Py_TPFLAGS_HAVE_SEQUENCE_IN
;
3550 if ((type
->tp_flags
& Py_TPFLAGS_HAVE_INPLACEOPS
) !=
3551 (base
->tp_flags
& Py_TPFLAGS_HAVE_INPLACEOPS
)) {
3552 if ((!type
->tp_as_number
&& base
->tp_as_number
) ||
3553 (!type
->tp_as_sequence
&& base
->tp_as_sequence
)) {
3554 type
->tp_flags
&= ~Py_TPFLAGS_HAVE_INPLACEOPS
;
3555 if (!type
->tp_as_number
&& !type
->tp_as_sequence
) {
3556 type
->tp_flags
|= base
->tp_flags
&
3557 Py_TPFLAGS_HAVE_INPLACEOPS
;
3562 if (!type
->tp_as_number
&& base
->tp_as_number
) {
3563 type
->tp_flags
&= ~Py_TPFLAGS_CHECKTYPES
;
3564 type
->tp_flags
|= base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
;
3567 /* Copying basicsize is connected to the GC flags */
3568 oldsize
= base
->tp_basicsize
;
3569 newsize
= type
->tp_basicsize
? type
->tp_basicsize
: oldsize
;
3570 if (!(type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
3571 (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
3572 (type
->tp_flags
& Py_TPFLAGS_HAVE_RICHCOMPARE
/*GC slots exist*/) &&
3573 (!type
->tp_traverse
&& !type
->tp_clear
)) {
3574 type
->tp_flags
|= Py_TPFLAGS_HAVE_GC
;
3575 if (type
->tp_traverse
== NULL
)
3576 type
->tp_traverse
= base
->tp_traverse
;
3577 if (type
->tp_clear
== NULL
)
3578 type
->tp_clear
= base
->tp_clear
;
3580 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
3581 /* The condition below could use some explanation.
3582 It appears that tp_new is not inherited for static types
3583 whose base class is 'object'; this seems to be a precaution
3584 so that old extension types don't suddenly become
3585 callable (object.__new__ wouldn't insure the invariants
3586 that the extension type's own factory function ensures).
3587 Heap types, of course, are under our control, so they do
3588 inherit tp_new; static extension types that specify some
3589 other built-in type as the default are considered
3590 new-style-aware so they also inherit object.__new__. */
3591 if (base
!= &PyBaseObject_Type
||
3592 (type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)) {
3593 if (type
->tp_new
== NULL
)
3594 type
->tp_new
= base
->tp_new
;
3597 type
->tp_basicsize
= newsize
;
3599 /* Copy other non-function slots */
3602 #define COPYVAL(SLOT) \
3603 if (type->SLOT == 0) type->SLOT = base->SLOT
3605 COPYVAL(tp_itemsize
);
3606 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_WEAKREFS
) {
3607 COPYVAL(tp_weaklistoffset
);
3609 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
3610 COPYVAL(tp_dictoffset
);
3613 /* Setup fast subclass flags */
3614 if (PyType_IsSubtype(base
, (PyTypeObject
*)PyExc_BaseException
))
3615 type
->tp_flags
|= Py_TPFLAGS_BASE_EXC_SUBCLASS
;
3616 else if (PyType_IsSubtype(base
, &PyType_Type
))
3617 type
->tp_flags
|= Py_TPFLAGS_TYPE_SUBCLASS
;
3618 else if (PyType_IsSubtype(base
, &PyInt_Type
))
3619 type
->tp_flags
|= Py_TPFLAGS_INT_SUBCLASS
;
3620 else if (PyType_IsSubtype(base
, &PyLong_Type
))
3621 type
->tp_flags
|= Py_TPFLAGS_LONG_SUBCLASS
;
3622 else if (PyType_IsSubtype(base
, &PyString_Type
))
3623 type
->tp_flags
|= Py_TPFLAGS_STRING_SUBCLASS
;
3624 #ifdef Py_USING_UNICODE
3625 else if (PyType_IsSubtype(base
, &PyUnicode_Type
))
3626 type
->tp_flags
|= Py_TPFLAGS_UNICODE_SUBCLASS
;
3628 else if (PyType_IsSubtype(base
, &PyTuple_Type
))
3629 type
->tp_flags
|= Py_TPFLAGS_TUPLE_SUBCLASS
;
3630 else if (PyType_IsSubtype(base
, &PyList_Type
))
3631 type
->tp_flags
|= Py_TPFLAGS_LIST_SUBCLASS
;
3632 else if (PyType_IsSubtype(base
, &PyDict_Type
))
3633 type
->tp_flags
|= Py_TPFLAGS_DICT_SUBCLASS
;
3636 static char *hash_name_op
[] = {
3644 overrides_hash(PyTypeObject
*type
)
3647 PyObject
*dict
= type
->tp_dict
;
3649 assert(dict
!= NULL
);
3650 for (p
= hash_name_op
; *p
; p
++) {
3651 if (PyDict_GetItemString(dict
, *p
) != NULL
)
3658 inherit_slots(PyTypeObject
*type
, PyTypeObject
*base
)
3660 PyTypeObject
*basebase
;
3669 #define SLOTDEFINED(SLOT) \
3670 (base->SLOT != 0 && \
3671 (basebase == NULL || base->SLOT != basebase->SLOT))
3673 #define COPYSLOT(SLOT) \
3674 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
3676 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3677 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3678 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
3679 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
3681 /* This won't inherit indirect slots (from tp_as_number etc.)
3682 if type doesn't provide the space. */
3684 if (type
->tp_as_number
!= NULL
&& base
->tp_as_number
!= NULL
) {
3685 basebase
= base
->tp_base
;
3686 if (basebase
->tp_as_number
== NULL
)
3689 COPYNUM(nb_subtract
);
3690 COPYNUM(nb_multiply
);
3692 COPYNUM(nb_remainder
);
3695 COPYNUM(nb_negative
);
3696 COPYNUM(nb_positive
);
3697 COPYNUM(nb_absolute
);
3698 COPYNUM(nb_nonzero
);
3711 COPYNUM(nb_inplace_add
);
3712 COPYNUM(nb_inplace_subtract
);
3713 COPYNUM(nb_inplace_multiply
);
3714 COPYNUM(nb_inplace_divide
);
3715 COPYNUM(nb_inplace_remainder
);
3716 COPYNUM(nb_inplace_power
);
3717 COPYNUM(nb_inplace_lshift
);
3718 COPYNUM(nb_inplace_rshift
);
3719 COPYNUM(nb_inplace_and
);
3720 COPYNUM(nb_inplace_xor
);
3721 COPYNUM(nb_inplace_or
);
3722 if (base
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) {
3723 COPYNUM(nb_true_divide
);
3724 COPYNUM(nb_floor_divide
);
3725 COPYNUM(nb_inplace_true_divide
);
3726 COPYNUM(nb_inplace_floor_divide
);
3728 if (base
->tp_flags
& Py_TPFLAGS_HAVE_INDEX
) {
3733 if (type
->tp_as_sequence
!= NULL
&& base
->tp_as_sequence
!= NULL
) {
3734 basebase
= base
->tp_base
;
3735 if (basebase
->tp_as_sequence
== NULL
)
3742 COPYSEQ(sq_ass_item
);
3743 COPYSEQ(sq_ass_slice
);
3744 COPYSEQ(sq_contains
);
3745 COPYSEQ(sq_inplace_concat
);
3746 COPYSEQ(sq_inplace_repeat
);
3749 if (type
->tp_as_mapping
!= NULL
&& base
->tp_as_mapping
!= NULL
) {
3750 basebase
= base
->tp_base
;
3751 if (basebase
->tp_as_mapping
== NULL
)
3754 COPYMAP(mp_subscript
);
3755 COPYMAP(mp_ass_subscript
);
3758 if (type
->tp_as_buffer
!= NULL
&& base
->tp_as_buffer
!= NULL
) {
3759 basebase
= base
->tp_base
;
3760 if (basebase
->tp_as_buffer
== NULL
)
3762 COPYBUF(bf_getreadbuffer
);
3763 COPYBUF(bf_getwritebuffer
);
3764 COPYBUF(bf_getsegcount
);
3765 COPYBUF(bf_getcharbuffer
);
3766 COPYBUF(bf_getbuffer
);
3767 COPYBUF(bf_releasebuffer
);
3770 basebase
= base
->tp_base
;
3772 COPYSLOT(tp_dealloc
);
3774 if (type
->tp_getattr
== NULL
&& type
->tp_getattro
== NULL
) {
3775 type
->tp_getattr
= base
->tp_getattr
;
3776 type
->tp_getattro
= base
->tp_getattro
;
3778 if (type
->tp_setattr
== NULL
&& type
->tp_setattro
== NULL
) {
3779 type
->tp_setattr
= base
->tp_setattr
;
3780 type
->tp_setattro
= base
->tp_setattro
;
3782 /* tp_compare see tp_richcompare */
3784 /* tp_hash see tp_richcompare */
3787 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_RICHCOMPARE
) {
3788 if (type
->tp_compare
== NULL
&&
3789 type
->tp_richcompare
== NULL
&&
3790 type
->tp_hash
== NULL
&&
3791 !overrides_hash(type
))
3793 type
->tp_compare
= base
->tp_compare
;
3794 type
->tp_richcompare
= base
->tp_richcompare
;
3795 type
->tp_hash
= base
->tp_hash
;
3799 COPYSLOT(tp_compare
);
3801 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_ITER
) {
3803 COPYSLOT(tp_iternext
);
3805 if (type
->tp_flags
& base
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
) {
3806 COPYSLOT(tp_descr_get
);
3807 COPYSLOT(tp_descr_set
);
3808 COPYSLOT(tp_dictoffset
);
3812 if ((type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) ==
3813 (base
->tp_flags
& Py_TPFLAGS_HAVE_GC
)) {
3814 /* They agree about gc. */
3817 else if ((type
->tp_flags
& Py_TPFLAGS_HAVE_GC
) &&
3818 type
->tp_free
== NULL
&&
3819 base
->tp_free
== _PyObject_Del
) {
3820 /* A bit of magic to plug in the correct default
3821 * tp_free function when a derived class adds gc,
3822 * didn't define tp_free, and the base uses the
3823 * default non-gc tp_free.
3825 type
->tp_free
= PyObject_GC_Del
;
3827 /* else they didn't agree about gc, and there isn't something
3828 * obvious to be done -- the type is on its own.
3833 static int add_operators(PyTypeObject
*);
3836 PyType_Ready(PyTypeObject
*type
)
3838 PyObject
*dict
, *bases
;
3842 if (type
->tp_flags
& Py_TPFLAGS_READY
) {
3843 assert(type
->tp_dict
!= NULL
);
3846 assert((type
->tp_flags
& Py_TPFLAGS_READYING
) == 0);
3848 type
->tp_flags
|= Py_TPFLAGS_READYING
;
3850 #ifdef Py_TRACE_REFS
3851 /* PyType_Ready is the closest thing we have to a choke point
3852 * for type objects, so is the best place I can think of to try
3853 * to get type objects into the doubly-linked list of all objects.
3854 * Still, not all type objects go thru PyType_Ready.
3856 _Py_AddToAllObjects((PyObject
*)type
, 0);
3859 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3860 base
= type
->tp_base
;
3861 if (base
== NULL
&& type
!= &PyBaseObject_Type
) {
3862 base
= type
->tp_base
= &PyBaseObject_Type
;
3866 /* Now the only way base can still be NULL is if type is
3867 * &PyBaseObject_Type.
3870 /* Initialize the base class */
3871 if (base
&& base
->tp_dict
== NULL
) {
3872 if (PyType_Ready(base
) < 0)
3876 /* Initialize ob_type if NULL. This means extensions that want to be
3877 compilable separately on Windows can call PyType_Ready() instead of
3878 initializing the ob_type field of their type objects. */
3879 /* The test for base != NULL is really unnecessary, since base is only
3880 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3881 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3883 if (Py_TYPE(type
) == NULL
&& base
!= NULL
)
3884 Py_TYPE(type
) = Py_TYPE(base
);
3886 /* Initialize tp_bases */
3887 bases
= type
->tp_bases
;
3888 if (bases
== NULL
) {
3890 bases
= PyTuple_New(0);
3892 bases
= PyTuple_Pack(1, base
);
3895 type
->tp_bases
= bases
;
3898 /* Initialize tp_dict */
3899 dict
= type
->tp_dict
;
3901 dict
= PyDict_New();
3904 type
->tp_dict
= dict
;
3907 /* Add type-specific descriptors to tp_dict */
3908 if (add_operators(type
) < 0)
3910 if (type
->tp_methods
!= NULL
) {
3911 if (add_methods(type
, type
->tp_methods
) < 0)
3914 if (type
->tp_members
!= NULL
) {
3915 if (add_members(type
, type
->tp_members
) < 0)
3918 if (type
->tp_getset
!= NULL
) {
3919 if (add_getset(type
, type
->tp_getset
) < 0)
3923 /* Calculate method resolution order */
3924 if (mro_internal(type
) < 0) {
3928 /* Inherit special flags from dominant base */
3929 if (type
->tp_base
!= NULL
)
3930 inherit_special(type
, type
->tp_base
);
3932 /* Initialize tp_dict properly */
3933 bases
= type
->tp_mro
;
3934 assert(bases
!= NULL
);
3935 assert(PyTuple_Check(bases
));
3936 n
= PyTuple_GET_SIZE(bases
);
3937 for (i
= 1; i
< n
; i
++) {
3938 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
3939 if (PyType_Check(b
))
3940 inherit_slots(type
, (PyTypeObject
*)b
);
3943 /* Sanity check for tp_free. */
3944 if (PyType_IS_GC(type
) && (type
->tp_flags
& Py_TPFLAGS_BASETYPE
) &&
3945 (type
->tp_free
== NULL
|| type
->tp_free
== PyObject_Del
)) {
3946 /* This base class needs to call tp_free, but doesn't have
3947 * one, or its tp_free is for non-gc'ed objects.
3949 PyErr_Format(PyExc_TypeError
, "type '%.100s' participates in "
3950 "gc and is a base type but has inappropriate "
3956 /* if the type dictionary doesn't contain a __doc__, set it from
3959 if (PyDict_GetItemString(type
->tp_dict
, "__doc__") == NULL
) {
3960 if (type
->tp_doc
!= NULL
) {
3961 PyObject
*doc
= PyString_FromString(type
->tp_doc
);
3964 PyDict_SetItemString(type
->tp_dict
, "__doc__", doc
);
3967 PyDict_SetItemString(type
->tp_dict
,
3968 "__doc__", Py_None
);
3972 /* Hack for tp_hash and __hash__.
3973 If after all that, tp_hash is still NULL, and __hash__ is not in
3974 tp_dict, set tp_dict['__hash__'] equal to None.
3975 This signals that __hash__ is not inherited.
3977 if (type
->tp_hash
== NULL
&&
3978 PyDict_GetItemString(type
->tp_dict
, "__hash__") == NULL
&&
3979 PyDict_SetItemString(type
->tp_dict
, "__hash__", Py_None
) < 0)
3984 /* Some more special stuff */
3985 base
= type
->tp_base
;
3987 if (type
->tp_as_number
== NULL
)
3988 type
->tp_as_number
= base
->tp_as_number
;
3989 if (type
->tp_as_sequence
== NULL
)
3990 type
->tp_as_sequence
= base
->tp_as_sequence
;
3991 if (type
->tp_as_mapping
== NULL
)
3992 type
->tp_as_mapping
= base
->tp_as_mapping
;
3993 if (type
->tp_as_buffer
== NULL
)
3994 type
->tp_as_buffer
= base
->tp_as_buffer
;
3997 /* Link into each base class's list of subclasses */
3998 bases
= type
->tp_bases
;
3999 n
= PyTuple_GET_SIZE(bases
);
4000 for (i
= 0; i
< n
; i
++) {
4001 PyObject
*b
= PyTuple_GET_ITEM(bases
, i
);
4002 if (PyType_Check(b
) &&
4003 add_subclass((PyTypeObject
*)b
, type
) < 0)
4007 /* All done -- set the ready flag */
4008 assert(type
->tp_dict
!= NULL
);
4010 (type
->tp_flags
& ~Py_TPFLAGS_READYING
) | Py_TPFLAGS_READY
;
4014 type
->tp_flags
&= ~Py_TPFLAGS_READYING
;
4019 add_subclass(PyTypeObject
*base
, PyTypeObject
*type
)
4023 PyObject
*list
, *ref
, *newobj
;
4025 list
= base
->tp_subclasses
;
4027 base
->tp_subclasses
= list
= PyList_New(0);
4031 assert(PyList_Check(list
));
4032 newobj
= PyWeakref_NewRef((PyObject
*)type
, NULL
);
4033 i
= PyList_GET_SIZE(list
);
4035 ref
= PyList_GET_ITEM(list
, i
);
4036 assert(PyWeakref_CheckRef(ref
));
4037 if (PyWeakref_GET_OBJECT(ref
) == Py_None
)
4038 return PyList_SetItem(list
, i
, newobj
);
4040 result
= PyList_Append(list
, newobj
);
4046 remove_subclass(PyTypeObject
*base
, PyTypeObject
*type
)
4049 PyObject
*list
, *ref
;
4051 list
= base
->tp_subclasses
;
4055 assert(PyList_Check(list
));
4056 i
= PyList_GET_SIZE(list
);
4058 ref
= PyList_GET_ITEM(list
, i
);
4059 assert(PyWeakref_CheckRef(ref
));
4060 if (PyWeakref_GET_OBJECT(ref
) == (PyObject
*)type
) {
4061 /* this can't fail, right? */
4062 PySequence_DelItem(list
, i
);
4069 check_num_args(PyObject
*ob
, int n
)
4071 if (!PyTuple_CheckExact(ob
)) {
4072 PyErr_SetString(PyExc_SystemError
,
4073 "PyArg_UnpackTuple() argument list is not a tuple");
4076 if (n
== PyTuple_GET_SIZE(ob
))
4080 "expected %d arguments, got %zd", n
, PyTuple_GET_SIZE(ob
));
4084 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
4086 /* There's a wrapper *function* for each distinct function typedef used
4087 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
4088 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4089 Most tables have only one entry; the tables for binary operators have two
4090 entries, one regular and one with reversed arguments. */
4093 wrap_lenfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4095 lenfunc func
= (lenfunc
)wrapped
;
4098 if (!check_num_args(args
, 0))
4100 res
= (*func
)(self
);
4101 if (res
== -1 && PyErr_Occurred())
4103 return PyInt_FromLong((long)res
);
4107 wrap_inquirypred(PyObject
*self
, PyObject
*args
, void *wrapped
)
4109 inquiry func
= (inquiry
)wrapped
;
4112 if (!check_num_args(args
, 0))
4114 res
= (*func
)(self
);
4115 if (res
== -1 && PyErr_Occurred())
4117 return PyBool_FromLong((long)res
);
4121 wrap_binaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4123 binaryfunc func
= (binaryfunc
)wrapped
;
4126 if (!check_num_args(args
, 1))
4128 other
= PyTuple_GET_ITEM(args
, 0);
4129 return (*func
)(self
, other
);
4133 wrap_binaryfunc_l(PyObject
*self
, PyObject
*args
, void *wrapped
)
4135 binaryfunc func
= (binaryfunc
)wrapped
;
4138 if (!check_num_args(args
, 1))
4140 other
= PyTuple_GET_ITEM(args
, 0);
4141 if (!(self
->ob_type
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) &&
4142 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
4143 Py_INCREF(Py_NotImplemented
);
4144 return Py_NotImplemented
;
4146 return (*func
)(self
, other
);
4150 wrap_binaryfunc_r(PyObject
*self
, PyObject
*args
, void *wrapped
)
4152 binaryfunc func
= (binaryfunc
)wrapped
;
4155 if (!check_num_args(args
, 1))
4157 other
= PyTuple_GET_ITEM(args
, 0);
4158 if (!(self
->ob_type
->tp_flags
& Py_TPFLAGS_CHECKTYPES
) &&
4159 !PyType_IsSubtype(other
->ob_type
, self
->ob_type
)) {
4160 Py_INCREF(Py_NotImplemented
);
4161 return Py_NotImplemented
;
4163 return (*func
)(other
, self
);
4167 wrap_coercefunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4169 coercion func
= (coercion
)wrapped
;
4170 PyObject
*other
, *res
;
4173 if (!check_num_args(args
, 1))
4175 other
= PyTuple_GET_ITEM(args
, 0);
4176 ok
= func(&self
, &other
);
4180 Py_INCREF(Py_NotImplemented
);
4181 return Py_NotImplemented
;
4183 res
= PyTuple_New(2);
4189 PyTuple_SET_ITEM(res
, 0, self
);
4190 PyTuple_SET_ITEM(res
, 1, other
);
4195 wrap_ternaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4197 ternaryfunc func
= (ternaryfunc
)wrapped
;
4199 PyObject
*third
= Py_None
;
4201 /* Note: This wrapper only works for __pow__() */
4203 if (!PyArg_UnpackTuple(args
, "", 1, 2, &other
, &third
))
4205 return (*func
)(self
, other
, third
);
4209 wrap_ternaryfunc_r(PyObject
*self
, PyObject
*args
, void *wrapped
)
4211 ternaryfunc func
= (ternaryfunc
)wrapped
;
4213 PyObject
*third
= Py_None
;
4215 /* Note: This wrapper only works for __pow__() */
4217 if (!PyArg_UnpackTuple(args
, "", 1, 2, &other
, &third
))
4219 return (*func
)(other
, self
, third
);
4223 wrap_unaryfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4225 unaryfunc func
= (unaryfunc
)wrapped
;
4227 if (!check_num_args(args
, 0))
4229 return (*func
)(self
);
4233 wrap_indexargfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4235 ssizeargfunc func
= (ssizeargfunc
)wrapped
;
4239 if (!PyArg_UnpackTuple(args
, "", 1, 1, &o
))
4241 i
= PyNumber_AsSsize_t(o
, PyExc_OverflowError
);
4242 if (i
== -1 && PyErr_Occurred())
4244 return (*func
)(self
, i
);
4248 getindex(PyObject
*self
, PyObject
*arg
)
4252 i
= PyNumber_AsSsize_t(arg
, PyExc_OverflowError
);
4253 if (i
== -1 && PyErr_Occurred())
4256 PySequenceMethods
*sq
= Py_TYPE(self
)->tp_as_sequence
;
4257 if (sq
&& sq
->sq_length
) {
4258 Py_ssize_t n
= (*sq
->sq_length
)(self
);
4268 wrap_sq_item(PyObject
*self
, PyObject
*args
, void *wrapped
)
4270 ssizeargfunc func
= (ssizeargfunc
)wrapped
;
4274 if (PyTuple_GET_SIZE(args
) == 1) {
4275 arg
= PyTuple_GET_ITEM(args
, 0);
4276 i
= getindex(self
, arg
);
4277 if (i
== -1 && PyErr_Occurred())
4279 return (*func
)(self
, i
);
4281 check_num_args(args
, 1);
4282 assert(PyErr_Occurred());
4287 wrap_ssizessizeargfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4289 ssizessizeargfunc func
= (ssizessizeargfunc
)wrapped
;
4292 if (!PyArg_ParseTuple(args
, "nn", &i
, &j
))
4294 return (*func
)(self
, i
, j
);
4298 wrap_sq_setitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
4300 ssizeobjargproc func
= (ssizeobjargproc
)wrapped
;
4303 PyObject
*arg
, *value
;
4305 if (!PyArg_UnpackTuple(args
, "", 2, 2, &arg
, &value
))
4307 i
= getindex(self
, arg
);
4308 if (i
== -1 && PyErr_Occurred())
4310 res
= (*func
)(self
, i
, value
);
4311 if (res
== -1 && PyErr_Occurred())
4318 wrap_sq_delitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
4320 ssizeobjargproc func
= (ssizeobjargproc
)wrapped
;
4325 if (!check_num_args(args
, 1))
4327 arg
= PyTuple_GET_ITEM(args
, 0);
4328 i
= getindex(self
, arg
);
4329 if (i
== -1 && PyErr_Occurred())
4331 res
= (*func
)(self
, i
, NULL
);
4332 if (res
== -1 && PyErr_Occurred())
4339 wrap_ssizessizeobjargproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4341 ssizessizeobjargproc func
= (ssizessizeobjargproc
)wrapped
;
4346 if (!PyArg_ParseTuple(args
, "nnO", &i
, &j
, &value
))
4348 res
= (*func
)(self
, i
, j
, value
);
4349 if (res
== -1 && PyErr_Occurred())
4356 wrap_delslice(PyObject
*self
, PyObject
*args
, void *wrapped
)
4358 ssizessizeobjargproc func
= (ssizessizeobjargproc
)wrapped
;
4362 if (!PyArg_ParseTuple(args
, "nn", &i
, &j
))
4364 res
= (*func
)(self
, i
, j
, NULL
);
4365 if (res
== -1 && PyErr_Occurred())
4371 /* XXX objobjproc is a misnomer; should be objargpred */
4373 wrap_objobjproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4375 objobjproc func
= (objobjproc
)wrapped
;
4379 if (!check_num_args(args
, 1))
4381 value
= PyTuple_GET_ITEM(args
, 0);
4382 res
= (*func
)(self
, value
);
4383 if (res
== -1 && PyErr_Occurred())
4386 return PyBool_FromLong(res
);
4390 wrap_objobjargproc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4392 objobjargproc func
= (objobjargproc
)wrapped
;
4394 PyObject
*key
, *value
;
4396 if (!PyArg_UnpackTuple(args
, "", 2, 2, &key
, &value
))
4398 res
= (*func
)(self
, key
, value
);
4399 if (res
== -1 && PyErr_Occurred())
4406 wrap_delitem(PyObject
*self
, PyObject
*args
, void *wrapped
)
4408 objobjargproc func
= (objobjargproc
)wrapped
;
4412 if (!check_num_args(args
, 1))
4414 key
= PyTuple_GET_ITEM(args
, 0);
4415 res
= (*func
)(self
, key
, NULL
);
4416 if (res
== -1 && PyErr_Occurred())
4423 wrap_cmpfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4425 cmpfunc func
= (cmpfunc
)wrapped
;
4429 if (!check_num_args(args
, 1))
4431 other
= PyTuple_GET_ITEM(args
, 0);
4432 if (Py_TYPE(other
)->tp_compare
!= func
&&
4433 !PyType_IsSubtype(Py_TYPE(other
), Py_TYPE(self
))) {
4436 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
4437 Py_TYPE(self
)->tp_name
,
4438 Py_TYPE(self
)->tp_name
,
4439 Py_TYPE(other
)->tp_name
);
4442 res
= (*func
)(self
, other
);
4443 if (PyErr_Occurred())
4445 return PyInt_FromLong((long)res
);
4448 /* Helper to check for object.__setattr__ or __delattr__ applied to a type.
4449 This is called the Carlo Verre hack after its discoverer. */
4451 hackcheck(PyObject
*self
, setattrofunc func
, char *what
)
4453 PyTypeObject
*type
= Py_TYPE(self
);
4454 while (type
&& type
->tp_flags
& Py_TPFLAGS_HEAPTYPE
)
4455 type
= type
->tp_base
;
4456 /* If type is NULL now, this is a really weird type.
4457 In the spirit of backwards compatibility (?), just shut up. */
4458 if (type
&& type
->tp_setattro
!= func
) {
4459 PyErr_Format(PyExc_TypeError
,
4460 "can't apply this %s to %s object",
4469 wrap_setattr(PyObject
*self
, PyObject
*args
, void *wrapped
)
4471 setattrofunc func
= (setattrofunc
)wrapped
;
4473 PyObject
*name
, *value
;
4475 if (!PyArg_UnpackTuple(args
, "", 2, 2, &name
, &value
))
4477 if (!hackcheck(self
, func
, "__setattr__"))
4479 res
= (*func
)(self
, name
, value
);
4487 wrap_delattr(PyObject
*self
, PyObject
*args
, void *wrapped
)
4489 setattrofunc func
= (setattrofunc
)wrapped
;
4493 if (!check_num_args(args
, 1))
4495 name
= PyTuple_GET_ITEM(args
, 0);
4496 if (!hackcheck(self
, func
, "__delattr__"))
4498 res
= (*func
)(self
, name
, NULL
);
4506 wrap_hashfunc(PyObject
*self
, PyObject
*args
, void *wrapped
)
4508 hashfunc func
= (hashfunc
)wrapped
;
4511 if (!check_num_args(args
, 0))
4513 res
= (*func
)(self
);
4514 if (res
== -1 && PyErr_Occurred())
4516 return PyInt_FromLong(res
);
4520 wrap_call(PyObject
*self
, PyObject
*args
, void *wrapped
, PyObject
*kwds
)
4522 ternaryfunc func
= (ternaryfunc
)wrapped
;
4524 return (*func
)(self
, args
, kwds
);
4528 wrap_richcmpfunc(PyObject
*self
, PyObject
*args
, void *wrapped
, int op
)
4530 richcmpfunc func
= (richcmpfunc
)wrapped
;
4533 if (!check_num_args(args
, 1))
4535 other
= PyTuple_GET_ITEM(args
, 0);
4536 return (*func
)(self
, other
, op
);
4539 #undef RICHCMP_WRAPPER
4540 #define RICHCMP_WRAPPER(NAME, OP) \
4542 richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4544 return wrap_richcmpfunc(self, args, wrapped, OP); \
4547 RICHCMP_WRAPPER(lt
, Py_LT
)
4548 RICHCMP_WRAPPER(le
, Py_LE
)
4549 RICHCMP_WRAPPER(eq
, Py_EQ
)
4550 RICHCMP_WRAPPER(ne
, Py_NE
)
4551 RICHCMP_WRAPPER(gt
, Py_GT
)
4552 RICHCMP_WRAPPER(ge
, Py_GE
)
4555 wrap_next(PyObject
*self
, PyObject
*args
, void *wrapped
)
4557 unaryfunc func
= (unaryfunc
)wrapped
;
4560 if (!check_num_args(args
, 0))
4562 res
= (*func
)(self
);
4563 if (res
== NULL
&& !PyErr_Occurred())
4564 PyErr_SetNone(PyExc_StopIteration
);
4569 wrap_descr_get(PyObject
*self
, PyObject
*args
, void *wrapped
)
4571 descrgetfunc func
= (descrgetfunc
)wrapped
;
4573 PyObject
*type
= NULL
;
4575 if (!PyArg_UnpackTuple(args
, "", 1, 2, &obj
, &type
))
4579 if (type
== Py_None
)
4581 if (type
== NULL
&&obj
== NULL
) {
4582 PyErr_SetString(PyExc_TypeError
,
4583 "__get__(None, None) is invalid");
4586 return (*func
)(self
, obj
, type
);
4590 wrap_descr_set(PyObject
*self
, PyObject
*args
, void *wrapped
)
4592 descrsetfunc func
= (descrsetfunc
)wrapped
;
4593 PyObject
*obj
, *value
;
4596 if (!PyArg_UnpackTuple(args
, "", 2, 2, &obj
, &value
))
4598 ret
= (*func
)(self
, obj
, value
);
4606 wrap_descr_delete(PyObject
*self
, PyObject
*args
, void *wrapped
)
4608 descrsetfunc func
= (descrsetfunc
)wrapped
;
4612 if (!check_num_args(args
, 1))
4614 obj
= PyTuple_GET_ITEM(args
, 0);
4615 ret
= (*func
)(self
, obj
, NULL
);
4623 wrap_init(PyObject
*self
, PyObject
*args
, void *wrapped
, PyObject
*kwds
)
4625 initproc func
= (initproc
)wrapped
;
4627 if (func(self
, args
, kwds
) < 0)
4634 tp_new_wrapper(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
4636 PyTypeObject
*type
, *subtype
, *staticbase
;
4637 PyObject
*arg0
, *res
;
4639 if (self
== NULL
|| !PyType_Check(self
))
4640 Py_FatalError("__new__() called with non-type 'self'");
4641 type
= (PyTypeObject
*)self
;
4642 if (!PyTuple_Check(args
) || PyTuple_GET_SIZE(args
) < 1) {
4643 PyErr_Format(PyExc_TypeError
,
4644 "%s.__new__(): not enough arguments",
4648 arg0
= PyTuple_GET_ITEM(args
, 0);
4649 if (!PyType_Check(arg0
)) {
4650 PyErr_Format(PyExc_TypeError
,
4651 "%s.__new__(X): X is not a type object (%s)",
4653 Py_TYPE(arg0
)->tp_name
);
4656 subtype
= (PyTypeObject
*)arg0
;
4657 if (!PyType_IsSubtype(subtype
, type
)) {
4658 PyErr_Format(PyExc_TypeError
,
4659 "%s.__new__(%s): %s is not a subtype of %s",
4667 /* Check that the use doesn't do something silly and unsafe like
4668 object.__new__(dict). To do this, we check that the
4669 most derived base that's not a heap type is this type. */
4670 staticbase
= subtype
;
4671 while (staticbase
&& (staticbase
->tp_flags
& Py_TPFLAGS_HEAPTYPE
))
4672 staticbase
= staticbase
->tp_base
;
4673 /* If staticbase is NULL now, it is a really weird type.
4674 In the spirit of backwards compatibility (?), just shut up. */
4675 if (staticbase
&& staticbase
->tp_new
!= type
->tp_new
) {
4676 PyErr_Format(PyExc_TypeError
,
4677 "%s.__new__(%s) is not safe, use %s.__new__()",
4680 staticbase
== NULL
? "?" : staticbase
->tp_name
);
4684 args
= PyTuple_GetSlice(args
, 1, PyTuple_GET_SIZE(args
));
4687 res
= type
->tp_new(subtype
, args
, kwds
);
4692 static struct PyMethodDef tp_new_methoddef
[] = {
4693 {"__new__", (PyCFunction
)tp_new_wrapper
, METH_VARARGS
|METH_KEYWORDS
,
4694 PyDoc_STR("T.__new__(S, ...) -> "
4695 "a new object with type S, a subtype of T")},
4700 add_tp_new_wrapper(PyTypeObject
*type
)
4704 if (PyDict_GetItemString(type
->tp_dict
, "__new__") != NULL
)
4706 func
= PyCFunction_New(tp_new_methoddef
, (PyObject
*)type
);
4709 if (PyDict_SetItemString(type
->tp_dict
, "__new__", func
)) {
4717 /* Slot wrappers that call the corresponding __foo__ slot. See comments
4718 below at override_slots() for more explanation. */
4720 #define SLOT0(FUNCNAME, OPSTR) \
4722 FUNCNAME(PyObject *self) \
4724 static PyObject *cache_str; \
4725 return call_method(self, OPSTR, &cache_str, "()"); \
4728 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
4730 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
4732 static PyObject *cache_str; \
4733 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
4736 /* Boolean helper for SLOT1BINFULL().
4737 right.__class__ is a nontrivial subclass of left.__class__. */
4739 method_is_overloaded(PyObject
*left
, PyObject
*right
, char *name
)
4744 b
= PyObject_GetAttrString((PyObject
*)(Py_TYPE(right
)), name
);
4747 /* If right doesn't have it, it's not overloaded */
4751 a
= PyObject_GetAttrString((PyObject
*)(Py_TYPE(left
)), name
);
4755 /* If right has it but left doesn't, it's overloaded */
4759 ok
= PyObject_RichCompareBool(a
, b
, Py_NE
);
4771 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
4773 FUNCNAME(PyObject *self, PyObject *other) \
4775 static PyObject *cache_str, *rcache_str; \
4776 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4777 Py_TYPE(other)->tp_as_number != NULL && \
4778 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4779 if (Py_TYPE(self)->tp_as_number != NULL && \
4780 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4783 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4784 method_is_overloaded(self, other, ROPSTR)) { \
4786 other, ROPSTR, &rcache_str, "(O)", self); \
4787 if (r != Py_NotImplemented) \
4793 self, OPSTR, &cache_str, "(O)", other); \
4794 if (r != Py_NotImplemented || \
4795 Py_TYPE(other) == Py_TYPE(self)) \
4800 return call_maybe( \
4801 other, ROPSTR, &rcache_str, "(O)", self); \
4803 Py_INCREF(Py_NotImplemented); \
4804 return Py_NotImplemented; \
4807 #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4808 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4810 #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4812 FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4814 static PyObject *cache_str; \
4815 return call_method(self, OPSTR, &cache_str, \
4816 "(" ARGCODES ")", arg1, arg2); \
4820 slot_sq_length(PyObject
*self
)
4822 static PyObject
*len_str
;
4823 PyObject
*res
= call_method(self
, "__len__", &len_str
, "()");
4828 len
= PyInt_AsSsize_t(res
);
4831 if (!PyErr_Occurred())
4832 PyErr_SetString(PyExc_ValueError
,
4833 "__len__() should return >= 0");
4839 /* Super-optimized version of slot_sq_item.
4840 Other slots could do the same... */
4842 slot_sq_item(PyObject
*self
, Py_ssize_t i
)
4844 static PyObject
*getitem_str
;
4845 PyObject
*func
, *args
= NULL
, *ival
= NULL
, *retval
= NULL
;
4848 if (getitem_str
== NULL
) {
4849 getitem_str
= PyString_InternFromString("__getitem__");
4850 if (getitem_str
== NULL
)
4853 func
= _PyType_Lookup(Py_TYPE(self
), getitem_str
);
4855 if ((f
= Py_TYPE(func
)->tp_descr_get
) == NULL
)
4858 func
= f(func
, self
, (PyObject
*)(Py_TYPE(self
)));
4863 ival
= PyInt_FromSsize_t(i
);
4865 args
= PyTuple_New(1);
4867 PyTuple_SET_ITEM(args
, 0, ival
);
4868 retval
= PyObject_Call(func
, args
, NULL
);
4876 PyErr_SetObject(PyExc_AttributeError
, getitem_str
);
4884 SLOT2(slot_sq_slice
, "__getslice__", Py_ssize_t
, Py_ssize_t
, "nn")
4887 slot_sq_ass_item(PyObject
*self
, Py_ssize_t index
, PyObject
*value
)
4890 static PyObject
*delitem_str
, *setitem_str
;
4893 res
= call_method(self
, "__delitem__", &delitem_str
,
4896 res
= call_method(self
, "__setitem__", &setitem_str
,
4897 "(nO)", index
, value
);
4905 slot_sq_ass_slice(PyObject
*self
, Py_ssize_t i
, Py_ssize_t j
, PyObject
*value
)
4908 static PyObject
*delslice_str
, *setslice_str
;
4911 res
= call_method(self
, "__delslice__", &delslice_str
,
4914 res
= call_method(self
, "__setslice__", &setslice_str
,
4915 "(nnO)", i
, j
, value
);
4923 slot_sq_contains(PyObject
*self
, PyObject
*value
)
4925 PyObject
*func
, *res
, *args
;
4928 static PyObject
*contains_str
;
4930 func
= lookup_maybe(self
, "__contains__", &contains_str
);
4932 args
= PyTuple_Pack(1, value
);
4936 res
= PyObject_Call(func
, args
, NULL
);
4941 result
= PyObject_IsTrue(res
);
4945 else if (! PyErr_Occurred()) {
4946 /* Possible results: -1 and 1 */
4947 result
= (int)_PySequence_IterSearch(self
, value
,
4948 PY_ITERSEARCH_CONTAINS
);
4953 #define slot_mp_length slot_sq_length
4955 SLOT1(slot_mp_subscript
, "__getitem__", PyObject
*, "O")
4958 slot_mp_ass_subscript(PyObject
*self
, PyObject
*key
, PyObject
*value
)
4961 static PyObject
*delitem_str
, *setitem_str
;
4964 res
= call_method(self
, "__delitem__", &delitem_str
,
4967 res
= call_method(self
, "__setitem__", &setitem_str
,
4968 "(OO)", key
, value
);
4975 SLOT1BIN(slot_nb_add
, nb_add
, "__add__", "__radd__")
4976 SLOT1BIN(slot_nb_subtract
, nb_subtract
, "__sub__", "__rsub__")
4977 SLOT1BIN(slot_nb_multiply
, nb_multiply
, "__mul__", "__rmul__")
4978 SLOT1BIN(slot_nb_divide
, nb_divide
, "__div__", "__rdiv__")
4979 SLOT1BIN(slot_nb_remainder
, nb_remainder
, "__mod__", "__rmod__")
4980 SLOT1BIN(slot_nb_divmod
, nb_divmod
, "__divmod__", "__rdivmod__")
4982 static PyObject
*slot_nb_power(PyObject
*, PyObject
*, PyObject
*);
4984 SLOT1BINFULL(slot_nb_power_binary
, slot_nb_power
,
4985 nb_power
, "__pow__", "__rpow__")
4988 slot_nb_power(PyObject
*self
, PyObject
*other
, PyObject
*modulus
)
4990 static PyObject
*pow_str
;
4992 if (modulus
== Py_None
)
4993 return slot_nb_power_binary(self
, other
);
4994 /* Three-arg power doesn't use __rpow__. But ternary_op
4995 can call this when the second argument's type uses
4996 slot_nb_power, so check before calling self.__pow__. */
4997 if (Py_TYPE(self
)->tp_as_number
!= NULL
&&
4998 Py_TYPE(self
)->tp_as_number
->nb_power
== slot_nb_power
) {
4999 return call_method(self
, "__pow__", &pow_str
,
5000 "(OO)", other
, modulus
);
5002 Py_INCREF(Py_NotImplemented
);
5003 return Py_NotImplemented
;
5006 SLOT0(slot_nb_negative
, "__neg__")
5007 SLOT0(slot_nb_positive
, "__pos__")
5008 SLOT0(slot_nb_absolute
, "__abs__")
5011 slot_nb_nonzero(PyObject
*self
)
5013 PyObject
*func
, *args
;
5014 static PyObject
*nonzero_str
, *len_str
;
5017 func
= lookup_maybe(self
, "__nonzero__", &nonzero_str
);
5019 if (PyErr_Occurred())
5021 func
= lookup_maybe(self
, "__len__", &len_str
);
5023 return PyErr_Occurred() ? -1 : 1;
5025 args
= PyTuple_New(0);
5027 PyObject
*temp
= PyObject_Call(func
, args
, NULL
);
5030 if (PyInt_CheckExact(temp
) || PyBool_Check(temp
))
5031 result
= PyObject_IsTrue(temp
);
5033 PyErr_Format(PyExc_TypeError
,
5034 "__nonzero__ should return "
5035 "bool or int, returned %s",
5036 temp
->ob_type
->tp_name
);
5048 slot_nb_index(PyObject
*self
)
5050 static PyObject
*index_str
;
5051 return call_method(self
, "__index__", &index_str
, "()");
5055 SLOT0(slot_nb_invert
, "__invert__")
5056 SLOT1BIN(slot_nb_lshift
, nb_lshift
, "__lshift__", "__rlshift__")
5057 SLOT1BIN(slot_nb_rshift
, nb_rshift
, "__rshift__", "__rrshift__")
5058 SLOT1BIN(slot_nb_and
, nb_and
, "__and__", "__rand__")
5059 SLOT1BIN(slot_nb_xor
, nb_xor
, "__xor__", "__rxor__")
5060 SLOT1BIN(slot_nb_or
, nb_or
, "__or__", "__ror__")
5063 slot_nb_coerce(PyObject
**a
, PyObject
**b
)
5065 static PyObject
*coerce_str
;
5066 PyObject
*self
= *a
, *other
= *b
;
5068 if (self
->ob_type
->tp_as_number
!= NULL
&&
5069 self
->ob_type
->tp_as_number
->nb_coerce
== slot_nb_coerce
) {
5072 self
, "__coerce__", &coerce_str
, "(O)", other
);
5075 if (r
== Py_NotImplemented
) {
5079 if (!PyTuple_Check(r
) || PyTuple_GET_SIZE(r
) != 2) {
5080 PyErr_SetString(PyExc_TypeError
,
5081 "__coerce__ didn't return a 2-tuple");
5085 *a
= PyTuple_GET_ITEM(r
, 0);
5087 *b
= PyTuple_GET_ITEM(r
, 1);
5093 if (other
->ob_type
->tp_as_number
!= NULL
&&
5094 other
->ob_type
->tp_as_number
->nb_coerce
== slot_nb_coerce
) {
5097 other
, "__coerce__", &coerce_str
, "(O)", self
);
5100 if (r
== Py_NotImplemented
) {
5104 if (!PyTuple_Check(r
) || PyTuple_GET_SIZE(r
) != 2) {
5105 PyErr_SetString(PyExc_TypeError
,
5106 "__coerce__ didn't return a 2-tuple");
5110 *a
= PyTuple_GET_ITEM(r
, 1);
5112 *b
= PyTuple_GET_ITEM(r
, 0);
5120 SLOT0(slot_nb_int
, "__int__")
5121 SLOT0(slot_nb_long
, "__long__")
5122 SLOT0(slot_nb_float
, "__float__")
5123 SLOT0(slot_nb_oct
, "__oct__")
5124 SLOT0(slot_nb_hex
, "__hex__")
5125 SLOT1(slot_nb_inplace_add
, "__iadd__", PyObject
*, "O")
5126 SLOT1(slot_nb_inplace_subtract
, "__isub__", PyObject
*, "O")
5127 SLOT1(slot_nb_inplace_multiply
, "__imul__", PyObject
*, "O")
5128 SLOT1(slot_nb_inplace_divide
, "__idiv__", PyObject
*, "O")
5129 SLOT1(slot_nb_inplace_remainder
, "__imod__", PyObject
*, "O")
5130 /* Can't use SLOT1 here, because nb_inplace_power is ternary */
5132 slot_nb_inplace_power(PyObject
*self
, PyObject
* arg1
, PyObject
*arg2
)
5134 static PyObject
*cache_str
;
5135 return call_method(self
, "__ipow__", &cache_str
, "(" "O" ")", arg1
);
5137 SLOT1(slot_nb_inplace_lshift
, "__ilshift__", PyObject
*, "O")
5138 SLOT1(slot_nb_inplace_rshift
, "__irshift__", PyObject
*, "O")
5139 SLOT1(slot_nb_inplace_and
, "__iand__", PyObject
*, "O")
5140 SLOT1(slot_nb_inplace_xor
, "__ixor__", PyObject
*, "O")
5141 SLOT1(slot_nb_inplace_or
, "__ior__", PyObject
*, "O")
5142 SLOT1BIN(slot_nb_floor_divide
, nb_floor_divide
,
5143 "__floordiv__", "__rfloordiv__")
5144 SLOT1BIN(slot_nb_true_divide
, nb_true_divide
, "__truediv__", "__rtruediv__")
5145 SLOT1(slot_nb_inplace_floor_divide
, "__ifloordiv__", PyObject
*, "O")
5146 SLOT1(slot_nb_inplace_true_divide
, "__itruediv__", PyObject
*, "O")
5149 half_compare(PyObject
*self
, PyObject
*other
)
5151 PyObject
*func
, *args
, *res
;
5152 static PyObject
*cmp_str
;
5155 func
= lookup_method(self
, "__cmp__", &cmp_str
);
5160 args
= PyTuple_Pack(1, other
);
5164 res
= PyObject_Call(func
, args
, NULL
);
5168 if (res
!= Py_NotImplemented
) {
5171 c
= PyInt_AsLong(res
);
5173 if (c
== -1 && PyErr_Occurred())
5175 return (c
< 0) ? -1 : (c
> 0) ? 1 : 0;
5182 /* This slot is published for the benefit of try_3way_compare in object.c */
5184 _PyObject_SlotCompare(PyObject
*self
, PyObject
*other
)
5188 if (Py_TYPE(self
)->tp_compare
== _PyObject_SlotCompare
) {
5189 c
= half_compare(self
, other
);
5193 if (Py_TYPE(other
)->tp_compare
== _PyObject_SlotCompare
) {
5194 c
= half_compare(other
, self
);
5200 return (void *)self
< (void *)other
? -1 :
5201 (void *)self
> (void *)other
? 1 : 0;
5205 slot_tp_repr(PyObject
*self
)
5207 PyObject
*func
, *res
;
5208 static PyObject
*repr_str
;
5210 func
= lookup_method(self
, "__repr__", &repr_str
);
5212 res
= PyEval_CallObject(func
, NULL
);
5217 return PyString_FromFormat("<%s object at %p>",
5218 Py_TYPE(self
)->tp_name
, self
);
5222 slot_tp_str(PyObject
*self
)
5224 PyObject
*func
, *res
;
5225 static PyObject
*str_str
;
5227 func
= lookup_method(self
, "__str__", &str_str
);
5229 res
= PyEval_CallObject(func
, NULL
);
5235 return slot_tp_repr(self
);
5240 slot_tp_hash(PyObject
*self
)
5243 static PyObject
*hash_str
, *eq_str
, *cmp_str
;
5246 func
= lookup_method(self
, "__hash__", &hash_str
);
5248 if (func
!= NULL
&& func
!= Py_None
) {
5249 PyObject
*res
= PyEval_CallObject(func
, NULL
);
5253 if (PyLong_Check(res
))
5254 h
= PyLong_Type
.tp_hash(res
);
5256 h
= PyInt_AsLong(res
);
5260 Py_XDECREF(func
); /* may be None */
5262 func
= lookup_method(self
, "__eq__", &eq_str
);
5265 func
= lookup_method(self
, "__cmp__", &cmp_str
);
5268 PyErr_Format(PyExc_TypeError
, "unhashable type: '%.200s'",
5269 self
->ob_type
->tp_name
);
5274 h
= _Py_HashPointer((void *)self
);
5276 if (h
== -1 && !PyErr_Occurred())
5282 slot_tp_call(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5284 static PyObject
*call_str
;
5285 PyObject
*meth
= lookup_method(self
, "__call__", &call_str
);
5291 res
= PyObject_Call(meth
, args
, kwds
);
5297 /* There are two slot dispatch functions for tp_getattro.
5299 - slot_tp_getattro() is used when __getattribute__ is overridden
5300 but no __getattr__ hook is present;
5302 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5304 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5305 detects the absence of __getattr__ and then installs the simpler slot if
5309 slot_tp_getattro(PyObject
*self
, PyObject
*name
)
5311 static PyObject
*getattribute_str
= NULL
;
5312 return call_method(self
, "__getattribute__", &getattribute_str
,
5317 slot_tp_getattr_hook(PyObject
*self
, PyObject
*name
)
5319 PyTypeObject
*tp
= Py_TYPE(self
);
5320 PyObject
*getattr
, *getattribute
, *res
;
5321 static PyObject
*getattribute_str
= NULL
;
5322 static PyObject
*getattr_str
= NULL
;
5324 if (getattr_str
== NULL
) {
5325 getattr_str
= PyString_InternFromString("__getattr__");
5326 if (getattr_str
== NULL
)
5329 if (getattribute_str
== NULL
) {
5331 PyString_InternFromString("__getattribute__");
5332 if (getattribute_str
== NULL
)
5335 getattr
= _PyType_Lookup(tp
, getattr_str
);
5336 if (getattr
== NULL
) {
5337 /* No __getattr__ hook: use a simpler dispatcher */
5338 tp
->tp_getattro
= slot_tp_getattro
;
5339 return slot_tp_getattro(self
, name
);
5341 getattribute
= _PyType_Lookup(tp
, getattribute_str
);
5342 if (getattribute
== NULL
||
5343 (Py_TYPE(getattribute
) == &PyWrapperDescr_Type
&&
5344 ((PyWrapperDescrObject
*)getattribute
)->d_wrapped
==
5345 (void *)PyObject_GenericGetAttr
))
5346 res
= PyObject_GenericGetAttr(self
, name
);
5348 res
= PyObject_CallFunctionObjArgs(getattribute
, self
, name
, NULL
);
5349 if (res
== NULL
&& PyErr_ExceptionMatches(PyExc_AttributeError
)) {
5351 res
= PyObject_CallFunctionObjArgs(getattr
, self
, name
, NULL
);
5357 slot_tp_setattro(PyObject
*self
, PyObject
*name
, PyObject
*value
)
5360 static PyObject
*delattr_str
, *setattr_str
;
5363 res
= call_method(self
, "__delattr__", &delattr_str
,
5366 res
= call_method(self
, "__setattr__", &setattr_str
,
5367 "(OO)", name
, value
);
5374 static char *name_op
[] = {
5384 half_richcompare(PyObject
*self
, PyObject
*other
, int op
)
5386 PyObject
*func
, *args
, *res
;
5387 static PyObject
*op_str
[6];
5389 func
= lookup_method(self
, name_op
[op
], &op_str
[op
]);
5392 Py_INCREF(Py_NotImplemented
);
5393 return Py_NotImplemented
;
5395 args
= PyTuple_Pack(1, other
);
5399 res
= PyObject_Call(func
, args
, NULL
);
5407 slot_tp_richcompare(PyObject
*self
, PyObject
*other
, int op
)
5411 if (Py_TYPE(self
)->tp_richcompare
== slot_tp_richcompare
) {
5412 res
= half_richcompare(self
, other
, op
);
5413 if (res
!= Py_NotImplemented
)
5417 if (Py_TYPE(other
)->tp_richcompare
== slot_tp_richcompare
) {
5418 res
= half_richcompare(other
, self
, _Py_SwappedOp
[op
]);
5419 if (res
!= Py_NotImplemented
) {
5424 Py_INCREF(Py_NotImplemented
);
5425 return Py_NotImplemented
;
5429 slot_tp_iter(PyObject
*self
)
5431 PyObject
*func
, *res
;
5432 static PyObject
*iter_str
, *getitem_str
;
5434 func
= lookup_method(self
, "__iter__", &iter_str
);
5437 args
= res
= PyTuple_New(0);
5439 res
= PyObject_Call(func
, args
, NULL
);
5446 func
= lookup_method(self
, "__getitem__", &getitem_str
);
5448 PyErr_Format(PyExc_TypeError
,
5449 "'%.200s' object is not iterable",
5450 Py_TYPE(self
)->tp_name
);
5454 return PySeqIter_New(self
);
5458 slot_tp_iternext(PyObject
*self
)
5460 static PyObject
*next_str
;
5461 return call_method(self
, "next", &next_str
, "()");
5465 slot_tp_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
5467 PyTypeObject
*tp
= Py_TYPE(self
);
5469 static PyObject
*get_str
= NULL
;
5471 if (get_str
== NULL
) {
5472 get_str
= PyString_InternFromString("__get__");
5473 if (get_str
== NULL
)
5476 get
= _PyType_Lookup(tp
, get_str
);
5478 /* Avoid further slowdowns */
5479 if (tp
->tp_descr_get
== slot_tp_descr_get
)
5480 tp
->tp_descr_get
= NULL
;
5488 return PyObject_CallFunctionObjArgs(get
, self
, obj
, type
, NULL
);
5492 slot_tp_descr_set(PyObject
*self
, PyObject
*target
, PyObject
*value
)
5495 static PyObject
*del_str
, *set_str
;
5498 res
= call_method(self
, "__delete__", &del_str
,
5501 res
= call_method(self
, "__set__", &set_str
,
5502 "(OO)", target
, value
);
5510 slot_tp_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5512 static PyObject
*init_str
;
5513 PyObject
*meth
= lookup_method(self
, "__init__", &init_str
);
5518 res
= PyObject_Call(meth
, args
, kwds
);
5522 if (res
!= Py_None
) {
5523 PyErr_Format(PyExc_TypeError
,
5524 "__init__() should return None, not '%.200s'",
5525 Py_TYPE(res
)->tp_name
);
5534 slot_tp_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
5536 static PyObject
*new_str
;
5538 PyObject
*newargs
, *x
;
5541 if (new_str
== NULL
) {
5542 new_str
= PyString_InternFromString("__new__");
5543 if (new_str
== NULL
)
5546 func
= PyObject_GetAttr((PyObject
*)type
, new_str
);
5549 assert(PyTuple_Check(args
));
5550 n
= PyTuple_GET_SIZE(args
);
5551 newargs
= PyTuple_New(n
+1);
5552 if (newargs
== NULL
)
5555 PyTuple_SET_ITEM(newargs
, 0, (PyObject
*)type
);
5556 for (i
= 0; i
< n
; i
++) {
5557 x
= PyTuple_GET_ITEM(args
, i
);
5559 PyTuple_SET_ITEM(newargs
, i
+1, x
);
5561 x
= PyObject_Call(func
, newargs
, kwds
);
5568 slot_tp_del(PyObject
*self
)
5570 static PyObject
*del_str
= NULL
;
5571 PyObject
*del
, *res
;
5572 PyObject
*error_type
, *error_value
, *error_traceback
;
5574 /* Temporarily resurrect the object. */
5575 assert(self
->ob_refcnt
== 0);
5576 self
->ob_refcnt
= 1;
5578 /* Save the current exception, if any. */
5579 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
5581 /* Execute __del__ method, if any. */
5582 del
= lookup_maybe(self
, "__del__", &del_str
);
5584 res
= PyEval_CallObject(del
, NULL
);
5586 PyErr_WriteUnraisable(del
);
5592 /* Restore the saved exception. */
5593 PyErr_Restore(error_type
, error_value
, error_traceback
);
5595 /* Undo the temporary resurrection; can't use DECREF here, it would
5596 * cause a recursive call.
5598 assert(self
->ob_refcnt
> 0);
5599 if (--self
->ob_refcnt
== 0)
5600 return; /* this is the normal path out */
5602 /* __del__ resurrected it! Make it look like the original Py_DECREF
5606 Py_ssize_t refcnt
= self
->ob_refcnt
;
5607 _Py_NewReference(self
);
5608 self
->ob_refcnt
= refcnt
;
5610 assert(!PyType_IS_GC(Py_TYPE(self
)) ||
5611 _Py_AS_GC(self
)->gc
.gc_refs
!= _PyGC_REFS_UNTRACKED
);
5612 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5613 * we need to undo that. */
5615 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5616 * chain, so no more to do there.
5617 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5618 * _Py_NewReference bumped tp_allocs: both of those need to be
5622 --Py_TYPE(self
)->tp_frees
;
5623 --Py_TYPE(self
)->tp_allocs
;
5628 /* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
5629 functions. The offsets here are relative to the 'PyHeapTypeObject'
5630 structure, which incorporates the additional structures used for numbers,
5631 sequences and mappings.
5632 Note that multiple names may map to the same slot (e.g. __eq__,
5633 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
5634 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5635 terminated with an all-zero entry. (This table is further initialized and
5636 sorted in init_slotdefs() below.) */
5638 typedef struct wrapperbase slotdef
;
5651 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5652 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5654 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5655 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5656 PyDoc_STR(DOC), FLAGS}
5657 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5658 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5660 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5661 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5662 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5663 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5664 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5665 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5666 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5667 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5668 "x." NAME "() <==> " DOC)
5669 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5670 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5671 "x." NAME "(y) <==> x" DOC "y")
5672 #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5673 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5674 "x." NAME "(y) <==> x" DOC "y")
5675 #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5676 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5677 "x." NAME "(y) <==> y" DOC "x")
5678 #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5679 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5680 "x." NAME "(y) <==> " DOC)
5681 #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5682 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5683 "x." NAME "(y) <==> " DOC)
5685 static slotdef slotdefs
[] = {
5686 SQSLOT("__len__", sq_length
, slot_sq_length
, wrap_lenfunc
,
5687 "x.__len__() <==> len(x)"),
5688 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5689 The logic in abstract.c always falls back to nb_add/nb_multiply in
5690 this case. Defining both the nb_* and the sq_* slots to call the
5691 user-defined methods has unexpected side-effects, as shown by
5692 test_descr.notimplemented() */
5693 SQSLOT("__add__", sq_concat
, NULL
, wrap_binaryfunc
,
5694 "x.__add__(y) <==> x+y"),
5695 SQSLOT("__mul__", sq_repeat
, NULL
, wrap_indexargfunc
,
5696 "x.__mul__(n) <==> x*n"),
5697 SQSLOT("__rmul__", sq_repeat
, NULL
, wrap_indexargfunc
,
5698 "x.__rmul__(n) <==> n*x"),
5699 SQSLOT("__getitem__", sq_item
, slot_sq_item
, wrap_sq_item
,
5700 "x.__getitem__(y) <==> x[y]"),
5701 SQSLOT("__getslice__", sq_slice
, slot_sq_slice
, wrap_ssizessizeargfunc
,
5702 "x.__getslice__(i, j) <==> x[i:j]\n\
5704 Use of negative indices is not supported."),
5705 SQSLOT("__setitem__", sq_ass_item
, slot_sq_ass_item
, wrap_sq_setitem
,
5706 "x.__setitem__(i, y) <==> x[i]=y"),
5707 SQSLOT("__delitem__", sq_ass_item
, slot_sq_ass_item
, wrap_sq_delitem
,
5708 "x.__delitem__(y) <==> del x[y]"),
5709 SQSLOT("__setslice__", sq_ass_slice
, slot_sq_ass_slice
,
5710 wrap_ssizessizeobjargproc
,
5711 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5713 Use of negative indices is not supported."),
5714 SQSLOT("__delslice__", sq_ass_slice
, slot_sq_ass_slice
, wrap_delslice
,
5715 "x.__delslice__(i, j) <==> del x[i:j]\n\
5717 Use of negative indices is not supported."),
5718 SQSLOT("__contains__", sq_contains
, slot_sq_contains
, wrap_objobjproc
,
5719 "x.__contains__(y) <==> y in x"),
5720 SQSLOT("__iadd__", sq_inplace_concat
, NULL
,
5721 wrap_binaryfunc
, "x.__iadd__(y) <==> x+=y"),
5722 SQSLOT("__imul__", sq_inplace_repeat
, NULL
,
5723 wrap_indexargfunc
, "x.__imul__(y) <==> x*=y"),
5725 MPSLOT("__len__", mp_length
, slot_mp_length
, wrap_lenfunc
,
5726 "x.__len__() <==> len(x)"),
5727 MPSLOT("__getitem__", mp_subscript
, slot_mp_subscript
,
5729 "x.__getitem__(y) <==> x[y]"),
5730 MPSLOT("__setitem__", mp_ass_subscript
, slot_mp_ass_subscript
,
5732 "x.__setitem__(i, y) <==> x[i]=y"),
5733 MPSLOT("__delitem__", mp_ass_subscript
, slot_mp_ass_subscript
,
5735 "x.__delitem__(y) <==> del x[y]"),
5737 BINSLOT("__add__", nb_add
, slot_nb_add
,
5739 RBINSLOT("__radd__", nb_add
, slot_nb_add
,
5741 BINSLOT("__sub__", nb_subtract
, slot_nb_subtract
,
5743 RBINSLOT("__rsub__", nb_subtract
, slot_nb_subtract
,
5745 BINSLOT("__mul__", nb_multiply
, slot_nb_multiply
,
5747 RBINSLOT("__rmul__", nb_multiply
, slot_nb_multiply
,
5749 BINSLOT("__div__", nb_divide
, slot_nb_divide
,
5751 RBINSLOT("__rdiv__", nb_divide
, slot_nb_divide
,
5753 BINSLOT("__mod__", nb_remainder
, slot_nb_remainder
,
5755 RBINSLOT("__rmod__", nb_remainder
, slot_nb_remainder
,
5757 BINSLOTNOTINFIX("__divmod__", nb_divmod
, slot_nb_divmod
,
5759 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod
, slot_nb_divmod
,
5761 NBSLOT("__pow__", nb_power
, slot_nb_power
, wrap_ternaryfunc
,
5762 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5763 NBSLOT("__rpow__", nb_power
, slot_nb_power
, wrap_ternaryfunc_r
,
5764 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5765 UNSLOT("__neg__", nb_negative
, slot_nb_negative
, wrap_unaryfunc
, "-x"),
5766 UNSLOT("__pos__", nb_positive
, slot_nb_positive
, wrap_unaryfunc
, "+x"),
5767 UNSLOT("__abs__", nb_absolute
, slot_nb_absolute
, wrap_unaryfunc
,
5769 UNSLOT("__nonzero__", nb_nonzero
, slot_nb_nonzero
, wrap_inquirypred
,
5771 UNSLOT("__invert__", nb_invert
, slot_nb_invert
, wrap_unaryfunc
, "~x"),
5772 BINSLOT("__lshift__", nb_lshift
, slot_nb_lshift
, "<<"),
5773 RBINSLOT("__rlshift__", nb_lshift
, slot_nb_lshift
, "<<"),
5774 BINSLOT("__rshift__", nb_rshift
, slot_nb_rshift
, ">>"),
5775 RBINSLOT("__rrshift__", nb_rshift
, slot_nb_rshift
, ">>"),
5776 BINSLOT("__and__", nb_and
, slot_nb_and
, "&"),
5777 RBINSLOT("__rand__", nb_and
, slot_nb_and
, "&"),
5778 BINSLOT("__xor__", nb_xor
, slot_nb_xor
, "^"),
5779 RBINSLOT("__rxor__", nb_xor
, slot_nb_xor
, "^"),
5780 BINSLOT("__or__", nb_or
, slot_nb_or
, "|"),
5781 RBINSLOT("__ror__", nb_or
, slot_nb_or
, "|"),
5782 NBSLOT("__coerce__", nb_coerce
, slot_nb_coerce
, wrap_coercefunc
,
5783 "x.__coerce__(y) <==> coerce(x, y)"),
5784 UNSLOT("__int__", nb_int
, slot_nb_int
, wrap_unaryfunc
,
5786 UNSLOT("__long__", nb_long
, slot_nb_long
, wrap_unaryfunc
,
5788 UNSLOT("__float__", nb_float
, slot_nb_float
, wrap_unaryfunc
,
5790 UNSLOT("__oct__", nb_oct
, slot_nb_oct
, wrap_unaryfunc
,
5792 UNSLOT("__hex__", nb_hex
, slot_nb_hex
, wrap_unaryfunc
,
5794 NBSLOT("__index__", nb_index
, slot_nb_index
, wrap_unaryfunc
,
5795 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5796 IBSLOT("__iadd__", nb_inplace_add
, slot_nb_inplace_add
,
5797 wrap_binaryfunc
, "+"),
5798 IBSLOT("__isub__", nb_inplace_subtract
, slot_nb_inplace_subtract
,
5799 wrap_binaryfunc
, "-"),
5800 IBSLOT("__imul__", nb_inplace_multiply
, slot_nb_inplace_multiply
,
5801 wrap_binaryfunc
, "*"),
5802 IBSLOT("__idiv__", nb_inplace_divide
, slot_nb_inplace_divide
,
5803 wrap_binaryfunc
, "/"),
5804 IBSLOT("__imod__", nb_inplace_remainder
, slot_nb_inplace_remainder
,
5805 wrap_binaryfunc
, "%"),
5806 IBSLOT("__ipow__", nb_inplace_power
, slot_nb_inplace_power
,
5807 wrap_binaryfunc
, "**"),
5808 IBSLOT("__ilshift__", nb_inplace_lshift
, slot_nb_inplace_lshift
,
5809 wrap_binaryfunc
, "<<"),
5810 IBSLOT("__irshift__", nb_inplace_rshift
, slot_nb_inplace_rshift
,
5811 wrap_binaryfunc
, ">>"),
5812 IBSLOT("__iand__", nb_inplace_and
, slot_nb_inplace_and
,
5813 wrap_binaryfunc
, "&"),
5814 IBSLOT("__ixor__", nb_inplace_xor
, slot_nb_inplace_xor
,
5815 wrap_binaryfunc
, "^"),
5816 IBSLOT("__ior__", nb_inplace_or
, slot_nb_inplace_or
,
5817 wrap_binaryfunc
, "|"),
5818 BINSLOT("__floordiv__", nb_floor_divide
, slot_nb_floor_divide
, "//"),
5819 RBINSLOT("__rfloordiv__", nb_floor_divide
, slot_nb_floor_divide
, "//"),
5820 BINSLOT("__truediv__", nb_true_divide
, slot_nb_true_divide
, "/"),
5821 RBINSLOT("__rtruediv__", nb_true_divide
, slot_nb_true_divide
, "/"),
5822 IBSLOT("__ifloordiv__", nb_inplace_floor_divide
,
5823 slot_nb_inplace_floor_divide
, wrap_binaryfunc
, "//"),
5824 IBSLOT("__itruediv__", nb_inplace_true_divide
,
5825 slot_nb_inplace_true_divide
, wrap_binaryfunc
, "/"),
5827 TPSLOT("__str__", tp_str
, slot_tp_str
, wrap_unaryfunc
,
5828 "x.__str__() <==> str(x)"),
5829 TPSLOT("__str__", tp_print
, NULL
, NULL
, ""),
5830 TPSLOT("__repr__", tp_repr
, slot_tp_repr
, wrap_unaryfunc
,
5831 "x.__repr__() <==> repr(x)"),
5832 TPSLOT("__repr__", tp_print
, NULL
, NULL
, ""),
5833 TPSLOT("__cmp__", tp_compare
, _PyObject_SlotCompare
, wrap_cmpfunc
,
5834 "x.__cmp__(y) <==> cmp(x,y)"),
5835 TPSLOT("__hash__", tp_hash
, slot_tp_hash
, wrap_hashfunc
,
5836 "x.__hash__() <==> hash(x)"),
5837 FLSLOT("__call__", tp_call
, slot_tp_call
, (wrapperfunc
)wrap_call
,
5838 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS
),
5839 TPSLOT("__getattribute__", tp_getattro
, slot_tp_getattr_hook
,
5840 wrap_binaryfunc
, "x.__getattribute__('name') <==> x.name"),
5841 TPSLOT("__getattribute__", tp_getattr
, NULL
, NULL
, ""),
5842 TPSLOT("__getattr__", tp_getattro
, slot_tp_getattr_hook
, NULL
, ""),
5843 TPSLOT("__getattr__", tp_getattr
, NULL
, NULL
, ""),
5844 TPSLOT("__setattr__", tp_setattro
, slot_tp_setattro
, wrap_setattr
,
5845 "x.__setattr__('name', value) <==> x.name = value"),
5846 TPSLOT("__setattr__", tp_setattr
, NULL
, NULL
, ""),
5847 TPSLOT("__delattr__", tp_setattro
, slot_tp_setattro
, wrap_delattr
,
5848 "x.__delattr__('name') <==> del x.name"),
5849 TPSLOT("__delattr__", tp_setattr
, NULL
, NULL
, ""),
5850 TPSLOT("__lt__", tp_richcompare
, slot_tp_richcompare
, richcmp_lt
,
5851 "x.__lt__(y) <==> x<y"),
5852 TPSLOT("__le__", tp_richcompare
, slot_tp_richcompare
, richcmp_le
,
5853 "x.__le__(y) <==> x<=y"),
5854 TPSLOT("__eq__", tp_richcompare
, slot_tp_richcompare
, richcmp_eq
,
5855 "x.__eq__(y) <==> x==y"),
5856 TPSLOT("__ne__", tp_richcompare
, slot_tp_richcompare
, richcmp_ne
,
5857 "x.__ne__(y) <==> x!=y"),
5858 TPSLOT("__gt__", tp_richcompare
, slot_tp_richcompare
, richcmp_gt
,
5859 "x.__gt__(y) <==> x>y"),
5860 TPSLOT("__ge__", tp_richcompare
, slot_tp_richcompare
, richcmp_ge
,
5861 "x.__ge__(y) <==> x>=y"),
5862 TPSLOT("__iter__", tp_iter
, slot_tp_iter
, wrap_unaryfunc
,
5863 "x.__iter__() <==> iter(x)"),
5864 TPSLOT("next", tp_iternext
, slot_tp_iternext
, wrap_next
,
5865 "x.next() -> the next value, or raise StopIteration"),
5866 TPSLOT("__get__", tp_descr_get
, slot_tp_descr_get
, wrap_descr_get
,
5867 "descr.__get__(obj[, type]) -> value"),
5868 TPSLOT("__set__", tp_descr_set
, slot_tp_descr_set
, wrap_descr_set
,
5869 "descr.__set__(obj, value)"),
5870 TPSLOT("__delete__", tp_descr_set
, slot_tp_descr_set
,
5871 wrap_descr_delete
, "descr.__delete__(obj)"),
5872 FLSLOT("__init__", tp_init
, slot_tp_init
, (wrapperfunc
)wrap_init
,
5873 "x.__init__(...) initializes x; "
5874 "see x.__class__.__doc__ for signature",
5875 PyWrapperFlag_KEYWORDS
),
5876 TPSLOT("__new__", tp_new
, slot_tp_new
, NULL
, ""),
5877 TPSLOT("__del__", tp_del
, slot_tp_del
, NULL
, ""),
5881 /* Given a type pointer and an offset gotten from a slotdef entry, return a
5882 pointer to the actual slot. This is not quite the same as simply adding
5883 the offset to the type pointer, since it takes care to indirect through the
5884 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5885 indirection pointer is NULL. */
5887 slotptr(PyTypeObject
*type
, int ioffset
)
5890 long offset
= ioffset
;
5892 /* Note: this depends on the order of the members of PyHeapTypeObject! */
5893 assert(offset
>= 0);
5894 assert((size_t)offset
< offsetof(PyHeapTypeObject
, as_buffer
));
5895 if ((size_t)offset
>= offsetof(PyHeapTypeObject
, as_sequence
)) {
5896 ptr
= (char *)type
->tp_as_sequence
;
5897 offset
-= offsetof(PyHeapTypeObject
, as_sequence
);
5899 else if ((size_t)offset
>= offsetof(PyHeapTypeObject
, as_mapping
)) {
5900 ptr
= (char *)type
->tp_as_mapping
;
5901 offset
-= offsetof(PyHeapTypeObject
, as_mapping
);
5903 else if ((size_t)offset
>= offsetof(PyHeapTypeObject
, as_number
)) {
5904 ptr
= (char *)type
->tp_as_number
;
5905 offset
-= offsetof(PyHeapTypeObject
, as_number
);
5912 return (void **)ptr
;
5915 /* Length of array of slotdef pointers used to store slots with the
5916 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5917 the same __name__, for any __name__. Since that's a static property, it is
5918 appropriate to declare fixed-size arrays for this. */
5919 #define MAX_EQUIV 10
5921 /* Return a slot pointer for a given name, but ONLY if the attribute has
5922 exactly one slot function. The name must be an interned string. */
5924 resolve_slotdups(PyTypeObject
*type
, PyObject
*name
)
5926 /* XXX Maybe this could be optimized more -- but is it worth it? */
5928 /* pname and ptrs act as a little cache */
5929 static PyObject
*pname
;
5930 static slotdef
*ptrs
[MAX_EQUIV
];
5934 if (pname
!= name
) {
5935 /* Collect all slotdefs that match name into ptrs. */
5938 for (p
= slotdefs
; p
->name_strobj
; p
++) {
5939 if (p
->name_strobj
== name
)
5945 /* Look in all matching slots of the type; if exactly one of these has
5946 a filled-in slot, return its value. Otherwise return NULL. */
5948 for (pp
= ptrs
; *pp
; pp
++) {
5949 ptr
= slotptr(type
, (*pp
)->offset
);
5950 if (ptr
== NULL
|| *ptr
== NULL
)
5959 /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
5960 does some incredibly complex thinking and then sticks something into the
5961 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5962 interests, and then stores a generic wrapper or a specific function into
5963 the slot.) Return a pointer to the next slotdef with a different offset,
5964 because that's convenient for fixup_slot_dispatchers(). */
5966 update_one_slot(PyTypeObject
*type
, slotdef
*p
)
5969 PyWrapperDescrObject
*d
;
5970 void *generic
= NULL
, *specific
= NULL
;
5971 int use_generic
= 0;
5972 int offset
= p
->offset
;
5973 void **ptr
= slotptr(type
, offset
);
5978 } while (p
->offset
== offset
);
5982 descr
= _PyType_Lookup(type
, p
->name_strobj
);
5985 if (Py_TYPE(descr
) == &PyWrapperDescr_Type
) {
5986 void **tptr
= resolve_slotdups(type
, p
->name_strobj
);
5987 if (tptr
== NULL
|| tptr
== ptr
)
5988 generic
= p
->function
;
5989 d
= (PyWrapperDescrObject
*)descr
;
5990 if (d
->d_base
->wrapper
== p
->wrapper
&&
5991 PyType_IsSubtype(type
, d
->d_type
))
5993 if (specific
== NULL
||
5994 specific
== d
->d_wrapped
)
5995 specific
= d
->d_wrapped
;
6000 else if (Py_TYPE(descr
) == &PyCFunction_Type
&&
6001 PyCFunction_GET_FUNCTION(descr
) ==
6002 (PyCFunction
)tp_new_wrapper
&&
6003 strcmp(p
->name
, "__new__") == 0)
6005 /* The __new__ wrapper is not a wrapper descriptor,
6006 so must be special-cased differently.
6007 If we don't do this, creating an instance will
6008 always use slot_tp_new which will look up
6009 __new__ in the MRO which will call tp_new_wrapper
6010 which will look through the base classes looking
6011 for a static base and call its tp_new (usually
6012 PyType_GenericNew), after performing various
6013 sanity checks and constructing a new argument
6014 list. Cut all that nonsense short -- this speeds
6015 up instance creation tremendously. */
6016 specific
= (void *)type
->tp_new
;
6017 /* XXX I'm not 100% sure that there isn't a hole
6018 in this reasoning that requires additional
6019 sanity checks. I'll buy the first person to
6020 point out a bug in this reasoning a beer. */
6024 generic
= p
->function
;
6026 } while ((++p
)->offset
== offset
);
6027 if (specific
&& !use_generic
)
6034 /* In the type, update the slots whose slotdefs are gathered in the pp array.
6035 This is a callback for update_subclasses(). */
6037 update_slots_callback(PyTypeObject
*type
, void *data
)
6039 slotdef
**pp
= (slotdef
**)data
;
6042 update_one_slot(type
, *pp
);
6046 /* Comparison function for qsort() to compare slotdefs by their offset, and
6047 for equal offset by their address (to force a stable sort). */
6049 slotdef_cmp(const void *aa
, const void *bb
)
6051 const slotdef
*a
= (const slotdef
*)aa
, *b
= (const slotdef
*)bb
;
6052 int c
= a
->offset
- b
->offset
;
6056 /* Cannot use a-b, as this gives off_t,
6057 which may lose precision when converted to int. */
6058 return (a
> b
) ? 1 : (a
< b
) ? -1 : 0;
6061 /* Initialize the slotdefs table by adding interned string objects for the
6062 names and sorting the entries. */
6067 static int initialized
= 0;
6071 for (p
= slotdefs
; p
->name
; p
++) {
6072 p
->name_strobj
= PyString_InternFromString(p
->name
);
6073 if (!p
->name_strobj
)
6074 Py_FatalError("Out of memory interning slotdef names");
6076 qsort((void *)slotdefs
, (size_t)(p
-slotdefs
), sizeof(slotdef
),
6081 /* Update the slots after assignment to a class (type) attribute. */
6083 update_slot(PyTypeObject
*type
, PyObject
*name
)
6085 slotdef
*ptrs
[MAX_EQUIV
];
6090 /* Clear the VALID_VERSION flag of 'type' and all its
6091 subclasses. This could possibly be unified with the
6092 update_subclasses() recursion below, but carefully:
6093 they each have their own conditions on which to stop
6094 recursing into subclasses. */
6095 type_modified(type
);
6099 for (p
= slotdefs
; p
->name
; p
++) {
6100 /* XXX assume name is interned! */
6101 if (p
->name_strobj
== name
)
6105 for (pp
= ptrs
; *pp
; pp
++) {
6108 while (p
> slotdefs
&& (p
-1)->offset
== offset
)
6112 if (ptrs
[0] == NULL
)
6113 return 0; /* Not an attribute that affects any slots */
6114 return update_subclasses(type
, name
,
6115 update_slots_callback
, (void *)ptrs
);
6118 /* Store the proper functions in the slot dispatches at class (type)
6119 definition time, based upon which operations the class overrides in its
6122 fixup_slot_dispatchers(PyTypeObject
*type
)
6127 for (p
= slotdefs
; p
->name
; )
6128 p
= update_one_slot(type
, p
);
6132 update_all_slots(PyTypeObject
* type
)
6137 for (p
= slotdefs
; p
->name
; p
++) {
6138 /* update_slot returns int but can't actually fail */
6139 update_slot(type
, p
->name_strobj
);
6143 /* recurse_down_subclasses() and update_subclasses() are mutually
6144 recursive functions to call a callback for all subclasses,
6145 but refraining from recursing into subclasses that define 'name'. */
6148 update_subclasses(PyTypeObject
*type
, PyObject
*name
,
6149 update_callback callback
, void *data
)
6151 if (callback(type
, data
) < 0)
6153 return recurse_down_subclasses(type
, name
, callback
, data
);
6157 recurse_down_subclasses(PyTypeObject
*type
, PyObject
*name
,
6158 update_callback callback
, void *data
)
6160 PyTypeObject
*subclass
;
6161 PyObject
*ref
, *subclasses
, *dict
;
6164 subclasses
= type
->tp_subclasses
;
6165 if (subclasses
== NULL
)
6167 assert(PyList_Check(subclasses
));
6168 n
= PyList_GET_SIZE(subclasses
);
6169 for (i
= 0; i
< n
; i
++) {
6170 ref
= PyList_GET_ITEM(subclasses
, i
);
6171 assert(PyWeakref_CheckRef(ref
));
6172 subclass
= (PyTypeObject
*)PyWeakref_GET_OBJECT(ref
);
6173 assert(subclass
!= NULL
);
6174 if ((PyObject
*)subclass
== Py_None
)
6176 assert(PyType_Check(subclass
));
6177 /* Avoid recursing down into unaffected classes */
6178 dict
= subclass
->tp_dict
;
6179 if (dict
!= NULL
&& PyDict_Check(dict
) &&
6180 PyDict_GetItem(dict
, name
) != NULL
)
6182 if (update_subclasses(subclass
, name
, callback
, data
) < 0)
6188 /* This function is called by PyType_Ready() to populate the type's
6189 dictionary with method descriptors for function slots. For each
6190 function slot (like tp_repr) that's defined in the type, one or more
6191 corresponding descriptors are added in the type's tp_dict dictionary
6192 under the appropriate name (like __repr__). Some function slots
6193 cause more than one descriptor to be added (for example, the nb_add
6194 slot adds both __add__ and __radd__ descriptors) and some function
6195 slots compete for the same descriptor (for example both sq_item and
6196 mp_subscript generate a __getitem__ descriptor).
6198 In the latter case, the first slotdef entry encoutered wins. Since
6199 slotdef entries are sorted by the offset of the slot in the
6200 PyHeapTypeObject, this gives us some control over disambiguating
6201 between competing slots: the members of PyHeapTypeObject are listed
6202 from most general to least general, so the most general slot is
6203 preferred. In particular, because as_mapping comes before as_sequence,
6204 for a type that defines both mp_subscript and sq_item, mp_subscript
6207 This only adds new descriptors and doesn't overwrite entries in
6208 tp_dict that were previously defined. The descriptors contain a
6209 reference to the C function they must call, so that it's safe if they
6210 are copied into a subtype's __dict__ and the subtype has a different
6211 C function in its slot -- calling the method defined by the
6212 descriptor will call the C function that was used to create it,
6213 rather than the C function present in the slot when it is called.
6214 (This is important because a subtype may have a C function in the
6215 slot that calls the method from the dictionary, and we want to avoid
6216 infinite recursion here.) */
6219 add_operators(PyTypeObject
*type
)
6221 PyObject
*dict
= type
->tp_dict
;
6227 for (p
= slotdefs
; p
->name
; p
++) {
6228 if (p
->wrapper
== NULL
)
6230 ptr
= slotptr(type
, p
->offset
);
6233 if (PyDict_GetItem(dict
, p
->name_strobj
))
6235 descr
= PyDescr_NewWrapper(type
, p
, *ptr
);
6238 if (PyDict_SetItem(dict
, p
->name_strobj
, descr
) < 0)
6242 if (type
->tp_new
!= NULL
) {
6243 if (add_tp_new_wrapper(type
) < 0)
6250 /* Cooperative 'super' */
6256 PyTypeObject
*obj_type
;
6259 static PyMemberDef super_members
[] = {
6260 {"__thisclass__", T_OBJECT
, offsetof(superobject
, type
), READONLY
,
6261 "the class invoking super()"},
6262 {"__self__", T_OBJECT
, offsetof(superobject
, obj
), READONLY
,
6263 "the instance invoking super(); may be None"},
6264 {"__self_class__", T_OBJECT
, offsetof(superobject
, obj_type
), READONLY
,
6265 "the type of the instance invoking super(); may be None"},
6270 super_dealloc(PyObject
*self
)
6272 superobject
*su
= (superobject
*)self
;
6274 _PyObject_GC_UNTRACK(self
);
6275 Py_XDECREF(su
->obj
);
6276 Py_XDECREF(su
->type
);
6277 Py_XDECREF(su
->obj_type
);
6278 Py_TYPE(self
)->tp_free(self
);
6282 super_repr(PyObject
*self
)
6284 superobject
*su
= (superobject
*)self
;
6287 return PyString_FromFormat(
6288 "<super: <class '%s'>, <%s object>>",
6289 su
->type
? su
->type
->tp_name
: "NULL",
6290 su
->obj_type
->tp_name
);
6292 return PyString_FromFormat(
6293 "<super: <class '%s'>, NULL>",
6294 su
->type
? su
->type
->tp_name
: "NULL");
6298 super_getattro(PyObject
*self
, PyObject
*name
)
6300 superobject
*su
= (superobject
*)self
;
6301 int skip
= su
->obj_type
== NULL
;
6304 /* We want __class__ to return the class of the super object
6305 (i.e. super, or a subclass), not the class of su->obj. */
6306 skip
= (PyString_Check(name
) &&
6307 PyString_GET_SIZE(name
) == 9 &&
6308 strcmp(PyString_AS_STRING(name
), "__class__") == 0);
6312 PyObject
*mro
, *res
, *tmp
, *dict
;
6313 PyTypeObject
*starttype
;
6317 starttype
= su
->obj_type
;
6318 mro
= starttype
->tp_mro
;
6323 assert(PyTuple_Check(mro
));
6324 n
= PyTuple_GET_SIZE(mro
);
6326 for (i
= 0; i
< n
; i
++) {
6327 if ((PyObject
*)(su
->type
) == PyTuple_GET_ITEM(mro
, i
))
6332 for (; i
< n
; i
++) {
6333 tmp
= PyTuple_GET_ITEM(mro
, i
);
6334 if (PyType_Check(tmp
))
6335 dict
= ((PyTypeObject
*)tmp
)->tp_dict
;
6336 else if (PyClass_Check(tmp
))
6337 dict
= ((PyClassObject
*)tmp
)->cl_dict
;
6340 res
= PyDict_GetItem(dict
, name
);
6343 f
= Py_TYPE(res
)->tp_descr_get
;
6346 /* Only pass 'obj' param if
6347 this is instance-mode super
6350 (su
->obj
== (PyObject
*)
6354 (PyObject
*)starttype
);
6362 return PyObject_GenericGetAttr(self
, name
);
6365 static PyTypeObject
*
6366 supercheck(PyTypeObject
*type
, PyObject
*obj
)
6368 /* Check that a super() call makes sense. Return a type object.
6370 obj can be a new-style class, or an instance of one:
6372 - If it is a class, it must be a subclass of 'type'. This case is
6373 used for class methods; the return value is obj.
6375 - If it is an instance, it must be an instance of 'type'. This is
6376 the normal case; the return value is obj.__class__.
6378 But... when obj is an instance, we want to allow for the case where
6379 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6380 This will allow using super() with a proxy for obj.
6383 /* Check for first bullet above (special case) */
6384 if (PyType_Check(obj
) && PyType_IsSubtype((PyTypeObject
*)obj
, type
)) {
6386 return (PyTypeObject
*)obj
;
6390 if (PyType_IsSubtype(Py_TYPE(obj
), type
)) {
6391 Py_INCREF(Py_TYPE(obj
));
6392 return Py_TYPE(obj
);
6395 /* Try the slow way */
6396 static PyObject
*class_str
= NULL
;
6397 PyObject
*class_attr
;
6399 if (class_str
== NULL
) {
6400 class_str
= PyString_FromString("__class__");
6401 if (class_str
== NULL
)
6405 class_attr
= PyObject_GetAttr(obj
, class_str
);
6407 if (class_attr
!= NULL
&&
6408 PyType_Check(class_attr
) &&
6409 (PyTypeObject
*)class_attr
!= Py_TYPE(obj
))
6411 int ok
= PyType_IsSubtype(
6412 (PyTypeObject
*)class_attr
, type
);
6414 return (PyTypeObject
*)class_attr
;
6417 if (class_attr
== NULL
)
6420 Py_DECREF(class_attr
);
6423 PyErr_SetString(PyExc_TypeError
,
6424 "super(type, obj): "
6425 "obj must be an instance or subtype of type");
6430 super_descr_get(PyObject
*self
, PyObject
*obj
, PyObject
*type
)
6432 superobject
*su
= (superobject
*)self
;
6433 superobject
*newobj
;
6435 if (obj
== NULL
|| obj
== Py_None
|| su
->obj
!= NULL
) {
6436 /* Not binding to an object, or already bound */
6440 if (Py_TYPE(su
) != &PySuper_Type
)
6441 /* If su is an instance of a (strict) subclass of super,
6443 return PyObject_CallFunctionObjArgs((PyObject
*)Py_TYPE(su
),
6444 su
->type
, obj
, NULL
);
6446 /* Inline the common case */
6447 PyTypeObject
*obj_type
= supercheck(su
->type
, obj
);
6448 if (obj_type
== NULL
)
6450 newobj
= (superobject
*)PySuper_Type
.tp_new(&PySuper_Type
,
6454 Py_INCREF(su
->type
);
6456 newobj
->type
= su
->type
;
6458 newobj
->obj_type
= obj_type
;
6459 return (PyObject
*)newobj
;
6464 super_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
6466 superobject
*su
= (superobject
*)self
;
6468 PyObject
*obj
= NULL
;
6469 PyTypeObject
*obj_type
= NULL
;
6471 if (!_PyArg_NoKeywords("super", kwds
))
6473 if (!PyArg_ParseTuple(args
, "O!|O:super", &PyType_Type
, &type
, &obj
))
6478 obj_type
= supercheck(type
, obj
);
6479 if (obj_type
== NULL
)
6486 su
->obj_type
= obj_type
;
6490 PyDoc_STRVAR(super_doc
,
6491 "super(type) -> unbound super object\n"
6492 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
6493 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
6494 "Typical use to call a cooperative superclass method:\n"
6496 " def meth(self, arg):\n"
6497 " super(C, self).meth(arg)");
6500 super_traverse(PyObject
*self
, visitproc visit
, void *arg
)
6502 superobject
*su
= (superobject
*)self
;
6506 Py_VISIT(su
->obj_type
);
6511 PyTypeObject PySuper_Type
= {
6512 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
6513 "super", /* tp_name */
6514 sizeof(superobject
), /* tp_basicsize */
6515 0, /* tp_itemsize */
6517 super_dealloc
, /* tp_dealloc */
6522 super_repr
, /* tp_repr */
6523 0, /* tp_as_number */
6524 0, /* tp_as_sequence */
6525 0, /* tp_as_mapping */
6529 super_getattro
, /* tp_getattro */
6530 0, /* tp_setattro */
6531 0, /* tp_as_buffer */
6532 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
6533 Py_TPFLAGS_BASETYPE
, /* tp_flags */
6534 super_doc
, /* tp_doc */
6535 super_traverse
, /* tp_traverse */
6537 0, /* tp_richcompare */
6538 0, /* tp_weaklistoffset */
6540 0, /* tp_iternext */
6542 super_members
, /* tp_members */
6546 super_descr_get
, /* tp_descr_get */
6547 0, /* tp_descr_set */
6548 0, /* tp_dictoffset */
6549 super_init
, /* tp_init */
6550 PyType_GenericAlloc
, /* tp_alloc */
6551 PyType_GenericNew
, /* tp_new */
6552 PyObject_GC_Del
, /* tp_free */