FL, flp, and fl from IRIX have been deprecated for removal in 3.0.
[python.git] / Objects / typeobject.c
blob4dfd39e9fab99755ef37c489128cf916b81ea712
1 /* Type object implementation */
3 #include "Python.h"
4 #include "structmember.h"
6 #include <ctype.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 {
28 unsigned int version;
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 *);
37 unsigned int
38 PyType_ClearCache(void)
40 Py_ssize_t i;
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;
48 next_version_tag = 0;
49 /* mark all version tags as invalid */
50 type_modified(&PyBaseObject_Type);
51 return cur_version_tag;
54 static void
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.
61 Invariants:
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
74 needed.
76 PyObject *raw, *ref;
77 Py_ssize_t i, n;
79 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
80 return;
82 raw = type->tp_subclasses;
83 if (raw != NULL) {
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);
88 if (ref != Py_None) {
89 type_modified((PyTypeObject *)ref);
93 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
96 static void
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
107 types.
109 Called from mro_internal, which will subsequently be called on
110 each subclass when their mro is recursively updated.
112 Py_ssize_t i, n;
113 int clear = 0;
115 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
116 return;
118 n = PyTuple_GET_SIZE(bases);
119 for (i = 0; i < n; i++) {
120 PyObject *b = PyTuple_GET_ITEM(bases, i);
121 PyTypeObject *cls;
123 if (!PyType_Check(b) ) {
124 clear = 1;
125 break;
128 cls = (PyTypeObject *)b;
130 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
131 !PyType_IsSubtype(type, cls)) {
132 clear = 1;
133 break;
137 if (clear)
138 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
139 Py_TPFLAGS_VALID_VERSION_TAG);
142 static int
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.
150 Py_ssize_t i, n;
151 PyObject *bases;
153 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
154 return 1;
155 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
156 return 0;
157 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
158 return 0;
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;
172 Py_INCREF(Py_None);
174 /* mark all version tags as invalid */
175 type_modified(&PyBaseObject_Type);
176 return 1;
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))
184 return 0;
186 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
187 return 1;
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},
204 static PyObject *
205 type_name(PyTypeObject *type, void *context)
207 const char *s;
209 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
210 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
212 Py_INCREF(et->ht_name);
213 return et->ht_name;
215 else {
216 s = strrchr(type->tp_name, '.');
217 if (s == NULL)
218 s = type->tp_name;
219 else
220 s++;
221 return PyString_FromString(s);
225 static int
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);
233 return -1;
235 if (!value) {
236 PyErr_Format(PyExc_TypeError,
237 "can't delete %s.__name__", type->tp_name);
238 return -1;
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);
244 return -1;
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");
250 return -1;
253 et = (PyHeapTypeObject*)type;
255 Py_INCREF(value);
257 Py_DECREF(et->ht_name);
258 et->ht_name = value;
260 type->tp_name = PyString_AS_STRING(value);
262 return 0;
265 static PyObject *
266 type_module(PyTypeObject *type, void *context)
268 PyObject *mod;
269 char *s;
271 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
272 mod = PyDict_GetItemString(type->tp_dict, "__module__");
273 if (!mod) {
274 PyErr_Format(PyExc_AttributeError, "__module__");
275 return 0;
277 Py_XINCREF(mod);
278 return mod;
280 else {
281 s = strrchr(type->tp_name, '.');
282 if (s != NULL)
283 return PyString_FromStringAndSize(
284 type->tp_name, (Py_ssize_t)(s - type->tp_name));
285 return PyString_FromString("__builtin__");
289 static int
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);
295 return -1;
297 if (!value) {
298 PyErr_Format(PyExc_TypeError,
299 "can't delete %s.__module__", type->tp_name);
300 return -1;
303 type_modified(type);
305 return PyDict_SetItemString(type->tp_dict, "__module__", value);
308 static PyObject *
309 type_abstractmethods(PyTypeObject *type, void *context)
311 PyObject *mod = PyDict_GetItemString(type->tp_dict,
312 "__abstractmethods__");
313 if (!mod) {
314 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
315 return NULL;
317 Py_XINCREF(mod);
318 return mod;
321 static int
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);
330 if (res == 0) {
331 type_modified(type);
332 if (value && PyObject_IsTrue(value)) {
333 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
335 else {
336 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
339 return res;
342 static PyObject *
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);
362 static int
363 mro_subclasses(PyTypeObject *type, PyObject* temp)
365 PyTypeObject *subclass;
366 PyObject *ref, *subclasses, *old_mro;
367 Py_ssize_t i, n;
369 subclasses = type->tp_subclasses;
370 if (subclasses == NULL)
371 return 0;
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)
380 continue;
381 assert(PyType_Check(subclass));
382 old_mro = subclass->tp_mro;
383 if (mro_internal(subclass) < 0) {
384 subclass->tp_mro = old_mro;
385 return -1;
387 else {
388 PyObject* tuple;
389 tuple = PyTuple_Pack(2, subclass, old_mro);
390 Py_DECREF(old_mro);
391 if (!tuple)
392 return -1;
393 if (PyList_Append(temp, tuple) < 0)
394 return -1;
395 Py_DECREF(tuple);
397 if (mro_subclasses(subclass, temp) < 0)
398 return -1;
400 return 0;
403 static int
404 type_set_bases(PyTypeObject *type, PyObject *value, void *context)
406 Py_ssize_t i;
407 int r = 0;
408 PyObject *ob, *temp;
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);
415 return -1;
417 if (!value) {
418 PyErr_Format(PyExc_TypeError,
419 "can't delete %s.__bases__", type->tp_name);
420 return -1;
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);
426 return -1;
428 if (PyTuple_GET_SIZE(value) == 0) {
429 PyErr_Format(PyExc_TypeError,
430 "can only assign non-empty tuple to %s.__bases__, not ()",
431 type->tp_name);
432 return -1;
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)) {
437 PyErr_Format(
438 PyExc_TypeError,
439 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
440 type->tp_name, Py_TYPE(ob)->tp_name);
441 return -1;
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");
447 return -1;
452 new_base = best_base(value);
454 if (!new_base) {
455 return -1;
458 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
459 return -1;
461 Py_INCREF(new_base);
462 Py_INCREF(value);
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) {
472 goto bail;
475 temp = PyList_New(0);
476 if (!temp)
477 goto bail;
479 r = mro_subclasses(type, temp);
481 if (r < 0) {
482 for (i = 0; i < PyList_Size(temp); i++) {
483 PyTypeObject* cls;
484 PyObject* mro;
485 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
486 "", 2, 2, &cls, &mro);
487 Py_INCREF(mro);
488 ob = cls->tp_mro;
489 cls->tp_mro = mro;
490 Py_DECREF(ob);
492 Py_DECREF(temp);
493 goto bail;
496 Py_DECREF(temp);
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)) {
509 remove_subclass(
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)
518 r = -1;
522 update_all_slots(type);
524 Py_DECREF(old_bases);
525 Py_DECREF(old_base);
526 Py_DECREF(old_mro);
528 return r;
530 bail:
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;
541 return -1;
544 static PyObject *
545 type_dict(PyTypeObject *type, void *context)
547 if (type->tp_dict == NULL) {
548 Py_INCREF(Py_None);
549 return Py_None;
551 return PyDictProxy_New(type->tp_dict);
554 static PyObject *
555 type_get_doc(PyTypeObject *type, void *context)
557 PyObject *result;
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) {
562 result = Py_None;
563 Py_INCREF(result);
565 else if (Py_TYPE(result)->tp_descr_get) {
566 result = Py_TYPE(result)->tp_descr_get(result, NULL,
567 (PyObject *)type);
569 else {
570 Py_INCREF(result);
572 return result;
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},
586 static int
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;
596 static PyObject*
597 type_richcompare(PyObject *v, PyObject *w, int op)
599 PyObject *result;
600 Py_uintptr_t vv, ww;
601 int c;
603 /* Make sure both arguments are types. */
604 if (!PyType_Check(v) || !PyType_Check(w)) {
605 result = Py_NotImplemented;
606 goto out;
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 "
613 "in 3.x", 1) < 0) {
614 return NULL;
617 /* Compare addresses */
618 vv = (Py_uintptr_t)v;
619 ww = (Py_uintptr_t)w;
620 switch (op) {
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;
627 default:
628 result = Py_NotImplemented;
629 goto out;
631 result = c ? Py_True : Py_False;
633 /* incref and return */
634 out:
635 Py_INCREF(result);
636 return result;
639 static PyObject *
640 type_repr(PyTypeObject *type)
642 PyObject *mod, *name, *rtn;
643 char *kind;
645 mod = type_module(type, NULL);
646 if (mod == NULL)
647 PyErr_Clear();
648 else if (!PyString_Check(mod)) {
649 Py_DECREF(mod);
650 mod = NULL;
652 name = type_name(type, NULL);
653 if (name == NULL)
654 return NULL;
656 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
657 kind = "class";
658 else
659 kind = "type";
661 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
662 rtn = PyString_FromFormat("<%s '%s.%s'>",
663 kind,
664 PyString_AS_STRING(mod),
665 PyString_AS_STRING(name));
667 else
668 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
670 Py_XDECREF(mod);
671 Py_DECREF(name);
672 return rtn;
675 static PyObject *
676 type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
678 PyObject *obj;
680 if (type->tp_new == NULL) {
681 PyErr_Format(PyExc_TypeError,
682 "cannot create '%.100s' instances",
683 type->tp_name);
684 return NULL;
687 obj = type->tp_new(type, args, kwds);
688 if (obj != NULL) {
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 &&
693 (kwds == NULL ||
694 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
695 return obj;
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))
699 return obj;
700 type = obj->ob_type;
701 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
702 type->tp_init != NULL &&
703 type->tp_init(obj, args, kwds) < 0) {
704 Py_DECREF(obj);
705 obj = NULL;
708 return obj;
711 PyObject *
712 PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
714 PyObject *obj;
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);
720 else
721 obj = (PyObject *)PyObject_MALLOC(size);
723 if (obj == NULL)
724 return PyErr_NoMemory();
726 memset(obj, '\0', size);
728 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
729 Py_INCREF(type);
731 if (type->tp_itemsize == 0)
732 PyObject_INIT(obj, type);
733 else
734 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
736 if (PyType_IS_GC(type))
737 _PyObject_GC_TRACK(obj);
738 return obj;
741 PyObject *
742 PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
744 return type->tp_alloc(type, 0);
747 /* Helpers for subtyping */
749 static int
750 traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
752 Py_ssize_t i, n;
753 PyMemberDef *mp;
755 n = Py_SIZE(type);
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;
761 if (obj != NULL) {
762 int err = visit(obj, arg);
763 if (err)
764 return err;
768 return 0;
771 static int
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);
780 base = type;
781 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
782 if (Py_SIZE(base)) {
783 int err = traverse_slots(base, self, visit, arg);
784 if (err)
785 return err;
787 base = base->tp_base;
788 assert(base);
791 if (type->tp_dictoffset != base->tp_dictoffset) {
792 PyObject **dictptr = _PyObject_GetDictPtr(self);
793 if (dictptr && *dictptr)
794 Py_VISIT(*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. */
801 Py_VISIT(type);
803 if (basetraverse)
804 return basetraverse(self, visit, arg);
805 return 0;
808 static void
809 clear_slots(PyTypeObject *type, PyObject *self)
811 Py_ssize_t i, n;
812 PyMemberDef *mp;
814 n = Py_SIZE(type);
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;
820 if (obj != NULL) {
821 *(PyObject **)addr = NULL;
822 Py_DECREF(obj);
828 static int
829 subtype_clear(PyObject *self)
831 PyTypeObject *type, *base;
832 inquiry baseclear;
834 /* Find the nearest base with a different tp_clear
835 and clear slots while we're at it */
836 type = Py_TYPE(self);
837 base = type;
838 while ((baseclear = base->tp_clear) == subtype_clear) {
839 if (Py_SIZE(base))
840 clear_slots(base, self);
841 base = base->tp_base;
842 assert(base);
845 /* There's no need to clear the instance dict (if any);
846 the collector will call its tp_clear handler. */
848 if (baseclear)
849 return baseclear(self);
850 return 0;
853 static void
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 */
873 if (type->tp_del) {
874 type->tp_del(self);
875 if (self->ob_refcnt > 0)
876 return;
879 /* Find the nearest base with a different tp_dealloc */
880 base = type;
881 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
882 assert(Py_SIZE(base) == 0);
883 base = base->tp_base;
884 assert(base);
887 /* Call the base tp_dealloc() */
888 assert(basedealloc);
889 basedealloc(self);
891 /* Can't reference self beyond this point */
892 Py_DECREF(type);
894 /* Done */
895 return;
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 */
913 base = type;
914 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
915 base = base->tp_base;
916 assert(base);
919 /* If we added a weaklist, we clear it. Do this *before* calling
920 the finalizer (__del__), clearing slots, or clearing the instance
921 dict. */
923 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
924 PyObject_ClearWeakRefs(self);
926 /* Maybe call finalizer; exit early if resurrected */
927 if (type->tp_del) {
928 _PyObject_GC_TRACK(self);
929 type->tp_del(self);
930 if (self->ob_refcnt > 0)
931 goto endlabel; /* resurrected */
932 else
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);
942 while (*list)
943 _PyWeakref_ClearRef(*list);
947 /* Clear slots up to the nearest base with a different tp_dealloc */
948 base = type;
949 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
950 if (Py_SIZE(base))
951 clear_slots(base, self);
952 base = base->tp_base;
953 assert(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;
961 if (dict != NULL) {
962 Py_DECREF(dict);
963 *dictptr = NULL;
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);
973 assert(basedealloc);
974 basedealloc(self);
976 /* Can't reference self beyond this point */
977 Py_DECREF(type);
979 endlabel:
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
992 sense.
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
1004 the dance becomes:
1006 GC untrack
1007 trashcan begin
1008 GC track
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
1018 a subtle disaster.
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
1032 executed
1034 - this destroys much of the object's contents, including its
1035 slots and __dict__
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
1063 block.
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
1074 complexity?
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
1079 and bug 574207.
1083 static PyTypeObject *solid_base(PyTypeObject *type);
1085 /* type test with subclassing support */
1088 PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1090 PyObject *mro;
1092 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1093 return b == a || b == &PyBaseObject_Type;
1095 mro = a->tp_mro;
1096 if (mro != NULL) {
1097 /* Deal with multiple inheritance without recursion
1098 by walking the MRO tuple */
1099 Py_ssize_t i, n;
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)
1104 return 1;
1106 return 0;
1108 else {
1109 /* a is not completely initilized yet; follow tp_base */
1110 do {
1111 if (a == b)
1112 return 1;
1113 a = a->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.
1126 Two variants:
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.
1134 static PyObject *
1135 lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
1137 PyObject *res;
1139 if (*attrobj == NULL) {
1140 *attrobj = PyString_InternFromString(attrstr);
1141 if (*attrobj == NULL)
1142 return NULL;
1144 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1145 if (res != NULL) {
1146 descrgetfunc f;
1147 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1148 Py_INCREF(res);
1149 else
1150 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1152 return res;
1155 static PyObject *
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);
1161 return res;
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. */
1168 static PyObject *
1169 call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1171 va_list va;
1172 PyObject *args, *func = 0, *retval;
1173 va_start(va, format);
1175 func = lookup_maybe(o, name, nameobj);
1176 if (func == NULL) {
1177 va_end(va);
1178 if (!PyErr_Occurred())
1179 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1180 return NULL;
1183 if (format && *format)
1184 args = Py_VaBuildValue(format, va);
1185 else
1186 args = PyTuple_New(0);
1188 va_end(va);
1190 if (args == NULL)
1191 return NULL;
1193 assert(PyTuple_Check(args));
1194 retval = PyObject_Call(func, args, NULL);
1196 Py_DECREF(args);
1197 Py_DECREF(func);
1199 return retval;
1202 /* Clone of call_method() that returns NotImplemented when the lookup fails. */
1204 static PyObject *
1205 call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1207 va_list va;
1208 PyObject *args, *func = 0, *retval;
1209 va_start(va, format);
1211 func = lookup_maybe(o, name, nameobj);
1212 if (func == NULL) {
1213 va_end(va);
1214 if (!PyErr_Occurred()) {
1215 Py_INCREF(Py_NotImplemented);
1216 return Py_NotImplemented;
1218 return NULL;
1221 if (format && *format)
1222 args = Py_VaBuildValue(format, va);
1223 else
1224 args = PyTuple_New(0);
1226 va_end(va);
1228 if (args == NULL)
1229 return NULL;
1231 assert(PyTuple_Check(args));
1232 retval = PyObject_Call(func, args, NULL);
1234 Py_DECREF(args);
1235 Py_DECREF(func);
1237 return retval;
1240 static int
1241 fill_classic_mro(PyObject *mro, PyObject *cls)
1243 PyObject *bases, *base;
1244 Py_ssize_t i, n;
1246 assert(PyList_Check(mro));
1247 assert(PyClass_Check(cls));
1248 i = PySequence_Contains(mro, cls);
1249 if (i < 0)
1250 return -1;
1251 if (!i) {
1252 if (PyList_Append(mro, cls) < 0)
1253 return -1;
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)
1261 return -1;
1263 return 0;
1266 static PyObject *
1267 classic_mro(PyObject *cls)
1269 PyObject *mro;
1271 assert(PyClass_Check(cls));
1272 mro = PyList_New(0);
1273 if (mro != NULL) {
1274 if (fill_classic_mro(mro, cls) == 0)
1275 return mro;
1276 Py_DECREF(mro);
1278 return NULL;
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.
1286 (OOPSLA 1996)
1288 Some notes about the rules implied by C3:
1290 No duplicate bases.
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
1297 subclasses of C.
1299 Monotonicity.
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.
1309 static int
1310 tail_contains(PyObject *list, int whence, PyObject *o) {
1311 Py_ssize_t j, size;
1312 size = PyList_GET_SIZE(list);
1314 for (j = whence+1; j < size; j++) {
1315 if (PyList_GET_ITEM(list, j) == o)
1316 return 1;
1318 return 0;
1321 static PyObject *
1322 class_name(PyObject *cls)
1324 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1325 if (name == NULL) {
1326 PyErr_Clear();
1327 Py_XDECREF(name);
1328 name = PyObject_Repr(cls);
1330 if (name == NULL)
1331 return NULL;
1332 if (!PyString_Check(name)) {
1333 Py_DECREF(name);
1334 return NULL;
1336 return name;
1339 static int
1340 check_duplicates(PyObject *list)
1342 Py_ssize_t i, j, n;
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) {
1351 o = class_name(o);
1352 PyErr_Format(PyExc_TypeError,
1353 "duplicate base class %s",
1354 o ? PyString_AS_STRING(o) : "?");
1355 Py_XDECREF(o);
1356 return -1;
1360 return 0;
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.
1372 static void
1373 set_mro_error(PyObject *to_merge, int *remain)
1375 Py_ssize_t i, n, off, to_merge_size;
1376 char buf[1000];
1377 PyObject *k, *v;
1378 PyObject *set = PyDict_New();
1379 if (!set) return;
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) {
1387 Py_DECREF(set);
1388 return;
1392 n = PyDict_Size(set);
1394 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1395 consistent method resolution\norder (MRO) for bases");
1396 i = 0;
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) : "?");
1401 Py_XDECREF(name);
1402 if (--n && (size_t)(off+1) < sizeof(buf)) {
1403 buf[off++] = ',';
1404 buf[off] = '\0';
1407 PyErr_SetString(PyExc_TypeError, buf);
1408 Py_DECREF(set);
1411 static int
1412 pmerge(PyObject *acc, PyObject* to_merge) {
1413 Py_ssize_t i, j, to_merge_size, empty_cnt;
1414 int *remain;
1415 int ok;
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);
1424 if (remain == NULL)
1425 return -1;
1426 for (i = 0; i < to_merge_size; i++)
1427 remain[i] = 0;
1429 again:
1430 empty_cnt = 0;
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)) {
1437 empty_cnt++;
1438 continue;
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);
1456 if (ok < 0) {
1457 PyMem_Free(remain);
1458 return -1;
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) {
1464 remain[j]++;
1467 goto again;
1468 skip: ;
1471 if (empty_cnt == to_merge_size) {
1472 PyMem_FREE(remain);
1473 return 0;
1475 set_mro_error(to_merge, remain);
1476 PyMem_FREE(remain);
1477 return -1;
1480 static PyObject *
1481 mro_implementation(PyTypeObject *type)
1483 Py_ssize_t i, n;
1484 int ok;
1485 PyObject *bases, *result;
1486 PyObject *to_merge, *bases_aslist;
1488 if (type->tp_dict == NULL) {
1489 if (PyType_Ready(type) < 0)
1490 return NULL;
1493 /* Find a superclass linearization that honors the constraints
1494 of the explicit lists of bases and the constraints implied by
1495 each base class.
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)
1507 return 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);
1515 else
1516 parentMRO = classic_mro(base);
1517 if (parentMRO == NULL) {
1518 Py_DECREF(to_merge);
1519 return NULL;
1522 PyList_SET_ITEM(to_merge, i, parentMRO);
1525 bases_aslist = PySequence_List(bases);
1526 if (bases_aslist == NULL) {
1527 Py_DECREF(to_merge);
1528 return NULL;
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);
1534 return NULL;
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);
1541 return NULL;
1544 ok = pmerge(result, to_merge);
1545 Py_DECREF(to_merge);
1546 if (ok < 0) {
1547 Py_DECREF(result);
1548 return NULL;
1551 return result;
1554 static PyObject *
1555 mro_external(PyObject *self)
1557 PyTypeObject *type = (PyTypeObject *)self;
1559 return mro_implementation(type);
1562 static int
1563 mro_internal(PyTypeObject *type)
1565 PyObject *mro, *result, *tuple;
1566 int checkit = 0;
1568 if (Py_TYPE(type) == &PyType_Type) {
1569 result = mro_implementation(type);
1571 else {
1572 static PyObject *mro_str;
1573 checkit = 1;
1574 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1575 if (mro == NULL)
1576 return -1;
1577 result = PyObject_CallObject(mro, NULL);
1578 Py_DECREF(mro);
1580 if (result == NULL)
1581 return -1;
1582 tuple = PySequence_Tuple(result);
1583 Py_DECREF(result);
1584 if (tuple == NULL)
1585 return -1;
1586 if (checkit) {
1587 Py_ssize_t i, len;
1588 PyObject *cls;
1589 PyTypeObject *solid;
1591 solid = solid_base(type);
1593 len = PyTuple_GET_SIZE(tuple);
1595 for (i = 0; i < len; i++) {
1596 PyTypeObject *t;
1597 cls = PyTuple_GET_ITEM(tuple, i);
1598 if (PyClass_Check(cls))
1599 continue;
1600 else if (!PyType_Check(cls)) {
1601 PyErr_Format(PyExc_TypeError,
1602 "mro() returned a non-class ('%.500s')",
1603 Py_TYPE(cls)->tp_name);
1604 Py_DECREF(tuple);
1605 return -1;
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')",
1611 t->tp_name);
1612 Py_DECREF(tuple);
1613 return -1;
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);
1626 return 0;
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)
1636 Py_ssize_t i, n;
1637 PyTypeObject *base, *winner, *candidate, *base_i;
1638 PyObject *base_proto;
1640 assert(PyTuple_Check(bases));
1641 n = PyTuple_GET_SIZE(bases);
1642 assert(n > 0);
1643 base = NULL;
1644 winner = NULL;
1645 for (i = 0; i < n; i++) {
1646 base_proto = PyTuple_GET_ITEM(bases, i);
1647 if (PyClass_Check(base_proto))
1648 continue;
1649 if (!PyType_Check(base_proto)) {
1650 PyErr_SetString(
1651 PyExc_TypeError,
1652 "bases must be types");
1653 return NULL;
1655 base_i = (PyTypeObject *)base_proto;
1656 if (base_i->tp_dict == NULL) {
1657 if (PyType_Ready(base_i) < 0)
1658 return NULL;
1660 candidate = solid_base(base_i);
1661 if (winner == NULL) {
1662 winner = candidate;
1663 base = base_i;
1665 else if (PyType_IsSubtype(winner, candidate))
1667 else if (PyType_IsSubtype(candidate, winner)) {
1668 winner = candidate;
1669 base = base_i;
1671 else {
1672 PyErr_SetString(
1673 PyExc_TypeError,
1674 "multiple bases have "
1675 "instance lay-out conflict");
1676 return NULL;
1679 if (base == NULL)
1680 PyErr_SetString(PyExc_TypeError,
1681 "a new-style class can't have only classic bases");
1682 return base;
1685 static int
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)
1712 PyTypeObject *base;
1714 if (type->tp_base)
1715 base = solid_base(type->tp_base);
1716 else
1717 base = &PyBaseObject_Type;
1718 if (extra_ivars(type, base))
1719 return type;
1720 else
1721 return 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))
1740 return type;
1741 type = type->tp_base;
1743 return NULL;
1746 static PyObject *
1747 get_dict_descriptor(PyTypeObject *type)
1749 static PyObject *dict_str;
1750 PyObject *descr;
1752 if (dict_str == NULL) {
1753 dict_str = PyString_InternFromString("__dict__");
1754 if (dict_str == NULL)
1755 return NULL;
1757 descr = _PyType_Lookup(type, dict_str);
1758 if (descr == NULL || !PyDescr_IsData(descr))
1759 return NULL;
1761 return descr;
1764 static void
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);
1772 static PyObject *
1773 subtype_dict(PyObject *obj, void *context)
1775 PyObject **dictptr;
1776 PyObject *dict;
1777 PyTypeObject *base;
1779 base = get_builtin_base_with_dict(obj->ob_type);
1780 if (base != NULL) {
1781 descrgetfunc func;
1782 PyObject *descr = get_dict_descriptor(base);
1783 if (descr == NULL) {
1784 raise_dict_descr_error(obj);
1785 return NULL;
1787 func = descr->ob_type->tp_descr_get;
1788 if (func == NULL) {
1789 raise_dict_descr_error(obj);
1790 return NULL;
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__");
1799 return NULL;
1801 dict = *dictptr;
1802 if (dict == NULL)
1803 *dictptr = dict = PyDict_New();
1804 Py_XINCREF(dict);
1805 return dict;
1808 static int
1809 subtype_setdict(PyObject *obj, PyObject *value, void *context)
1811 PyObject **dictptr;
1812 PyObject *dict;
1813 PyTypeObject *base;
1815 base = get_builtin_base_with_dict(obj->ob_type);
1816 if (base != NULL) {
1817 descrsetfunc func;
1818 PyObject *descr = get_dict_descriptor(base);
1819 if (descr == NULL) {
1820 raise_dict_descr_error(obj);
1821 return -1;
1823 func = descr->ob_type->tp_descr_set;
1824 if (func == NULL) {
1825 raise_dict_descr_error(obj);
1826 return -1;
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__");
1835 return -1;
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);
1841 return -1;
1843 dict = *dictptr;
1844 Py_XINCREF(value);
1845 *dictptr = value;
1846 Py_XDECREF(dict);
1847 return 0;
1850 static PyObject *
1851 subtype_getweakref(PyObject *obj, void *context)
1853 PyObject **weaklistptr;
1854 PyObject *result;
1856 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1857 PyErr_SetString(PyExc_AttributeError,
1858 "This object has no __weakref__");
1859 return NULL;
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)
1867 result = Py_None;
1868 else
1869 result = *weaklistptr;
1870 Py_INCREF(result);
1871 return result;
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)")},
1896 static int
1897 valid_identifier(PyObject *s)
1899 unsigned char *p;
1900 Py_ssize_t i, n;
1902 if (!PyString_Check(s)) {
1903 PyErr_Format(PyExc_TypeError,
1904 "__slots__ items must be strings, not '%.200s'",
1905 Py_TYPE(s)->tp_name);
1906 return 0;
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. */
1912 if (n == 0)
1913 n = 1;
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");
1918 return 0;
1921 return 1;
1924 #ifdef Py_USING_UNICODE
1925 /* Replace Unicode objects in slots. */
1927 static PyObject *
1928 _unicode_to_string(PyObject *slots, Py_ssize_t nslots)
1930 PyObject *tmp = NULL;
1931 PyObject *slot_name, *new_name;
1932 Py_ssize_t i;
1934 for (i = 0; i < nslots; i++) {
1935 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1936 if (tmp == NULL) {
1937 tmp = PySequence_List(slots);
1938 if (tmp == NULL)
1939 return NULL;
1941 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1942 NULL);
1943 if (new_name == NULL) {
1944 Py_DECREF(tmp);
1945 return NULL;
1947 Py_INCREF(new_name);
1948 PyList_SET_ITEM(tmp, i, new_name);
1949 Py_DECREF(slot_name);
1952 if (tmp != NULL) {
1953 slots = PyList_AsTuple(tmp);
1954 Py_DECREF(tmp);
1956 return slots;
1958 #endif
1960 /* Forward */
1961 static int
1962 object_init(PyObject *self, PyObject *args, PyObject *kwds);
1964 static int
1965 type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1967 int res;
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");
1975 return -1;
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");
1982 return -1;
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);
1989 Py_DECREF(args);
1990 return res;
1993 static PyObject *
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;
2001 PyMemberDef *mp;
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");
2025 return NULL;
2029 /* Check arguments: (name, bases, dict) */
2030 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
2031 &name,
2032 &PyTuple_Type, &bases,
2033 &PyDict_Type, &dict))
2034 return NULL;
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);
2041 winner = metatype;
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))
2048 continue;
2049 if (PyType_IsSubtype(tmptype, winner)) {
2050 winner = tmptype;
2051 continue;
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");
2058 return NULL;
2060 if (winner != metatype) {
2061 if (winner->tp_new != type_new) /* Pass it to the winner */
2062 return winner->tp_new(winner, args, kwds);
2063 metatype = winner;
2066 /* Adjust for empty tuple bases */
2067 if (nbases == 0) {
2068 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2069 if (bases == NULL)
2070 return NULL;
2071 nbases = 1;
2073 else
2074 Py_INCREF(bases);
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);
2080 if (base == NULL) {
2081 Py_DECREF(bases);
2082 return NULL;
2084 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2085 PyErr_Format(PyExc_TypeError,
2086 "type '%.100s' is not an acceptable base type",
2087 base->tp_name);
2088 Py_DECREF(bases);
2089 return NULL;
2092 /* Check for a __slots__ sequence variable in dict, and count it */
2093 slots = PyDict_GetItemString(dict, "__slots__");
2094 nslots = 0;
2095 add_dict = 0;
2096 add_weak = 0;
2097 may_add_dict = base->tp_dictoffset == 0;
2098 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2099 if (slots == NULL) {
2100 if (may_add_dict) {
2101 add_dict++;
2103 if (may_add_weak) {
2104 add_weak++;
2107 else {
2108 /* Have slots */
2110 /* Make it into a tuple */
2111 if (PyString_Check(slots) || PyUnicode_Check(slots))
2112 slots = PyTuple_Pack(1, slots);
2113 else
2114 slots = PySequence_Tuple(slots);
2115 if (slots == NULL) {
2116 Py_DECREF(bases);
2117 return 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'",
2127 base->tp_name);
2128 bad_slots:
2129 Py_DECREF(bases);
2130 Py_DECREF(slots);
2131 return NULL;
2134 #ifdef Py_USING_UNICODE
2135 tmp = _unicode_to_string(slots, nslots);
2136 if (tmp == NULL)
2137 goto bad_slots;
2138 if (tmp != slots) {
2139 Py_DECREF(slots);
2140 slots = tmp;
2142 #endif
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);
2146 char *s;
2147 if (!valid_identifier(tmp))
2148 goto bad_slots;
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");
2156 goto bad_slots;
2158 add_dict++;
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");
2166 goto bad_slots;
2168 add_weak++;
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)
2178 goto bad_slots;
2179 for (i = j = 0; i < nslots; i++) {
2180 char *s;
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))
2185 continue;
2186 tmp =_Py_Mangle(name, tmp);
2187 if (!tmp)
2188 goto bad_slots;
2189 PyList_SET_ITEM(newslots, j, tmp);
2190 j++;
2192 assert(j == nslots - add_dict - add_weak);
2193 nslots = j;
2194 Py_DECREF(slots);
2195 if (PyList_Sort(newslots) == -1) {
2196 Py_DECREF(bases);
2197 Py_DECREF(newslots);
2198 return NULL;
2200 slots = PyList_AsTuple(newslots);
2201 Py_DECREF(newslots);
2202 if (slots == NULL) {
2203 Py_DECREF(bases);
2204 return NULL;
2207 /* Secondary bases may provide weakrefs or dict */
2208 if (nbases > 1 &&
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)
2218 add_dict++;
2219 if (may_add_weak && !add_weak)
2220 add_weak++;
2221 break;
2223 assert(PyType_Check(tmp));
2224 tmptype = (PyTypeObject *)tmp;
2225 if (may_add_dict && !add_dict &&
2226 tmptype->tp_dictoffset != 0)
2227 add_dict++;
2228 if (may_add_weak && !add_weak &&
2229 tmptype->tp_weaklistoffset != 0)
2230 add_weak++;
2231 if (may_add_dict && !add_dict)
2232 continue;
2233 if (may_add_weak && !add_weak)
2234 continue;
2235 /* Nothing more to check */
2236 break;
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);
2246 if (type == NULL) {
2247 Py_XDECREF(slots);
2248 Py_DECREF(bases);
2249 return NULL;
2252 /* Keep name and slots alive in the extended type object */
2253 et = (PyHeapTypeObject *)type;
2254 Py_INCREF(name);
2255 et->ht_name = name;
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;
2279 Py_INCREF(base);
2280 type->tp_base = base;
2282 /* Initialize tp_dict from passed-in dict */
2283 type->tp_dict = dict = PyDict_Copy(dict);
2284 if (dict == NULL) {
2285 Py_DECREF(type);
2286 return NULL;
2289 /* Set __module__ in the dict */
2290 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2291 tmp = PyEval_GetGlobals();
2292 if (tmp != NULL) {
2293 tmp = PyDict_GetItemString(tmp, "__name__");
2294 if (tmp != NULL) {
2295 if (PyDict_SetItemString(dict, "__module__",
2296 tmp) < 0)
2297 return NULL;
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) {
2312 Py_DECREF(type);
2313 return 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);
2325 if (tmp == NULL) {
2326 Py_DECREF(type);
2327 return NULL;
2329 PyDict_SetItemString(dict, "__new__", tmp);
2330 Py_DECREF(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 *);
2350 if (add_dict) {
2351 if (base->tp_itemsize)
2352 type->tp_dictoffset = -(long)sizeof(PyObject *);
2353 else
2354 type->tp_dictoffset = slotoffset;
2355 slotoffset += sizeof(PyObject *);
2357 if (add_weak) {
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;
2372 else
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;
2396 else
2397 type->tp_free = PyObject_Del;
2399 /* Initialize the rest */
2400 if (PyType_Ready(type) < 0) {
2401 Py_DECREF(type);
2402 return NULL;
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! */
2413 PyObject *
2414 _PyType_Lookup(PyTypeObject *type, PyObject *name)
2416 Py_ssize_t i, n;
2417 PyObject *mro, *res, *base, *dict;
2418 unsigned int h;
2420 if (MCACHE_CACHEABLE_NAME(name) &&
2421 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2422 /* fast path */
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 */
2430 mro = type->tp_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. */
2435 if (mro == NULL)
2436 return NULL;
2438 res = 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;
2445 else {
2446 assert(PyType_Check(base));
2447 dict = ((PyTypeObject *)base)->tp_dict;
2449 assert(dict && PyDict_Check(dict));
2450 res = PyDict_GetItem(dict, name);
2451 if (res != NULL)
2452 break;
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 */
2459 Py_INCREF(name);
2460 Py_DECREF(method_cache[h].name);
2461 method_cache[h].name = name;
2463 return res;
2466 /* This is similar to PyObject_GenericGetAttr(),
2467 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2468 static PyObject *
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)
2478 return NULL;
2481 /* No readable descriptor found yet */
2482 meta_get = NULL;
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,
2514 (PyObject *)type);
2517 Py_INCREF(attribute);
2518 return attribute;
2521 /* No attribute found in local __dict__ (or bases): use the
2522 * descriptor from the metatype, if any */
2523 if (meta_get != NULL) {
2524 PyObject *res;
2525 res = meta_get(meta_attribute, (PyObject *)type,
2526 (PyObject *)metatype);
2527 Py_DECREF(meta_attribute);
2528 return res;
2531 /* If an ordinary attribute was found on the metatype, return it now */
2532 if (meta_attribute != NULL) {
2533 return meta_attribute;
2536 /* Give up */
2537 PyErr_Format(PyExc_AttributeError,
2538 "type object '%.50s' has no attribute '%.400s'",
2539 type->tp_name, PyString_AS_STRING(name));
2540 return NULL;
2543 static int
2544 type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2546 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2547 PyErr_Format(
2548 PyExc_TypeError,
2549 "can't set attributes of built-in/extension type '%s'",
2550 type->tp_name);
2551 return -1;
2553 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2554 return -1;
2555 return update_slot(type, name);
2558 static void
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);
2583 static PyObject *
2584 type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2586 PyObject *list, *raw, *ref;
2587 Py_ssize_t i, n;
2589 list = PyList_New(0);
2590 if (list == NULL)
2591 return NULL;
2592 raw = type->tp_subclasses;
2593 if (raw == NULL)
2594 return list;
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) {
2603 Py_DECREF(list);
2604 return NULL;
2608 return list;
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");
2623 static int
2624 type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2626 /* Because of type_is_gc(), the collector only calls this
2627 for heaptypes. */
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. */
2641 return 0;
2644 static int
2645 type_clear(PyTypeObject *type)
2647 /* Because of type_is_gc(), the collector only calls this
2648 for heaptypes. */
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:
2657 tp_dict:
2658 It is a dict, so the collector will call its tp_clear.
2660 tp_cache:
2661 Not used; if it were, it would be a dict.
2663 tp_bases, tp_base:
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.
2668 tp_subclasses:
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);
2678 return 0;
2681 static int
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 */
2693 0, /* tp_print */
2694 0, /* tp_getattr */
2695 0, /* tp_setattr */
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 */
2703 0, /* tp_str */
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 */
2714 0, /* tp_iter */
2715 0, /* tp_iternext */
2716 type_methods, /* tp_methods */
2717 type_members, /* tp_members */
2718 type_getsets, /* tp_getset */
2719 0, /* tp_base */
2720 0, /* tp_dict */
2721 0, /* tp_descr_get */
2722 0, /* tp_descr_set */
2723 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2724 type_init, /* tp_init */
2725 0, /* tp_alloc */
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
2752 complaining.
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
2770 rules.
2774 /* Forward */
2775 static PyObject *
2776 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2778 static int
2779 excess_args(PyObject *args, PyObject *kwds)
2781 return PyTuple_GET_SIZE(args) ||
2782 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2785 static int
2786 object_init(PyObject *self, PyObject *args, PyObject *kwds)
2788 int err = 0;
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");
2803 err = -1;
2806 return err;
2809 static PyObject *
2810 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2812 int err = 0;
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");
2826 err = -1;
2829 if (err < 0)
2830 return NULL;
2832 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2833 static PyObject *comma = NULL;
2834 PyObject *abstract_methods = NULL;
2835 PyObject *builtins;
2836 PyObject *sorted;
2837 PyObject *sorted_methods = NULL;
2838 PyObject *joined = NULL;
2839 const char *joined_str;
2841 /* Compute ", ".join(sorted(type.__abstractmethods__))
2842 into joined. */
2843 abstract_methods = type_abstractmethods(type, NULL);
2844 if (abstract_methods == NULL)
2845 goto error;
2846 builtins = PyEval_GetBuiltins();
2847 if (builtins == NULL)
2848 goto error;
2849 sorted = PyDict_GetItemString(builtins, "sorted");
2850 if (sorted == NULL)
2851 goto error;
2852 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2853 abstract_methods,
2854 NULL);
2855 if (sorted_methods == NULL)
2856 goto error;
2857 if (comma == NULL) {
2858 comma = PyString_InternFromString(", ");
2859 if (comma == NULL)
2860 goto error;
2862 joined = PyObject_CallMethod(comma, "join",
2863 "O", sorted_methods);
2864 if (joined == NULL)
2865 goto error;
2866 joined_str = PyString_AsString(joined);
2867 if (joined_str == NULL)
2868 goto error;
2870 PyErr_Format(PyExc_TypeError,
2871 "Can't instantiate abstract class %s "
2872 "with abstract methods %s",
2873 type->tp_name,
2874 joined_str);
2875 error:
2876 Py_XDECREF(joined);
2877 Py_XDECREF(sorted_methods);
2878 Py_XDECREF(abstract_methods);
2879 return NULL;
2881 return type->tp_alloc(type, 0);
2884 static void
2885 object_dealloc(PyObject *self)
2887 Py_TYPE(self)->tp_free(self);
2890 static PyObject *
2891 object_repr(PyObject *self)
2893 PyTypeObject *type;
2894 PyObject *mod, *name, *rtn;
2896 type = Py_TYPE(self);
2897 mod = type_module(type, NULL);
2898 if (mod == NULL)
2899 PyErr_Clear();
2900 else if (!PyString_Check(mod)) {
2901 Py_DECREF(mod);
2902 mod = NULL;
2904 name = type_name(type, NULL);
2905 if (name == NULL)
2906 return 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),
2911 self);
2912 else
2913 rtn = PyString_FromFormat("<%s object at %p>",
2914 type->tp_name, self);
2915 Py_XDECREF(mod);
2916 Py_DECREF(name);
2917 return rtn;
2920 static PyObject *
2921 object_str(PyObject *self)
2923 unaryfunc f;
2925 f = Py_TYPE(self)->tp_repr;
2926 if (f == NULL)
2927 f = object_repr;
2928 return f(self);
2931 static PyObject *
2932 object_get_class(PyObject *self, void *closure)
2934 Py_INCREF(Py_TYPE(self));
2935 return (PyObject *)(Py_TYPE(self));
2938 static int
2939 equiv_structs(PyTypeObject *a, PyTypeObject *b)
2941 return a == b ||
2942 (a != NULL &&
2943 b != NULL &&
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)));
2952 static int
2953 same_slots_added(PyTypeObject *a, PyTypeObject *b)
2955 PyTypeObject *base = a->tp_base;
2956 Py_ssize_t size;
2957 PyObject *slots_a, *slots_b;
2959 if (base != b->tp_base)
2960 return 0;
2961 if (equiv_structs(a, base) && equiv_structs(b, base))
2962 return 1;
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)
2974 return 0;
2975 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2977 return size == a->tp_basicsize && size == b->tp_basicsize;
2980 static int
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,
2989 "%s assignment: "
2990 "'%s' deallocator differs from '%s'",
2991 attr,
2992 newto->tp_name,
2993 oldto->tp_name);
2994 return 0;
2996 newbase = newto;
2997 oldbase = oldto;
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,
3006 "%s assignment: "
3007 "'%s' object layout differs from '%s'",
3008 attr,
3009 newto->tp_name,
3010 oldto->tp_name);
3011 return 0;
3014 return 1;
3017 static int
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");
3026 return -1;
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);
3032 return -1;
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");
3040 return -1;
3042 if (compatible_for_assignment(newto, oldto, "__class__")) {
3043 Py_INCREF(newto);
3044 Py_TYPE(self) = newto;
3045 Py_DECREF(oldto);
3046 return 0;
3048 else {
3049 return -1;
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)
3067 static PyObject *
3068 import_copyreg(void)
3070 static PyObject *copyreg_str;
3072 if (!copyreg_str) {
3073 copyreg_str = PyString_InternFromString("copyreg");
3074 if (copyreg_str == NULL)
3075 return NULL;
3078 return PyImport_Import(copyreg_str);
3081 static PyObject *
3082 slotnames(PyObject *cls)
3084 PyObject *clsdict;
3085 PyObject *copyreg;
3086 PyObject *slotnames;
3088 if (!PyType_Check(cls)) {
3089 Py_INCREF(Py_None);
3090 return Py_None;
3093 clsdict = ((PyTypeObject *)cls)->tp_dict;
3094 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
3095 if (slotnames != NULL && PyList_Check(slotnames)) {
3096 Py_INCREF(slotnames);
3097 return slotnames;
3100 copyreg = import_copyreg();
3101 if (copyreg == NULL)
3102 return NULL;
3104 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3105 Py_DECREF(copyreg);
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);
3113 slotnames = NULL;
3116 return slotnames;
3119 static PyObject *
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;
3127 Py_ssize_t i, n;
3129 cls = PyObject_GetAttrString(obj, "__class__");
3130 if (cls == NULL)
3131 return NULL;
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);
3141 goto end;
3144 else {
3145 PyErr_Clear();
3146 args = PyTuple_New(0);
3148 if (args == NULL)
3149 goto end;
3151 getstate = PyObject_GetAttrString(obj, "__getstate__");
3152 if (getstate != NULL) {
3153 state = PyObject_CallObject(getstate, NULL);
3154 Py_DECREF(getstate);
3155 if (state == NULL)
3156 goto end;
3158 else {
3159 PyErr_Clear();
3160 state = PyObject_GetAttrString(obj, "__dict__");
3161 if (state == NULL) {
3162 PyErr_Clear();
3163 state = Py_None;
3164 Py_INCREF(state);
3166 names = slotnames(cls);
3167 if (names == NULL)
3168 goto end;
3169 if (names != Py_None) {
3170 assert(PyList_Check(names));
3171 slots = PyDict_New();
3172 if (slots == NULL)
3173 goto end;
3174 n = 0;
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);
3182 if (value == NULL)
3183 PyErr_Clear();
3184 else {
3185 int err = PyDict_SetItem(slots, name,
3186 value);
3187 Py_DECREF(value);
3188 if (err)
3189 goto end;
3190 n++;
3193 if (n) {
3194 state = Py_BuildValue("(NO)", state, slots);
3195 if (state == NULL)
3196 goto end;
3201 if (!PyList_Check(obj)) {
3202 listitems = Py_None;
3203 Py_INCREF(listitems);
3205 else {
3206 listitems = PyObject_GetIter(obj);
3207 if (listitems == NULL)
3208 goto end;
3211 if (!PyDict_Check(obj)) {
3212 dictitems = Py_None;
3213 Py_INCREF(dictitems);
3215 else {
3216 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3217 if (dictitems == NULL)
3218 goto end;
3221 copyreg = import_copyreg();
3222 if (copyreg == NULL)
3223 goto end;
3224 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
3225 if (newobj == NULL)
3226 goto end;
3228 n = PyTuple_GET_SIZE(args);
3229 args2 = PyTuple_New(n+1);
3230 if (args2 == NULL)
3231 goto end;
3232 PyTuple_SET_ITEM(args2, 0, cls);
3233 cls = NULL;
3234 for (i = 0; i < n; i++) {
3235 PyObject *v = PyTuple_GET_ITEM(args, i);
3236 Py_INCREF(v);
3237 PyTuple_SET_ITEM(args2, i+1, v);
3240 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
3242 end:
3243 Py_XDECREF(cls);
3244 Py_XDECREF(args);
3245 Py_XDECREF(args2);
3246 Py_XDECREF(slots);
3247 Py_XDECREF(state);
3248 Py_XDECREF(names);
3249 Py_XDECREF(listitems);
3250 Py_XDECREF(dictitems);
3251 Py_XDECREF(copyreg);
3252 Py_XDECREF(newobj);
3253 return res;
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
3269 * function.
3271 static PyObject *
3272 _common_reduce(PyObject *self, int proto)
3274 PyObject *copyreg, *res;
3276 if (proto >= 2)
3277 return reduce_2(self);
3279 copyreg = import_copyreg();
3280 if (!copyreg)
3281 return NULL;
3283 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3284 Py_DECREF(copyreg);
3286 return res;
3289 static PyObject *
3290 object_reduce(PyObject *self, PyObject *args)
3292 int proto = 0;
3294 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3295 return NULL;
3297 return _common_reduce(self, proto);
3300 static PyObject *
3301 object_reduce_ex(PyObject *self, PyObject *args)
3303 PyObject *reduce, *res;
3304 int proto = 0;
3306 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3307 return NULL;
3309 reduce = PyObject_GetAttrString(self, "__reduce__");
3310 if (reduce == NULL)
3311 PyErr_Clear();
3312 else {
3313 PyObject *cls, *clsreduce, *objreduce;
3314 int override;
3315 cls = PyObject_GetAttrString(self, "__class__");
3316 if (cls == NULL) {
3317 Py_DECREF(reduce);
3318 return NULL;
3320 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3321 Py_DECREF(cls);
3322 if (clsreduce == NULL) {
3323 Py_DECREF(reduce);
3324 return NULL;
3326 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3327 "__reduce__");
3328 override = (clsreduce != objreduce);
3329 Py_DECREF(clsreduce);
3330 if (override) {
3331 res = PyObject_CallObject(reduce, NULL);
3332 Py_DECREF(reduce);
3333 return res;
3335 else
3336 Py_DECREF(reduce);
3339 return _common_reduce(self, proto);
3342 static PyObject *
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"
3351 "\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:
3360 class object:
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)
3367 static PyObject *
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))
3376 return NULL;
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);
3381 } else {
3382 PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
3383 return NULL;
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) {
3390 /* and call it */
3391 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3395 Py_XDECREF(self_as_str);
3396 Py_XDECREF(format_meth);
3398 return result;
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 */
3420 0, /* tp_print */
3421 0, /* tp_getattr */
3422 0, /* tp_setattr */
3423 0, /* tp_compare */
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 */
3429 0, /* tp_call */
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 */
3437 0, /* tp_clear */
3438 0, /* tp_richcompare */
3439 0, /* tp_weaklistoffset */
3440 0, /* tp_iter */
3441 0, /* tp_iternext */
3442 object_methods, /* tp_methods */
3443 0, /* tp_members */
3444 object_getsets, /* tp_getset */
3445 0, /* tp_base */
3446 0, /* tp_dict */
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 */
3459 static int
3460 add_methods(PyTypeObject *type, PyMethodDef *meth)
3462 PyObject *dict = type->tp_dict;
3464 for (; meth->ml_name != NULL; meth++) {
3465 PyObject *descr;
3466 if (PyDict_GetItemString(dict, meth->ml_name) &&
3467 !(meth->ml_flags & METH_COEXIST))
3468 continue;
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");
3473 return -1;
3475 descr = PyDescr_NewClassMethod(type, meth);
3477 else if (meth->ml_flags & METH_STATIC) {
3478 PyObject *cfunc = PyCFunction_New(meth, NULL);
3479 if (cfunc == NULL)
3480 return -1;
3481 descr = PyStaticMethod_New(cfunc);
3482 Py_DECREF(cfunc);
3484 else {
3485 descr = PyDescr_NewMethod(type, meth);
3487 if (descr == NULL)
3488 return -1;
3489 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3490 return -1;
3491 Py_DECREF(descr);
3493 return 0;
3496 static int
3497 add_members(PyTypeObject *type, PyMemberDef *memb)
3499 PyObject *dict = type->tp_dict;
3501 for (; memb->name != NULL; memb++) {
3502 PyObject *descr;
3503 if (PyDict_GetItemString(dict, memb->name))
3504 continue;
3505 descr = PyDescr_NewMember(type, memb);
3506 if (descr == NULL)
3507 return -1;
3508 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3509 return -1;
3510 Py_DECREF(descr);
3512 return 0;
3515 static int
3516 add_getset(PyTypeObject *type, PyGetSetDef *gsp)
3518 PyObject *dict = type->tp_dict;
3520 for (; gsp->name != NULL; gsp++) {
3521 PyObject *descr;
3522 if (PyDict_GetItemString(dict, gsp->name))
3523 continue;
3524 descr = PyDescr_NewGetSet(type, gsp);
3526 if (descr == NULL)
3527 return -1;
3528 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3529 return -1;
3530 Py_DECREF(descr);
3532 return 0;
3535 static void
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;
3543 type->tp_flags |=
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;
3560 /* Wow */
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 */
3601 #undef COPYVAL
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;
3627 #endif
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[] = {
3637 "__eq__",
3638 "__cmp__",
3639 "__hash__",
3640 NULL
3643 static int
3644 overrides_hash(PyTypeObject *type)
3646 char **p;
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)
3652 return 1;
3654 return 0;
3657 static void
3658 inherit_slots(PyTypeObject *type, PyTypeObject *base)
3660 PyTypeObject *basebase;
3662 #undef SLOTDEFINED
3663 #undef COPYSLOT
3664 #undef COPYNUM
3665 #undef COPYSEQ
3666 #undef COPYMAP
3667 #undef COPYBUF
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)
3687 basebase = NULL;
3688 COPYNUM(nb_add);
3689 COPYNUM(nb_subtract);
3690 COPYNUM(nb_multiply);
3691 COPYNUM(nb_divide);
3692 COPYNUM(nb_remainder);
3693 COPYNUM(nb_divmod);
3694 COPYNUM(nb_power);
3695 COPYNUM(nb_negative);
3696 COPYNUM(nb_positive);
3697 COPYNUM(nb_absolute);
3698 COPYNUM(nb_nonzero);
3699 COPYNUM(nb_invert);
3700 COPYNUM(nb_lshift);
3701 COPYNUM(nb_rshift);
3702 COPYNUM(nb_and);
3703 COPYNUM(nb_xor);
3704 COPYNUM(nb_or);
3705 COPYNUM(nb_coerce);
3706 COPYNUM(nb_int);
3707 COPYNUM(nb_long);
3708 COPYNUM(nb_float);
3709 COPYNUM(nb_oct);
3710 COPYNUM(nb_hex);
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) {
3729 COPYNUM(nb_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)
3736 basebase = NULL;
3737 COPYSEQ(sq_length);
3738 COPYSEQ(sq_concat);
3739 COPYSEQ(sq_repeat);
3740 COPYSEQ(sq_item);
3741 COPYSEQ(sq_slice);
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)
3752 basebase = NULL;
3753 COPYMAP(mp_length);
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)
3761 basebase = 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);
3773 COPYSLOT(tp_print);
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 */
3783 COPYSLOT(tp_repr);
3784 /* tp_hash see tp_richcompare */
3785 COPYSLOT(tp_call);
3786 COPYSLOT(tp_str);
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;
3798 else {
3799 COPYSLOT(tp_compare);
3801 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3802 COPYSLOT(tp_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);
3809 COPYSLOT(tp_init);
3810 COPYSLOT(tp_alloc);
3811 COPYSLOT(tp_is_gc);
3812 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3813 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3814 /* They agree about gc. */
3815 COPYSLOT(tp_free);
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;
3839 PyTypeObject *base;
3840 Py_ssize_t i, n;
3842 if (type->tp_flags & Py_TPFLAGS_READY) {
3843 assert(type->tp_dict != NULL);
3844 return 0;
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);
3857 #endif
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;
3863 Py_INCREF(base);
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)
3873 goto error;
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
3882 know that. */
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) {
3889 if (base == NULL)
3890 bases = PyTuple_New(0);
3891 else
3892 bases = PyTuple_Pack(1, base);
3893 if (bases == NULL)
3894 goto error;
3895 type->tp_bases = bases;
3898 /* Initialize tp_dict */
3899 dict = type->tp_dict;
3900 if (dict == NULL) {
3901 dict = PyDict_New();
3902 if (dict == NULL)
3903 goto error;
3904 type->tp_dict = dict;
3907 /* Add type-specific descriptors to tp_dict */
3908 if (add_operators(type) < 0)
3909 goto error;
3910 if (type->tp_methods != NULL) {
3911 if (add_methods(type, type->tp_methods) < 0)
3912 goto error;
3914 if (type->tp_members != NULL) {
3915 if (add_members(type, type->tp_members) < 0)
3916 goto error;
3918 if (type->tp_getset != NULL) {
3919 if (add_getset(type, type->tp_getset) < 0)
3920 goto error;
3923 /* Calculate method resolution order */
3924 if (mro_internal(type) < 0) {
3925 goto error;
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 "
3951 "tp_free slot",
3952 type->tp_name);
3953 goto error;
3956 /* if the type dictionary doesn't contain a __doc__, set it from
3957 the tp_doc slot.
3959 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3960 if (type->tp_doc != NULL) {
3961 PyObject *doc = PyString_FromString(type->tp_doc);
3962 if (doc == NULL)
3963 goto error;
3964 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3965 Py_DECREF(doc);
3966 } else {
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)
3981 goto error;
3984 /* Some more special stuff */
3985 base = type->tp_base;
3986 if (base != NULL) {
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)
4004 goto error;
4007 /* All done -- set the ready flag */
4008 assert(type->tp_dict != NULL);
4009 type->tp_flags =
4010 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4011 return 0;
4013 error:
4014 type->tp_flags &= ~Py_TPFLAGS_READYING;
4015 return -1;
4018 static int
4019 add_subclass(PyTypeObject *base, PyTypeObject *type)
4021 Py_ssize_t i;
4022 int result;
4023 PyObject *list, *ref, *newobj;
4025 list = base->tp_subclasses;
4026 if (list == NULL) {
4027 base->tp_subclasses = list = PyList_New(0);
4028 if (list == NULL)
4029 return -1;
4031 assert(PyList_Check(list));
4032 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4033 i = PyList_GET_SIZE(list);
4034 while (--i >= 0) {
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);
4041 Py_DECREF(newobj);
4042 return result;
4045 static void
4046 remove_subclass(PyTypeObject *base, PyTypeObject *type)
4048 Py_ssize_t i;
4049 PyObject *list, *ref;
4051 list = base->tp_subclasses;
4052 if (list == NULL) {
4053 return;
4055 assert(PyList_Check(list));
4056 i = PyList_GET_SIZE(list);
4057 while (--i >= 0) {
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);
4063 return;
4068 static int
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");
4074 return 0;
4076 if (n == PyTuple_GET_SIZE(ob))
4077 return 1;
4078 PyErr_Format(
4079 PyExc_TypeError,
4080 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4081 return 0;
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. */
4092 static PyObject *
4093 wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
4095 lenfunc func = (lenfunc)wrapped;
4096 Py_ssize_t res;
4098 if (!check_num_args(args, 0))
4099 return NULL;
4100 res = (*func)(self);
4101 if (res == -1 && PyErr_Occurred())
4102 return NULL;
4103 return PyInt_FromLong((long)res);
4106 static PyObject *
4107 wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4109 inquiry func = (inquiry)wrapped;
4110 int res;
4112 if (!check_num_args(args, 0))
4113 return NULL;
4114 res = (*func)(self);
4115 if (res == -1 && PyErr_Occurred())
4116 return NULL;
4117 return PyBool_FromLong((long)res);
4120 static PyObject *
4121 wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4123 binaryfunc func = (binaryfunc)wrapped;
4124 PyObject *other;
4126 if (!check_num_args(args, 1))
4127 return NULL;
4128 other = PyTuple_GET_ITEM(args, 0);
4129 return (*func)(self, other);
4132 static PyObject *
4133 wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4135 binaryfunc func = (binaryfunc)wrapped;
4136 PyObject *other;
4138 if (!check_num_args(args, 1))
4139 return NULL;
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);
4149 static PyObject *
4150 wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4152 binaryfunc func = (binaryfunc)wrapped;
4153 PyObject *other;
4155 if (!check_num_args(args, 1))
4156 return NULL;
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);
4166 static PyObject *
4167 wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4169 coercion func = (coercion)wrapped;
4170 PyObject *other, *res;
4171 int ok;
4173 if (!check_num_args(args, 1))
4174 return NULL;
4175 other = PyTuple_GET_ITEM(args, 0);
4176 ok = func(&self, &other);
4177 if (ok < 0)
4178 return NULL;
4179 if (ok > 0) {
4180 Py_INCREF(Py_NotImplemented);
4181 return Py_NotImplemented;
4183 res = PyTuple_New(2);
4184 if (res == NULL) {
4185 Py_DECREF(self);
4186 Py_DECREF(other);
4187 return NULL;
4189 PyTuple_SET_ITEM(res, 0, self);
4190 PyTuple_SET_ITEM(res, 1, other);
4191 return res;
4194 static PyObject *
4195 wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4197 ternaryfunc func = (ternaryfunc)wrapped;
4198 PyObject *other;
4199 PyObject *third = Py_None;
4201 /* Note: This wrapper only works for __pow__() */
4203 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4204 return NULL;
4205 return (*func)(self, other, third);
4208 static PyObject *
4209 wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4211 ternaryfunc func = (ternaryfunc)wrapped;
4212 PyObject *other;
4213 PyObject *third = Py_None;
4215 /* Note: This wrapper only works for __pow__() */
4217 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4218 return NULL;
4219 return (*func)(other, self, third);
4222 static PyObject *
4223 wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4225 unaryfunc func = (unaryfunc)wrapped;
4227 if (!check_num_args(args, 0))
4228 return NULL;
4229 return (*func)(self);
4232 static PyObject *
4233 wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
4235 ssizeargfunc func = (ssizeargfunc)wrapped;
4236 PyObject* o;
4237 Py_ssize_t i;
4239 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4240 return NULL;
4241 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4242 if (i == -1 && PyErr_Occurred())
4243 return NULL;
4244 return (*func)(self, i);
4247 static Py_ssize_t
4248 getindex(PyObject *self, PyObject *arg)
4250 Py_ssize_t i;
4252 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4253 if (i == -1 && PyErr_Occurred())
4254 return -1;
4255 if (i < 0) {
4256 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4257 if (sq && sq->sq_length) {
4258 Py_ssize_t n = (*sq->sq_length)(self);
4259 if (n < 0)
4260 return -1;
4261 i += n;
4264 return i;
4267 static PyObject *
4268 wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4270 ssizeargfunc func = (ssizeargfunc)wrapped;
4271 PyObject *arg;
4272 Py_ssize_t i;
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())
4278 return NULL;
4279 return (*func)(self, i);
4281 check_num_args(args, 1);
4282 assert(PyErr_Occurred());
4283 return NULL;
4286 static PyObject *
4287 wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
4289 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4290 Py_ssize_t i, j;
4292 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4293 return NULL;
4294 return (*func)(self, i, j);
4297 static PyObject *
4298 wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
4300 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4301 Py_ssize_t i;
4302 int res;
4303 PyObject *arg, *value;
4305 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4306 return NULL;
4307 i = getindex(self, arg);
4308 if (i == -1 && PyErr_Occurred())
4309 return NULL;
4310 res = (*func)(self, i, value);
4311 if (res == -1 && PyErr_Occurred())
4312 return NULL;
4313 Py_INCREF(Py_None);
4314 return Py_None;
4317 static PyObject *
4318 wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
4320 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4321 Py_ssize_t i;
4322 int res;
4323 PyObject *arg;
4325 if (!check_num_args(args, 1))
4326 return NULL;
4327 arg = PyTuple_GET_ITEM(args, 0);
4328 i = getindex(self, arg);
4329 if (i == -1 && PyErr_Occurred())
4330 return NULL;
4331 res = (*func)(self, i, NULL);
4332 if (res == -1 && PyErr_Occurred())
4333 return NULL;
4334 Py_INCREF(Py_None);
4335 return Py_None;
4338 static PyObject *
4339 wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
4341 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4342 Py_ssize_t i, j;
4343 int res;
4344 PyObject *value;
4346 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
4347 return NULL;
4348 res = (*func)(self, i, j, value);
4349 if (res == -1 && PyErr_Occurred())
4350 return NULL;
4351 Py_INCREF(Py_None);
4352 return Py_None;
4355 static PyObject *
4356 wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4358 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4359 Py_ssize_t i, j;
4360 int res;
4362 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4363 return NULL;
4364 res = (*func)(self, i, j, NULL);
4365 if (res == -1 && PyErr_Occurred())
4366 return NULL;
4367 Py_INCREF(Py_None);
4368 return Py_None;
4371 /* XXX objobjproc is a misnomer; should be objargpred */
4372 static PyObject *
4373 wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4375 objobjproc func = (objobjproc)wrapped;
4376 int res;
4377 PyObject *value;
4379 if (!check_num_args(args, 1))
4380 return NULL;
4381 value = PyTuple_GET_ITEM(args, 0);
4382 res = (*func)(self, value);
4383 if (res == -1 && PyErr_Occurred())
4384 return NULL;
4385 else
4386 return PyBool_FromLong(res);
4389 static PyObject *
4390 wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4392 objobjargproc func = (objobjargproc)wrapped;
4393 int res;
4394 PyObject *key, *value;
4396 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4397 return NULL;
4398 res = (*func)(self, key, value);
4399 if (res == -1 && PyErr_Occurred())
4400 return NULL;
4401 Py_INCREF(Py_None);
4402 return Py_None;
4405 static PyObject *
4406 wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4408 objobjargproc func = (objobjargproc)wrapped;
4409 int res;
4410 PyObject *key;
4412 if (!check_num_args(args, 1))
4413 return NULL;
4414 key = PyTuple_GET_ITEM(args, 0);
4415 res = (*func)(self, key, NULL);
4416 if (res == -1 && PyErr_Occurred())
4417 return NULL;
4418 Py_INCREF(Py_None);
4419 return Py_None;
4422 static PyObject *
4423 wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4425 cmpfunc func = (cmpfunc)wrapped;
4426 int res;
4427 PyObject *other;
4429 if (!check_num_args(args, 1))
4430 return NULL;
4431 other = PyTuple_GET_ITEM(args, 0);
4432 if (Py_TYPE(other)->tp_compare != func &&
4433 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
4434 PyErr_Format(
4435 PyExc_TypeError,
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);
4440 return NULL;
4442 res = (*func)(self, other);
4443 if (PyErr_Occurred())
4444 return NULL;
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. */
4450 static int
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",
4461 what,
4462 type->tp_name);
4463 return 0;
4465 return 1;
4468 static PyObject *
4469 wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4471 setattrofunc func = (setattrofunc)wrapped;
4472 int res;
4473 PyObject *name, *value;
4475 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4476 return NULL;
4477 if (!hackcheck(self, func, "__setattr__"))
4478 return NULL;
4479 res = (*func)(self, name, value);
4480 if (res < 0)
4481 return NULL;
4482 Py_INCREF(Py_None);
4483 return Py_None;
4486 static PyObject *
4487 wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4489 setattrofunc func = (setattrofunc)wrapped;
4490 int res;
4491 PyObject *name;
4493 if (!check_num_args(args, 1))
4494 return NULL;
4495 name = PyTuple_GET_ITEM(args, 0);
4496 if (!hackcheck(self, func, "__delattr__"))
4497 return NULL;
4498 res = (*func)(self, name, NULL);
4499 if (res < 0)
4500 return NULL;
4501 Py_INCREF(Py_None);
4502 return Py_None;
4505 static PyObject *
4506 wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4508 hashfunc func = (hashfunc)wrapped;
4509 long res;
4511 if (!check_num_args(args, 0))
4512 return NULL;
4513 res = (*func)(self);
4514 if (res == -1 && PyErr_Occurred())
4515 return NULL;
4516 return PyInt_FromLong(res);
4519 static PyObject *
4520 wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
4522 ternaryfunc func = (ternaryfunc)wrapped;
4524 return (*func)(self, args, kwds);
4527 static PyObject *
4528 wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4530 richcmpfunc func = (richcmpfunc)wrapped;
4531 PyObject *other;
4533 if (!check_num_args(args, 1))
4534 return NULL;
4535 other = PyTuple_GET_ITEM(args, 0);
4536 return (*func)(self, other, op);
4539 #undef RICHCMP_WRAPPER
4540 #define RICHCMP_WRAPPER(NAME, OP) \
4541 static PyObject * \
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)
4554 static PyObject *
4555 wrap_next(PyObject *self, PyObject *args, void *wrapped)
4557 unaryfunc func = (unaryfunc)wrapped;
4558 PyObject *res;
4560 if (!check_num_args(args, 0))
4561 return NULL;
4562 res = (*func)(self);
4563 if (res == NULL && !PyErr_Occurred())
4564 PyErr_SetNone(PyExc_StopIteration);
4565 return res;
4568 static PyObject *
4569 wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4571 descrgetfunc func = (descrgetfunc)wrapped;
4572 PyObject *obj;
4573 PyObject *type = NULL;
4575 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4576 return NULL;
4577 if (obj == Py_None)
4578 obj = NULL;
4579 if (type == Py_None)
4580 type = NULL;
4581 if (type == NULL &&obj == NULL) {
4582 PyErr_SetString(PyExc_TypeError,
4583 "__get__(None, None) is invalid");
4584 return NULL;
4586 return (*func)(self, obj, type);
4589 static PyObject *
4590 wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
4592 descrsetfunc func = (descrsetfunc)wrapped;
4593 PyObject *obj, *value;
4594 int ret;
4596 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4597 return NULL;
4598 ret = (*func)(self, obj, value);
4599 if (ret < 0)
4600 return NULL;
4601 Py_INCREF(Py_None);
4602 return Py_None;
4605 static PyObject *
4606 wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4608 descrsetfunc func = (descrsetfunc)wrapped;
4609 PyObject *obj;
4610 int ret;
4612 if (!check_num_args(args, 1))
4613 return NULL;
4614 obj = PyTuple_GET_ITEM(args, 0);
4615 ret = (*func)(self, obj, NULL);
4616 if (ret < 0)
4617 return NULL;
4618 Py_INCREF(Py_None);
4619 return Py_None;
4622 static PyObject *
4623 wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
4625 initproc func = (initproc)wrapped;
4627 if (func(self, args, kwds) < 0)
4628 return NULL;
4629 Py_INCREF(Py_None);
4630 return Py_None;
4633 static PyObject *
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",
4645 type->tp_name);
4646 return NULL;
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)",
4652 type->tp_name,
4653 Py_TYPE(arg0)->tp_name);
4654 return NULL;
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",
4660 type->tp_name,
4661 subtype->tp_name,
4662 subtype->tp_name,
4663 type->tp_name);
4664 return NULL;
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__()",
4678 type->tp_name,
4679 subtype->tp_name,
4680 staticbase == NULL ? "?" : staticbase->tp_name);
4681 return NULL;
4684 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4685 if (args == NULL)
4686 return NULL;
4687 res = type->tp_new(subtype, args, kwds);
4688 Py_DECREF(args);
4689 return res;
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")},
4699 static int
4700 add_tp_new_wrapper(PyTypeObject *type)
4702 PyObject *func;
4704 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4705 return 0;
4706 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4707 if (func == NULL)
4708 return -1;
4709 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4710 Py_DECREF(func);
4711 return -1;
4713 Py_DECREF(func);
4714 return 0;
4717 /* Slot wrappers that call the corresponding __foo__ slot. See comments
4718 below at override_slots() for more explanation. */
4720 #define SLOT0(FUNCNAME, OPSTR) \
4721 static PyObject * \
4722 FUNCNAME(PyObject *self) \
4724 static PyObject *cache_str; \
4725 return call_method(self, OPSTR, &cache_str, "()"); \
4728 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
4729 static PyObject * \
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__. */
4738 static int
4739 method_is_overloaded(PyObject *left, PyObject *right, char *name)
4741 PyObject *a, *b;
4742 int ok;
4744 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4745 if (b == NULL) {
4746 PyErr_Clear();
4747 /* If right doesn't have it, it's not overloaded */
4748 return 0;
4751 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4752 if (a == NULL) {
4753 PyErr_Clear();
4754 Py_DECREF(b);
4755 /* If right has it but left doesn't, it's overloaded */
4756 return 1;
4759 ok = PyObject_RichCompareBool(a, b, Py_NE);
4760 Py_DECREF(a);
4761 Py_DECREF(b);
4762 if (ok < 0) {
4763 PyErr_Clear();
4764 return 0;
4767 return ok;
4771 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
4772 static PyObject * \
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) { \
4781 PyObject *r; \
4782 if (do_other && \
4783 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4784 method_is_overloaded(self, other, ROPSTR)) { \
4785 r = call_maybe( \
4786 other, ROPSTR, &rcache_str, "(O)", self); \
4787 if (r != Py_NotImplemented) \
4788 return r; \
4789 Py_DECREF(r); \
4790 do_other = 0; \
4792 r = call_maybe( \
4793 self, OPSTR, &cache_str, "(O)", other); \
4794 if (r != Py_NotImplemented || \
4795 Py_TYPE(other) == Py_TYPE(self)) \
4796 return r; \
4797 Py_DECREF(r); \
4799 if (do_other) { \
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) \
4811 static PyObject * \
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); \
4819 static Py_ssize_t
4820 slot_sq_length(PyObject *self)
4822 static PyObject *len_str;
4823 PyObject *res = call_method(self, "__len__", &len_str, "()");
4824 Py_ssize_t len;
4826 if (res == NULL)
4827 return -1;
4828 len = PyInt_AsSsize_t(res);
4829 Py_DECREF(res);
4830 if (len < 0) {
4831 if (!PyErr_Occurred())
4832 PyErr_SetString(PyExc_ValueError,
4833 "__len__() should return >= 0");
4834 return -1;
4836 return len;
4839 /* Super-optimized version of slot_sq_item.
4840 Other slots could do the same... */
4841 static PyObject *
4842 slot_sq_item(PyObject *self, Py_ssize_t i)
4844 static PyObject *getitem_str;
4845 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4846 descrgetfunc f;
4848 if (getitem_str == NULL) {
4849 getitem_str = PyString_InternFromString("__getitem__");
4850 if (getitem_str == NULL)
4851 return NULL;
4853 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4854 if (func != NULL) {
4855 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4856 Py_INCREF(func);
4857 else {
4858 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4859 if (func == NULL) {
4860 return NULL;
4863 ival = PyInt_FromSsize_t(i);
4864 if (ival != NULL) {
4865 args = PyTuple_New(1);
4866 if (args != NULL) {
4867 PyTuple_SET_ITEM(args, 0, ival);
4868 retval = PyObject_Call(func, args, NULL);
4869 Py_XDECREF(args);
4870 Py_XDECREF(func);
4871 return retval;
4875 else {
4876 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4878 Py_XDECREF(args);
4879 Py_XDECREF(ival);
4880 Py_XDECREF(func);
4881 return NULL;
4884 SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
4886 static int
4887 slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
4889 PyObject *res;
4890 static PyObject *delitem_str, *setitem_str;
4892 if (value == NULL)
4893 res = call_method(self, "__delitem__", &delitem_str,
4894 "(n)", index);
4895 else
4896 res = call_method(self, "__setitem__", &setitem_str,
4897 "(nO)", index, value);
4898 if (res == NULL)
4899 return -1;
4900 Py_DECREF(res);
4901 return 0;
4904 static int
4905 slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
4907 PyObject *res;
4908 static PyObject *delslice_str, *setslice_str;
4910 if (value == NULL)
4911 res = call_method(self, "__delslice__", &delslice_str,
4912 "(nn)", i, j);
4913 else
4914 res = call_method(self, "__setslice__", &setslice_str,
4915 "(nnO)", i, j, value);
4916 if (res == NULL)
4917 return -1;
4918 Py_DECREF(res);
4919 return 0;
4922 static int
4923 slot_sq_contains(PyObject *self, PyObject *value)
4925 PyObject *func, *res, *args;
4926 int result = -1;
4928 static PyObject *contains_str;
4930 func = lookup_maybe(self, "__contains__", &contains_str);
4931 if (func != NULL) {
4932 args = PyTuple_Pack(1, value);
4933 if (args == NULL)
4934 res = NULL;
4935 else {
4936 res = PyObject_Call(func, args, NULL);
4937 Py_DECREF(args);
4939 Py_DECREF(func);
4940 if (res != NULL) {
4941 result = PyObject_IsTrue(res);
4942 Py_DECREF(res);
4945 else if (! PyErr_Occurred()) {
4946 /* Possible results: -1 and 1 */
4947 result = (int)_PySequence_IterSearch(self, value,
4948 PY_ITERSEARCH_CONTAINS);
4950 return result;
4953 #define slot_mp_length slot_sq_length
4955 SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
4957 static int
4958 slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4960 PyObject *res;
4961 static PyObject *delitem_str, *setitem_str;
4963 if (value == NULL)
4964 res = call_method(self, "__delitem__", &delitem_str,
4965 "(O)", key);
4966 else
4967 res = call_method(self, "__setitem__", &setitem_str,
4968 "(OO)", key, value);
4969 if (res == NULL)
4970 return -1;
4971 Py_DECREF(res);
4972 return 0;
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__")
4987 static PyObject *
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__")
5010 static int
5011 slot_nb_nonzero(PyObject *self)
5013 PyObject *func, *args;
5014 static PyObject *nonzero_str, *len_str;
5015 int result = -1;
5017 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
5018 if (func == NULL) {
5019 if (PyErr_Occurred())
5020 return -1;
5021 func = lookup_maybe(self, "__len__", &len_str);
5022 if (func == NULL)
5023 return PyErr_Occurred() ? -1 : 1;
5025 args = PyTuple_New(0);
5026 if (args != NULL) {
5027 PyObject *temp = PyObject_Call(func, args, NULL);
5028 Py_DECREF(args);
5029 if (temp != NULL) {
5030 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
5031 result = PyObject_IsTrue(temp);
5032 else {
5033 PyErr_Format(PyExc_TypeError,
5034 "__nonzero__ should return "
5035 "bool or int, returned %s",
5036 temp->ob_type->tp_name);
5037 result = -1;
5039 Py_DECREF(temp);
5042 Py_DECREF(func);
5043 return result;
5047 static PyObject *
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__")
5062 static int
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) {
5070 PyObject *r;
5071 r = call_maybe(
5072 self, "__coerce__", &coerce_str, "(O)", other);
5073 if (r == NULL)
5074 return -1;
5075 if (r == Py_NotImplemented) {
5076 Py_DECREF(r);
5078 else {
5079 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5080 PyErr_SetString(PyExc_TypeError,
5081 "__coerce__ didn't return a 2-tuple");
5082 Py_DECREF(r);
5083 return -1;
5085 *a = PyTuple_GET_ITEM(r, 0);
5086 Py_INCREF(*a);
5087 *b = PyTuple_GET_ITEM(r, 1);
5088 Py_INCREF(*b);
5089 Py_DECREF(r);
5090 return 0;
5093 if (other->ob_type->tp_as_number != NULL &&
5094 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5095 PyObject *r;
5096 r = call_maybe(
5097 other, "__coerce__", &coerce_str, "(O)", self);
5098 if (r == NULL)
5099 return -1;
5100 if (r == Py_NotImplemented) {
5101 Py_DECREF(r);
5102 return 1;
5104 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5105 PyErr_SetString(PyExc_TypeError,
5106 "__coerce__ didn't return a 2-tuple");
5107 Py_DECREF(r);
5108 return -1;
5110 *a = PyTuple_GET_ITEM(r, 1);
5111 Py_INCREF(*a);
5112 *b = PyTuple_GET_ITEM(r, 0);
5113 Py_INCREF(*b);
5114 Py_DECREF(r);
5115 return 0;
5117 return 1;
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 */
5131 static PyObject *
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")
5148 static int
5149 half_compare(PyObject *self, PyObject *other)
5151 PyObject *func, *args, *res;
5152 static PyObject *cmp_str;
5153 Py_ssize_t c;
5155 func = lookup_method(self, "__cmp__", &cmp_str);
5156 if (func == NULL) {
5157 PyErr_Clear();
5159 else {
5160 args = PyTuple_Pack(1, other);
5161 if (args == NULL)
5162 res = NULL;
5163 else {
5164 res = PyObject_Call(func, args, NULL);
5165 Py_DECREF(args);
5167 Py_DECREF(func);
5168 if (res != Py_NotImplemented) {
5169 if (res == NULL)
5170 return -2;
5171 c = PyInt_AsLong(res);
5172 Py_DECREF(res);
5173 if (c == -1 && PyErr_Occurred())
5174 return -2;
5175 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5177 Py_DECREF(res);
5179 return 2;
5182 /* This slot is published for the benefit of try_3way_compare in object.c */
5184 _PyObject_SlotCompare(PyObject *self, PyObject *other)
5186 int c;
5188 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
5189 c = half_compare(self, other);
5190 if (c <= 1)
5191 return c;
5193 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
5194 c = half_compare(other, self);
5195 if (c < -1)
5196 return -2;
5197 if (c <= 1)
5198 return -c;
5200 return (void *)self < (void *)other ? -1 :
5201 (void *)self > (void *)other ? 1 : 0;
5204 static PyObject *
5205 slot_tp_repr(PyObject *self)
5207 PyObject *func, *res;
5208 static PyObject *repr_str;
5210 func = lookup_method(self, "__repr__", &repr_str);
5211 if (func != NULL) {
5212 res = PyEval_CallObject(func, NULL);
5213 Py_DECREF(func);
5214 return res;
5216 PyErr_Clear();
5217 return PyString_FromFormat("<%s object at %p>",
5218 Py_TYPE(self)->tp_name, self);
5221 static PyObject *
5222 slot_tp_str(PyObject *self)
5224 PyObject *func, *res;
5225 static PyObject *str_str;
5227 func = lookup_method(self, "__str__", &str_str);
5228 if (func != NULL) {
5229 res = PyEval_CallObject(func, NULL);
5230 Py_DECREF(func);
5231 return res;
5233 else {
5234 PyErr_Clear();
5235 return slot_tp_repr(self);
5239 static long
5240 slot_tp_hash(PyObject *self)
5242 PyObject *func;
5243 static PyObject *hash_str, *eq_str, *cmp_str;
5244 long h;
5246 func = lookup_method(self, "__hash__", &hash_str);
5248 if (func != NULL && func != Py_None) {
5249 PyObject *res = PyEval_CallObject(func, NULL);
5250 Py_DECREF(func);
5251 if (res == NULL)
5252 return -1;
5253 if (PyLong_Check(res))
5254 h = PyLong_Type.tp_hash(res);
5255 else
5256 h = PyInt_AsLong(res);
5257 Py_DECREF(res);
5259 else {
5260 Py_XDECREF(func); /* may be None */
5261 PyErr_Clear();
5262 func = lookup_method(self, "__eq__", &eq_str);
5263 if (func == NULL) {
5264 PyErr_Clear();
5265 func = lookup_method(self, "__cmp__", &cmp_str);
5267 if (func != NULL) {
5268 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
5269 self->ob_type->tp_name);
5270 Py_DECREF(func);
5271 return -1;
5273 PyErr_Clear();
5274 h = _Py_HashPointer((void *)self);
5276 if (h == -1 && !PyErr_Occurred())
5277 h = -2;
5278 return h;
5281 static PyObject *
5282 slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5284 static PyObject *call_str;
5285 PyObject *meth = lookup_method(self, "__call__", &call_str);
5286 PyObject *res;
5288 if (meth == NULL)
5289 return NULL;
5291 res = PyObject_Call(meth, args, kwds);
5293 Py_DECREF(meth);
5294 return res;
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
5306 necessary. */
5308 static PyObject *
5309 slot_tp_getattro(PyObject *self, PyObject *name)
5311 static PyObject *getattribute_str = NULL;
5312 return call_method(self, "__getattribute__", &getattribute_str,
5313 "(O)", name);
5316 static PyObject *
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)
5327 return NULL;
5329 if (getattribute_str == NULL) {
5330 getattribute_str =
5331 PyString_InternFromString("__getattribute__");
5332 if (getattribute_str == NULL)
5333 return 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);
5347 else
5348 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
5349 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5350 PyErr_Clear();
5351 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
5353 return res;
5356 static int
5357 slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5359 PyObject *res;
5360 static PyObject *delattr_str, *setattr_str;
5362 if (value == NULL)
5363 res = call_method(self, "__delattr__", &delattr_str,
5364 "(O)", name);
5365 else
5366 res = call_method(self, "__setattr__", &setattr_str,
5367 "(OO)", name, value);
5368 if (res == NULL)
5369 return -1;
5370 Py_DECREF(res);
5371 return 0;
5374 static char *name_op[] = {
5375 "__lt__",
5376 "__le__",
5377 "__eq__",
5378 "__ne__",
5379 "__gt__",
5380 "__ge__",
5383 static PyObject *
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]);
5390 if (func == NULL) {
5391 PyErr_Clear();
5392 Py_INCREF(Py_NotImplemented);
5393 return Py_NotImplemented;
5395 args = PyTuple_Pack(1, other);
5396 if (args == NULL)
5397 res = NULL;
5398 else {
5399 res = PyObject_Call(func, args, NULL);
5400 Py_DECREF(args);
5402 Py_DECREF(func);
5403 return res;
5406 static PyObject *
5407 slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5409 PyObject *res;
5411 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
5412 res = half_richcompare(self, other, op);
5413 if (res != Py_NotImplemented)
5414 return res;
5415 Py_DECREF(res);
5417 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
5418 res = half_richcompare(other, self, _Py_SwappedOp[op]);
5419 if (res != Py_NotImplemented) {
5420 return res;
5422 Py_DECREF(res);
5424 Py_INCREF(Py_NotImplemented);
5425 return Py_NotImplemented;
5428 static PyObject *
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);
5435 if (func != NULL) {
5436 PyObject *args;
5437 args = res = PyTuple_New(0);
5438 if (args != NULL) {
5439 res = PyObject_Call(func, args, NULL);
5440 Py_DECREF(args);
5442 Py_DECREF(func);
5443 return res;
5445 PyErr_Clear();
5446 func = lookup_method(self, "__getitem__", &getitem_str);
5447 if (func == NULL) {
5448 PyErr_Format(PyExc_TypeError,
5449 "'%.200s' object is not iterable",
5450 Py_TYPE(self)->tp_name);
5451 return NULL;
5453 Py_DECREF(func);
5454 return PySeqIter_New(self);
5457 static PyObject *
5458 slot_tp_iternext(PyObject *self)
5460 static PyObject *next_str;
5461 return call_method(self, "next", &next_str, "()");
5464 static PyObject *
5465 slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5467 PyTypeObject *tp = Py_TYPE(self);
5468 PyObject *get;
5469 static PyObject *get_str = NULL;
5471 if (get_str == NULL) {
5472 get_str = PyString_InternFromString("__get__");
5473 if (get_str == NULL)
5474 return NULL;
5476 get = _PyType_Lookup(tp, get_str);
5477 if (get == NULL) {
5478 /* Avoid further slowdowns */
5479 if (tp->tp_descr_get == slot_tp_descr_get)
5480 tp->tp_descr_get = NULL;
5481 Py_INCREF(self);
5482 return self;
5484 if (obj == NULL)
5485 obj = Py_None;
5486 if (type == NULL)
5487 type = Py_None;
5488 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
5491 static int
5492 slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5494 PyObject *res;
5495 static PyObject *del_str, *set_str;
5497 if (value == NULL)
5498 res = call_method(self, "__delete__", &del_str,
5499 "(O)", target);
5500 else
5501 res = call_method(self, "__set__", &set_str,
5502 "(OO)", target, value);
5503 if (res == NULL)
5504 return -1;
5505 Py_DECREF(res);
5506 return 0;
5509 static int
5510 slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5512 static PyObject *init_str;
5513 PyObject *meth = lookup_method(self, "__init__", &init_str);
5514 PyObject *res;
5516 if (meth == NULL)
5517 return -1;
5518 res = PyObject_Call(meth, args, kwds);
5519 Py_DECREF(meth);
5520 if (res == NULL)
5521 return -1;
5522 if (res != Py_None) {
5523 PyErr_Format(PyExc_TypeError,
5524 "__init__() should return None, not '%.200s'",
5525 Py_TYPE(res)->tp_name);
5526 Py_DECREF(res);
5527 return -1;
5529 Py_DECREF(res);
5530 return 0;
5533 static PyObject *
5534 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5536 static PyObject *new_str;
5537 PyObject *func;
5538 PyObject *newargs, *x;
5539 Py_ssize_t i, n;
5541 if (new_str == NULL) {
5542 new_str = PyString_InternFromString("__new__");
5543 if (new_str == NULL)
5544 return NULL;
5546 func = PyObject_GetAttr((PyObject *)type, new_str);
5547 if (func == NULL)
5548 return NULL;
5549 assert(PyTuple_Check(args));
5550 n = PyTuple_GET_SIZE(args);
5551 newargs = PyTuple_New(n+1);
5552 if (newargs == NULL)
5553 return NULL;
5554 Py_INCREF(type);
5555 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5556 for (i = 0; i < n; i++) {
5557 x = PyTuple_GET_ITEM(args, i);
5558 Py_INCREF(x);
5559 PyTuple_SET_ITEM(newargs, i+1, x);
5561 x = PyObject_Call(func, newargs, kwds);
5562 Py_DECREF(newargs);
5563 Py_DECREF(func);
5564 return x;
5567 static void
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);
5583 if (del != NULL) {
5584 res = PyEval_CallObject(del, NULL);
5585 if (res == NULL)
5586 PyErr_WriteUnraisable(del);
5587 else
5588 Py_DECREF(res);
5589 Py_DECREF(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
5603 * never happened.
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. */
5614 _Py_DEC_REFTOTAL;
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
5619 * undone.
5621 #ifdef COUNT_ALLOCS
5622 --Py_TYPE(self)->tp_frees;
5623 --Py_TYPE(self)->tp_allocs;
5624 #endif
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;
5640 #undef TPSLOT
5641 #undef FLSLOT
5642 #undef ETSLOT
5643 #undef SQSLOT
5644 #undef MPSLOT
5645 #undef NBSLOT
5646 #undef UNSLOT
5647 #undef IBSLOT
5648 #undef BINSLOT
5649 #undef RBINSLOT
5651 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5652 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5653 PyDoc_STR(DOC)}
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, \
5659 PyDoc_STR(DOC)}
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,
5728 wrap_binaryfunc,
5729 "x.__getitem__(y) <==> x[y]"),
5730 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5731 wrap_objobjargproc,
5732 "x.__setitem__(i, y) <==> x[i]=y"),
5733 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5734 wrap_delitem,
5735 "x.__delitem__(y) <==> del x[y]"),
5737 BINSLOT("__add__", nb_add, slot_nb_add,
5738 "+"),
5739 RBINSLOT("__radd__", nb_add, slot_nb_add,
5740 "+"),
5741 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5742 "-"),
5743 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5744 "-"),
5745 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5746 "*"),
5747 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5748 "*"),
5749 BINSLOT("__div__", nb_divide, slot_nb_divide,
5750 "/"),
5751 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5752 "/"),
5753 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5754 "%"),
5755 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5756 "%"),
5757 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5758 "divmod(x, y)"),
5759 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5760 "divmod(y, x)"),
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,
5768 "abs(x)"),
5769 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
5770 "x != 0"),
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,
5785 "int(x)"),
5786 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5787 "long(x)"),
5788 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5789 "float(x)"),
5790 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5791 "oct(x)"),
5792 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5793 "hex(x)"),
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, ""),
5878 {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. */
5886 static void **
5887 slotptr(PyTypeObject *type, int ioffset)
5889 char *ptr;
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);
5907 else {
5908 ptr = (char *)type;
5910 if (ptr != NULL)
5911 ptr += offset;
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. */
5923 static void **
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];
5931 slotdef *p, **pp;
5932 void **res, **ptr;
5934 if (pname != name) {
5935 /* Collect all slotdefs that match name into ptrs. */
5936 pname = name;
5937 pp = ptrs;
5938 for (p = slotdefs; p->name_strobj; p++) {
5939 if (p->name_strobj == name)
5940 *pp++ = p;
5942 *pp = NULL;
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. */
5947 res = NULL;
5948 for (pp = ptrs; *pp; pp++) {
5949 ptr = slotptr(type, (*pp)->offset);
5950 if (ptr == NULL || *ptr == NULL)
5951 continue;
5952 if (res != NULL)
5953 return NULL;
5954 res = ptr;
5956 return res;
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(). */
5965 static slotdef *
5966 update_one_slot(PyTypeObject *type, slotdef *p)
5968 PyObject *descr;
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);
5975 if (ptr == NULL) {
5976 do {
5977 ++p;
5978 } while (p->offset == offset);
5979 return p;
5981 do {
5982 descr = _PyType_Lookup(type, p->name_strobj);
5983 if (descr == NULL)
5984 continue;
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;
5996 else
5997 use_generic = 1;
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. */
6022 else {
6023 use_generic = 1;
6024 generic = p->function;
6026 } while ((++p)->offset == offset);
6027 if (specific && !use_generic)
6028 *ptr = specific;
6029 else
6030 *ptr = generic;
6031 return p;
6034 /* In the type, update the slots whose slotdefs are gathered in the pp array.
6035 This is a callback for update_subclasses(). */
6036 static int
6037 update_slots_callback(PyTypeObject *type, void *data)
6039 slotdef **pp = (slotdef **)data;
6041 for (; *pp; pp++)
6042 update_one_slot(type, *pp);
6043 return 0;
6046 /* Comparison function for qsort() to compare slotdefs by their offset, and
6047 for equal offset by their address (to force a stable sort). */
6048 static int
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;
6053 if (c != 0)
6054 return c;
6055 else
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. */
6063 static void
6064 init_slotdefs(void)
6066 slotdef *p;
6067 static int initialized = 0;
6069 if (initialized)
6070 return;
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),
6077 slotdef_cmp);
6078 initialized = 1;
6081 /* Update the slots after assignment to a class (type) attribute. */
6082 static int
6083 update_slot(PyTypeObject *type, PyObject *name)
6085 slotdef *ptrs[MAX_EQUIV];
6086 slotdef *p;
6087 slotdef **pp;
6088 int offset;
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);
6097 init_slotdefs();
6098 pp = ptrs;
6099 for (p = slotdefs; p->name; p++) {
6100 /* XXX assume name is interned! */
6101 if (p->name_strobj == name)
6102 *pp++ = p;
6104 *pp = NULL;
6105 for (pp = ptrs; *pp; pp++) {
6106 p = *pp;
6107 offset = p->offset;
6108 while (p > slotdefs && (p-1)->offset == offset)
6109 --p;
6110 *pp = p;
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
6120 dict. */
6121 static void
6122 fixup_slot_dispatchers(PyTypeObject *type)
6124 slotdef *p;
6126 init_slotdefs();
6127 for (p = slotdefs; p->name; )
6128 p = update_one_slot(type, p);
6131 static void
6132 update_all_slots(PyTypeObject* type)
6134 slotdef *p;
6136 init_slotdefs();
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'. */
6147 static int
6148 update_subclasses(PyTypeObject *type, PyObject *name,
6149 update_callback callback, void *data)
6151 if (callback(type, data) < 0)
6152 return -1;
6153 return recurse_down_subclasses(type, name, callback, data);
6156 static int
6157 recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6158 update_callback callback, void *data)
6160 PyTypeObject *subclass;
6161 PyObject *ref, *subclasses, *dict;
6162 Py_ssize_t i, n;
6164 subclasses = type->tp_subclasses;
6165 if (subclasses == NULL)
6166 return 0;
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)
6175 continue;
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)
6181 continue;
6182 if (update_subclasses(subclass, name, callback, data) < 0)
6183 return -1;
6185 return 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
6205 wins.
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.) */
6218 static int
6219 add_operators(PyTypeObject *type)
6221 PyObject *dict = type->tp_dict;
6222 slotdef *p;
6223 PyObject *descr;
6224 void **ptr;
6226 init_slotdefs();
6227 for (p = slotdefs; p->name; p++) {
6228 if (p->wrapper == NULL)
6229 continue;
6230 ptr = slotptr(type, p->offset);
6231 if (!ptr || !*ptr)
6232 continue;
6233 if (PyDict_GetItem(dict, p->name_strobj))
6234 continue;
6235 descr = PyDescr_NewWrapper(type, p, *ptr);
6236 if (descr == NULL)
6237 return -1;
6238 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6239 return -1;
6240 Py_DECREF(descr);
6242 if (type->tp_new != NULL) {
6243 if (add_tp_new_wrapper(type) < 0)
6244 return -1;
6246 return 0;
6250 /* Cooperative 'super' */
6252 typedef struct {
6253 PyObject_HEAD
6254 PyTypeObject *type;
6255 PyObject *obj;
6256 PyTypeObject *obj_type;
6257 } superobject;
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"},
6269 static void
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);
6281 static PyObject *
6282 super_repr(PyObject *self)
6284 superobject *su = (superobject *)self;
6286 if (su->obj_type)
6287 return PyString_FromFormat(
6288 "<super: <class '%s'>, <%s object>>",
6289 su->type ? su->type->tp_name : "NULL",
6290 su->obj_type->tp_name);
6291 else
6292 return PyString_FromFormat(
6293 "<super: <class '%s'>, NULL>",
6294 su->type ? su->type->tp_name : "NULL");
6297 static PyObject *
6298 super_getattro(PyObject *self, PyObject *name)
6300 superobject *su = (superobject *)self;
6301 int skip = su->obj_type == NULL;
6303 if (!skip) {
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);
6311 if (!skip) {
6312 PyObject *mro, *res, *tmp, *dict;
6313 PyTypeObject *starttype;
6314 descrgetfunc f;
6315 Py_ssize_t i, n;
6317 starttype = su->obj_type;
6318 mro = starttype->tp_mro;
6320 if (mro == NULL)
6321 n = 0;
6322 else {
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))
6328 break;
6330 i++;
6331 res = NULL;
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;
6338 else
6339 continue;
6340 res = PyDict_GetItem(dict, name);
6341 if (res != NULL) {
6342 Py_INCREF(res);
6343 f = Py_TYPE(res)->tp_descr_get;
6344 if (f != NULL) {
6345 tmp = f(res,
6346 /* Only pass 'obj' param if
6347 this is instance-mode super
6348 (See SF ID #743627)
6350 (su->obj == (PyObject *)
6351 su->obj_type
6352 ? (PyObject *)NULL
6353 : su->obj),
6354 (PyObject *)starttype);
6355 Py_DECREF(res);
6356 res = tmp;
6358 return res;
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)) {
6385 Py_INCREF(obj);
6386 return (PyTypeObject *)obj;
6389 /* Normal case */
6390 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6391 Py_INCREF(Py_TYPE(obj));
6392 return Py_TYPE(obj);
6394 else {
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)
6402 return 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);
6413 if (ok)
6414 return (PyTypeObject *)class_attr;
6417 if (class_attr == NULL)
6418 PyErr_Clear();
6419 else
6420 Py_DECREF(class_attr);
6423 PyErr_SetString(PyExc_TypeError,
6424 "super(type, obj): "
6425 "obj must be an instance or subtype of type");
6426 return NULL;
6429 static PyObject *
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 */
6437 Py_INCREF(self);
6438 return self;
6440 if (Py_TYPE(su) != &PySuper_Type)
6441 /* If su is an instance of a (strict) subclass of super,
6442 call its type */
6443 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6444 su->type, obj, NULL);
6445 else {
6446 /* Inline the common case */
6447 PyTypeObject *obj_type = supercheck(su->type, obj);
6448 if (obj_type == NULL)
6449 return NULL;
6450 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6451 NULL, NULL);
6452 if (newobj == NULL)
6453 return NULL;
6454 Py_INCREF(su->type);
6455 Py_INCREF(obj);
6456 newobj->type = su->type;
6457 newobj->obj = obj;
6458 newobj->obj_type = obj_type;
6459 return (PyObject *)newobj;
6463 static int
6464 super_init(PyObject *self, PyObject *args, PyObject *kwds)
6466 superobject *su = (superobject *)self;
6467 PyTypeObject *type;
6468 PyObject *obj = NULL;
6469 PyTypeObject *obj_type = NULL;
6471 if (!_PyArg_NoKeywords("super", kwds))
6472 return -1;
6473 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6474 return -1;
6475 if (obj == Py_None)
6476 obj = NULL;
6477 if (obj != NULL) {
6478 obj_type = supercheck(type, obj);
6479 if (obj_type == NULL)
6480 return -1;
6481 Py_INCREF(obj);
6483 Py_INCREF(type);
6484 su->type = type;
6485 su->obj = obj;
6486 su->obj_type = obj_type;
6487 return 0;
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"
6495 "class C(B):\n"
6496 " def meth(self, arg):\n"
6497 " super(C, self).meth(arg)");
6499 static int
6500 super_traverse(PyObject *self, visitproc visit, void *arg)
6502 superobject *su = (superobject *)self;
6504 Py_VISIT(su->obj);
6505 Py_VISIT(su->type);
6506 Py_VISIT(su->obj_type);
6508 return 0;
6511 PyTypeObject PySuper_Type = {
6512 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6513 "super", /* tp_name */
6514 sizeof(superobject), /* tp_basicsize */
6515 0, /* tp_itemsize */
6516 /* methods */
6517 super_dealloc, /* tp_dealloc */
6518 0, /* tp_print */
6519 0, /* tp_getattr */
6520 0, /* tp_setattr */
6521 0, /* tp_compare */
6522 super_repr, /* tp_repr */
6523 0, /* tp_as_number */
6524 0, /* tp_as_sequence */
6525 0, /* tp_as_mapping */
6526 0, /* tp_hash */
6527 0, /* tp_call */
6528 0, /* tp_str */
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 */
6536 0, /* tp_clear */
6537 0, /* tp_richcompare */
6538 0, /* tp_weaklistoffset */
6539 0, /* tp_iter */
6540 0, /* tp_iternext */
6541 0, /* tp_methods */
6542 super_members, /* tp_members */
6543 0, /* tp_getset */
6544 0, /* tp_base */
6545 0, /* tp_dict */
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 */