add explanatory comment
[python.git] / Objects / typeobject.c
blob1df37d199634f2d126d6f9690c70f38cdac468e1
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;
36 unsigned int
37 PyType_ClearCache(void)
39 Py_ssize_t i;
40 unsigned int cur_version_tag = next_version_tag - 1;
42 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
43 method_cache[i].version = 0;
44 Py_CLEAR(method_cache[i].name);
45 method_cache[i].value = NULL;
47 next_version_tag = 0;
48 /* mark all version tags as invalid */
49 PyType_Modified(&PyBaseObject_Type);
50 return cur_version_tag;
53 void
54 PyType_Modified(PyTypeObject *type)
56 /* Invalidate any cached data for the specified type and all
57 subclasses. This function is called after the base
58 classes, mro, or attributes of the type are altered.
60 Invariants:
62 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
63 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
64 objects coming from non-recompiled extension modules)
66 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
67 it must first be set on all super types.
69 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
70 type (so it must first clear it on all subclasses). The
71 tp_version_tag value is meaningless unless this flag is set.
72 We don't assign new version tags eagerly, but only as
73 needed.
75 PyObject *raw, *ref;
76 Py_ssize_t i, n;
78 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
79 return;
81 raw = type->tp_subclasses;
82 if (raw != NULL) {
83 n = PyList_GET_SIZE(raw);
84 for (i = 0; i < n; i++) {
85 ref = PyList_GET_ITEM(raw, i);
86 ref = PyWeakref_GET_OBJECT(ref);
87 if (ref != Py_None) {
88 PyType_Modified((PyTypeObject *)ref);
92 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
95 static void
96 type_mro_modified(PyTypeObject *type, PyObject *bases) {
98 Check that all base classes or elements of the mro of type are
99 able to be cached. This function is called after the base
100 classes or mro of the type are altered.
102 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
103 inherits from an old-style class, either directly or if it
104 appears in the MRO of a new-style class. No support either for
105 custom MROs that include types that are not officially super
106 types.
108 Called from mro_internal, which will subsequently be called on
109 each subclass when their mro is recursively updated.
111 Py_ssize_t i, n;
112 int clear = 0;
114 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
115 return;
117 n = PyTuple_GET_SIZE(bases);
118 for (i = 0; i < n; i++) {
119 PyObject *b = PyTuple_GET_ITEM(bases, i);
120 PyTypeObject *cls;
122 if (!PyType_Check(b) ) {
123 clear = 1;
124 break;
127 cls = (PyTypeObject *)b;
129 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
130 !PyType_IsSubtype(type, cls)) {
131 clear = 1;
132 break;
136 if (clear)
137 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
138 Py_TPFLAGS_VALID_VERSION_TAG);
141 static int
142 assign_version_tag(PyTypeObject *type)
144 /* Ensure that the tp_version_tag is valid and set
145 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
146 must first be done on all super classes. Return 0 if this
147 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
149 Py_ssize_t i, n;
150 PyObject *bases;
152 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
153 return 1;
154 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
155 return 0;
156 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
157 return 0;
159 type->tp_version_tag = next_version_tag++;
160 /* for stress-testing: next_version_tag &= 0xFF; */
162 if (type->tp_version_tag == 0) {
163 /* wrap-around or just starting Python - clear the whole
164 cache by filling names with references to Py_None.
165 Values are also set to NULL for added protection, as they
166 are borrowed reference */
167 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
168 method_cache[i].value = NULL;
169 Py_XDECREF(method_cache[i].name);
170 method_cache[i].name = Py_None;
171 Py_INCREF(Py_None);
173 /* mark all version tags as invalid */
174 PyType_Modified(&PyBaseObject_Type);
175 return 1;
177 bases = type->tp_bases;
178 n = PyTuple_GET_SIZE(bases);
179 for (i = 0; i < n; i++) {
180 PyObject *b = PyTuple_GET_ITEM(bases, i);
181 assert(PyType_Check(b));
182 if (!assign_version_tag((PyTypeObject *)b))
183 return 0;
185 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
186 return 1;
190 static PyMemberDef type_members[] = {
191 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
192 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
193 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
194 {"__weakrefoffset__", T_LONG,
195 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
196 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
197 {"__dictoffset__", T_LONG,
198 offsetof(PyTypeObject, tp_dictoffset), READONLY},
199 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
203 static PyObject *
204 type_name(PyTypeObject *type, void *context)
206 const char *s;
208 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
209 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
211 Py_INCREF(et->ht_name);
212 return et->ht_name;
214 else {
215 s = strrchr(type->tp_name, '.');
216 if (s == NULL)
217 s = type->tp_name;
218 else
219 s++;
220 return PyString_FromString(s);
224 static int
225 type_set_name(PyTypeObject *type, PyObject *value, void *context)
227 PyHeapTypeObject* et;
229 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
230 PyErr_Format(PyExc_TypeError,
231 "can't set %s.__name__", type->tp_name);
232 return -1;
234 if (!value) {
235 PyErr_Format(PyExc_TypeError,
236 "can't delete %s.__name__", type->tp_name);
237 return -1;
239 if (!PyString_Check(value)) {
240 PyErr_Format(PyExc_TypeError,
241 "can only assign string to %s.__name__, not '%s'",
242 type->tp_name, Py_TYPE(value)->tp_name);
243 return -1;
245 if (strlen(PyString_AS_STRING(value))
246 != (size_t)PyString_GET_SIZE(value)) {
247 PyErr_Format(PyExc_ValueError,
248 "__name__ must not contain null bytes");
249 return -1;
252 et = (PyHeapTypeObject*)type;
254 Py_INCREF(value);
256 Py_DECREF(et->ht_name);
257 et->ht_name = value;
259 type->tp_name = PyString_AS_STRING(value);
261 return 0;
264 static PyObject *
265 type_module(PyTypeObject *type, void *context)
267 PyObject *mod;
268 char *s;
270 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
271 mod = PyDict_GetItemString(type->tp_dict, "__module__");
272 if (!mod) {
273 PyErr_Format(PyExc_AttributeError, "__module__");
274 return 0;
276 Py_XINCREF(mod);
277 return mod;
279 else {
280 s = strrchr(type->tp_name, '.');
281 if (s != NULL)
282 return PyString_FromStringAndSize(
283 type->tp_name, (Py_ssize_t)(s - type->tp_name));
284 return PyString_FromString("__builtin__");
288 static int
289 type_set_module(PyTypeObject *type, PyObject *value, void *context)
291 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
292 PyErr_Format(PyExc_TypeError,
293 "can't set %s.__module__", type->tp_name);
294 return -1;
296 if (!value) {
297 PyErr_Format(PyExc_TypeError,
298 "can't delete %s.__module__", type->tp_name);
299 return -1;
302 PyType_Modified(type);
304 return PyDict_SetItemString(type->tp_dict, "__module__", value);
307 static PyObject *
308 type_abstractmethods(PyTypeObject *type, void *context)
310 PyObject *mod = PyDict_GetItemString(type->tp_dict,
311 "__abstractmethods__");
312 if (!mod) {
313 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
314 return NULL;
316 Py_XINCREF(mod);
317 return mod;
320 static int
321 type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
323 /* __abstractmethods__ should only be set once on a type, in
324 abc.ABCMeta.__new__, so this function doesn't do anything
325 special to update subclasses.
327 int res = PyDict_SetItemString(type->tp_dict,
328 "__abstractmethods__", value);
329 if (res == 0) {
330 PyType_Modified(type);
331 if (value && PyObject_IsTrue(value)) {
332 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
334 else {
335 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
338 return res;
341 static PyObject *
342 type_get_bases(PyTypeObject *type, void *context)
344 Py_INCREF(type->tp_bases);
345 return type->tp_bases;
348 static PyTypeObject *best_base(PyObject *);
349 static int mro_internal(PyTypeObject *);
350 static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
351 static int add_subclass(PyTypeObject*, PyTypeObject*);
352 static void remove_subclass(PyTypeObject *, PyTypeObject *);
353 static void update_all_slots(PyTypeObject *);
355 typedef int (*update_callback)(PyTypeObject *, void *);
356 static int update_subclasses(PyTypeObject *type, PyObject *name,
357 update_callback callback, void *data);
358 static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
359 update_callback callback, void *data);
361 static int
362 mro_subclasses(PyTypeObject *type, PyObject* temp)
364 PyTypeObject *subclass;
365 PyObject *ref, *subclasses, *old_mro;
366 Py_ssize_t i, n;
368 subclasses = type->tp_subclasses;
369 if (subclasses == NULL)
370 return 0;
371 assert(PyList_Check(subclasses));
372 n = PyList_GET_SIZE(subclasses);
373 for (i = 0; i < n; i++) {
374 ref = PyList_GET_ITEM(subclasses, i);
375 assert(PyWeakref_CheckRef(ref));
376 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
377 assert(subclass != NULL);
378 if ((PyObject *)subclass == Py_None)
379 continue;
380 assert(PyType_Check(subclass));
381 old_mro = subclass->tp_mro;
382 if (mro_internal(subclass) < 0) {
383 subclass->tp_mro = old_mro;
384 return -1;
386 else {
387 PyObject* tuple;
388 tuple = PyTuple_Pack(2, subclass, old_mro);
389 Py_DECREF(old_mro);
390 if (!tuple)
391 return -1;
392 if (PyList_Append(temp, tuple) < 0)
393 return -1;
394 Py_DECREF(tuple);
396 if (mro_subclasses(subclass, temp) < 0)
397 return -1;
399 return 0;
402 static int
403 type_set_bases(PyTypeObject *type, PyObject *value, void *context)
405 Py_ssize_t i;
406 int r = 0;
407 PyObject *ob, *temp;
408 PyTypeObject *new_base, *old_base;
409 PyObject *old_bases, *old_mro;
411 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
412 PyErr_Format(PyExc_TypeError,
413 "can't set %s.__bases__", type->tp_name);
414 return -1;
416 if (!value) {
417 PyErr_Format(PyExc_TypeError,
418 "can't delete %s.__bases__", type->tp_name);
419 return -1;
421 if (!PyTuple_Check(value)) {
422 PyErr_Format(PyExc_TypeError,
423 "can only assign tuple to %s.__bases__, not %s",
424 type->tp_name, Py_TYPE(value)->tp_name);
425 return -1;
427 if (PyTuple_GET_SIZE(value) == 0) {
428 PyErr_Format(PyExc_TypeError,
429 "can only assign non-empty tuple to %s.__bases__, not ()",
430 type->tp_name);
431 return -1;
433 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
434 ob = PyTuple_GET_ITEM(value, i);
435 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
436 PyErr_Format(
437 PyExc_TypeError,
438 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
439 type->tp_name, Py_TYPE(ob)->tp_name);
440 return -1;
442 if (PyType_Check(ob)) {
443 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
444 PyErr_SetString(PyExc_TypeError,
445 "a __bases__ item causes an inheritance cycle");
446 return -1;
451 new_base = best_base(value);
453 if (!new_base) {
454 return -1;
457 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
458 return -1;
460 Py_INCREF(new_base);
461 Py_INCREF(value);
463 old_bases = type->tp_bases;
464 old_base = type->tp_base;
465 old_mro = type->tp_mro;
467 type->tp_bases = value;
468 type->tp_base = new_base;
470 if (mro_internal(type) < 0) {
471 goto bail;
474 temp = PyList_New(0);
475 if (!temp)
476 goto bail;
478 r = mro_subclasses(type, temp);
480 if (r < 0) {
481 for (i = 0; i < PyList_Size(temp); i++) {
482 PyTypeObject* cls;
483 PyObject* mro;
484 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
485 "", 2, 2, &cls, &mro);
486 Py_INCREF(mro);
487 ob = cls->tp_mro;
488 cls->tp_mro = mro;
489 Py_DECREF(ob);
491 Py_DECREF(temp);
492 goto bail;
495 Py_DECREF(temp);
497 /* any base that was in __bases__ but now isn't, we
498 need to remove |type| from its tp_subclasses.
499 conversely, any class now in __bases__ that wasn't
500 needs to have |type| added to its subclasses. */
502 /* for now, sod that: just remove from all old_bases,
503 add to all new_bases */
505 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
506 ob = PyTuple_GET_ITEM(old_bases, i);
507 if (PyType_Check(ob)) {
508 remove_subclass(
509 (PyTypeObject*)ob, type);
513 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
514 ob = PyTuple_GET_ITEM(value, i);
515 if (PyType_Check(ob)) {
516 if (add_subclass((PyTypeObject*)ob, type) < 0)
517 r = -1;
521 update_all_slots(type);
523 Py_DECREF(old_bases);
524 Py_DECREF(old_base);
525 Py_DECREF(old_mro);
527 return r;
529 bail:
530 Py_DECREF(type->tp_bases);
531 Py_DECREF(type->tp_base);
532 if (type->tp_mro != old_mro) {
533 Py_DECREF(type->tp_mro);
536 type->tp_bases = old_bases;
537 type->tp_base = old_base;
538 type->tp_mro = old_mro;
540 return -1;
543 static PyObject *
544 type_dict(PyTypeObject *type, void *context)
546 if (type->tp_dict == NULL) {
547 Py_INCREF(Py_None);
548 return Py_None;
550 return PyDictProxy_New(type->tp_dict);
553 static PyObject *
554 type_get_doc(PyTypeObject *type, void *context)
556 PyObject *result;
557 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
558 return PyString_FromString(type->tp_doc);
559 result = PyDict_GetItemString(type->tp_dict, "__doc__");
560 if (result == NULL) {
561 result = Py_None;
562 Py_INCREF(result);
564 else if (Py_TYPE(result)->tp_descr_get) {
565 result = Py_TYPE(result)->tp_descr_get(result, NULL,
566 (PyObject *)type);
568 else {
569 Py_INCREF(result);
571 return result;
574 static PyObject *
575 type___instancecheck__(PyObject *type, PyObject *inst)
577 switch (_PyObject_RealIsInstance(inst, type)) {
578 case -1:
579 return NULL;
580 case 0:
581 Py_RETURN_FALSE;
582 default:
583 Py_RETURN_TRUE;
588 static PyObject *
589 type_get_instancecheck(PyObject *type, void *context)
591 static PyMethodDef ml = {"__instancecheck__",
592 type___instancecheck__, METH_O };
593 return PyCFunction_New(&ml, type);
596 static PyObject *
597 type___subclasscheck__(PyObject *type, PyObject *inst)
599 switch (_PyObject_RealIsSubclass(inst, type)) {
600 case -1:
601 return NULL;
602 case 0:
603 Py_RETURN_FALSE;
604 default:
605 Py_RETURN_TRUE;
609 static PyObject *
610 type_get_subclasscheck(PyObject *type, void *context)
612 static PyMethodDef ml = {"__subclasscheck__",
613 type___subclasscheck__, METH_O };
614 return PyCFunction_New(&ml, type);
617 static PyGetSetDef type_getsets[] = {
618 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
619 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
620 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
621 {"__abstractmethods__", (getter)type_abstractmethods,
622 (setter)type_set_abstractmethods, NULL},
623 {"__dict__", (getter)type_dict, NULL, NULL},
624 {"__doc__", (getter)type_get_doc, NULL, NULL},
625 {"__instancecheck__", (getter)type_get_instancecheck, NULL, NULL},
626 {"__subclasscheck__", (getter)type_get_subclasscheck, NULL, NULL},
630 static int
631 type_compare(PyObject *v, PyObject *w)
633 /* This is called with type objects only. So we
634 can just compare the addresses. */
635 Py_uintptr_t vv = (Py_uintptr_t)v;
636 Py_uintptr_t ww = (Py_uintptr_t)w;
637 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
640 static PyObject*
641 type_richcompare(PyObject *v, PyObject *w, int op)
643 PyObject *result;
644 Py_uintptr_t vv, ww;
645 int c;
647 /* Make sure both arguments are types. */
648 if (!PyType_Check(v) || !PyType_Check(w)) {
649 result = Py_NotImplemented;
650 goto out;
653 /* Py3K warning if comparison isn't == or != */
654 if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
655 PyErr_WarnEx(PyExc_DeprecationWarning,
656 "type inequality comparisons not supported "
657 "in 3.x", 1) < 0) {
658 return NULL;
661 /* Compare addresses */
662 vv = (Py_uintptr_t)v;
663 ww = (Py_uintptr_t)w;
664 switch (op) {
665 case Py_LT: c = vv < ww; break;
666 case Py_LE: c = vv <= ww; break;
667 case Py_EQ: c = vv == ww; break;
668 case Py_NE: c = vv != ww; break;
669 case Py_GT: c = vv > ww; break;
670 case Py_GE: c = vv >= ww; break;
671 default:
672 result = Py_NotImplemented;
673 goto out;
675 result = c ? Py_True : Py_False;
677 /* incref and return */
678 out:
679 Py_INCREF(result);
680 return result;
683 static PyObject *
684 type_repr(PyTypeObject *type)
686 PyObject *mod, *name, *rtn;
687 char *kind;
689 mod = type_module(type, NULL);
690 if (mod == NULL)
691 PyErr_Clear();
692 else if (!PyString_Check(mod)) {
693 Py_DECREF(mod);
694 mod = NULL;
696 name = type_name(type, NULL);
697 if (name == NULL)
698 return NULL;
700 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
701 kind = "class";
702 else
703 kind = "type";
705 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
706 rtn = PyString_FromFormat("<%s '%s.%s'>",
707 kind,
708 PyString_AS_STRING(mod),
709 PyString_AS_STRING(name));
711 else
712 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
714 Py_XDECREF(mod);
715 Py_DECREF(name);
716 return rtn;
719 static PyObject *
720 type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
722 PyObject *obj;
724 if (type->tp_new == NULL) {
725 PyErr_Format(PyExc_TypeError,
726 "cannot create '%.100s' instances",
727 type->tp_name);
728 return NULL;
731 obj = type->tp_new(type, args, kwds);
732 if (obj != NULL) {
733 /* Ugly exception: when the call was type(something),
734 don't call tp_init on the result. */
735 if (type == &PyType_Type &&
736 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
737 (kwds == NULL ||
738 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
739 return obj;
740 /* If the returned object is not an instance of type,
741 it won't be initialized. */
742 if (!PyType_IsSubtype(obj->ob_type, type))
743 return obj;
744 type = obj->ob_type;
745 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
746 type->tp_init != NULL &&
747 type->tp_init(obj, args, kwds) < 0) {
748 Py_DECREF(obj);
749 obj = NULL;
752 return obj;
755 PyObject *
756 PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
758 PyObject *obj;
759 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
760 /* note that we need to add one, for the sentinel */
762 if (PyType_IS_GC(type))
763 obj = _PyObject_GC_Malloc(size);
764 else
765 obj = (PyObject *)PyObject_MALLOC(size);
767 if (obj == NULL)
768 return PyErr_NoMemory();
770 memset(obj, '\0', size);
772 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
773 Py_INCREF(type);
775 if (type->tp_itemsize == 0)
776 PyObject_INIT(obj, type);
777 else
778 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
780 if (PyType_IS_GC(type))
781 _PyObject_GC_TRACK(obj);
782 return obj;
785 PyObject *
786 PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
788 return type->tp_alloc(type, 0);
791 /* Helpers for subtyping */
793 static int
794 traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
796 Py_ssize_t i, n;
797 PyMemberDef *mp;
799 n = Py_SIZE(type);
800 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
801 for (i = 0; i < n; i++, mp++) {
802 if (mp->type == T_OBJECT_EX) {
803 char *addr = (char *)self + mp->offset;
804 PyObject *obj = *(PyObject **)addr;
805 if (obj != NULL) {
806 int err = visit(obj, arg);
807 if (err)
808 return err;
812 return 0;
815 static int
816 subtype_traverse(PyObject *self, visitproc visit, void *arg)
818 PyTypeObject *type, *base;
819 traverseproc basetraverse;
821 /* Find the nearest base with a different tp_traverse,
822 and traverse slots while we're at it */
823 type = Py_TYPE(self);
824 base = type;
825 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
826 if (Py_SIZE(base)) {
827 int err = traverse_slots(base, self, visit, arg);
828 if (err)
829 return err;
831 base = base->tp_base;
832 assert(base);
835 if (type->tp_dictoffset != base->tp_dictoffset) {
836 PyObject **dictptr = _PyObject_GetDictPtr(self);
837 if (dictptr && *dictptr)
838 Py_VISIT(*dictptr);
841 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
842 /* For a heaptype, the instances count as references
843 to the type. Traverse the type so the collector
844 can find cycles involving this link. */
845 Py_VISIT(type);
847 if (basetraverse)
848 return basetraverse(self, visit, arg);
849 return 0;
852 static void
853 clear_slots(PyTypeObject *type, PyObject *self)
855 Py_ssize_t i, n;
856 PyMemberDef *mp;
858 n = Py_SIZE(type);
859 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
860 for (i = 0; i < n; i++, mp++) {
861 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
862 char *addr = (char *)self + mp->offset;
863 PyObject *obj = *(PyObject **)addr;
864 if (obj != NULL) {
865 *(PyObject **)addr = NULL;
866 Py_DECREF(obj);
872 static int
873 subtype_clear(PyObject *self)
875 PyTypeObject *type, *base;
876 inquiry baseclear;
878 /* Find the nearest base with a different tp_clear
879 and clear slots while we're at it */
880 type = Py_TYPE(self);
881 base = type;
882 while ((baseclear = base->tp_clear) == subtype_clear) {
883 if (Py_SIZE(base))
884 clear_slots(base, self);
885 base = base->tp_base;
886 assert(base);
889 /* There's no need to clear the instance dict (if any);
890 the collector will call its tp_clear handler. */
892 if (baseclear)
893 return baseclear(self);
894 return 0;
897 static void
898 subtype_dealloc(PyObject *self)
900 PyTypeObject *type, *base;
901 destructor basedealloc;
903 /* Extract the type; we expect it to be a heap type */
904 type = Py_TYPE(self);
905 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
907 /* Test whether the type has GC exactly once */
909 if (!PyType_IS_GC(type)) {
910 /* It's really rare to find a dynamic type that doesn't have
911 GC; it can only happen when deriving from 'object' and not
912 adding any slots or instance variables. This allows
913 certain simplifications: there's no need to call
914 clear_slots(), or DECREF the dict, or clear weakrefs. */
916 /* Maybe call finalizer; exit early if resurrected */
917 if (type->tp_del) {
918 type->tp_del(self);
919 if (self->ob_refcnt > 0)
920 return;
923 /* Find the nearest base with a different tp_dealloc */
924 base = type;
925 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
926 assert(Py_SIZE(base) == 0);
927 base = base->tp_base;
928 assert(base);
931 /* Call the base tp_dealloc() */
932 assert(basedealloc);
933 basedealloc(self);
935 /* Can't reference self beyond this point */
936 Py_DECREF(type);
938 /* Done */
939 return;
942 /* We get here only if the type has GC */
944 /* UnTrack and re-Track around the trashcan macro, alas */
945 /* See explanation at end of function for full disclosure */
946 PyObject_GC_UnTrack(self);
947 ++_PyTrash_delete_nesting;
948 Py_TRASHCAN_SAFE_BEGIN(self);
949 --_PyTrash_delete_nesting;
950 /* DO NOT restore GC tracking at this point. weakref callbacks
951 * (if any, and whether directly here or indirectly in something we
952 * call) may trigger GC, and if self is tracked at that point, it
953 * will look like trash to GC and GC will try to delete self again.
956 /* Find the nearest base with a different tp_dealloc */
957 base = type;
958 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
959 base = base->tp_base;
960 assert(base);
963 /* If we added a weaklist, we clear it. Do this *before* calling
964 the finalizer (__del__), clearing slots, or clearing the instance
965 dict. */
967 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
968 PyObject_ClearWeakRefs(self);
970 /* Maybe call finalizer; exit early if resurrected */
971 if (type->tp_del) {
972 _PyObject_GC_TRACK(self);
973 type->tp_del(self);
974 if (self->ob_refcnt > 0)
975 goto endlabel; /* resurrected */
976 else
977 _PyObject_GC_UNTRACK(self);
978 /* New weakrefs could be created during the finalizer call.
979 If this occurs, clear them out without calling their
980 finalizers since they might rely on part of the object
981 being finalized that has already been destroyed. */
982 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
983 /* Modeled after GET_WEAKREFS_LISTPTR() */
984 PyWeakReference **list = (PyWeakReference **) \
985 PyObject_GET_WEAKREFS_LISTPTR(self);
986 while (*list)
987 _PyWeakref_ClearRef(*list);
991 /* Clear slots up to the nearest base with a different tp_dealloc */
992 base = type;
993 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
994 if (Py_SIZE(base))
995 clear_slots(base, self);
996 base = base->tp_base;
997 assert(base);
1000 /* If we added a dict, DECREF it */
1001 if (type->tp_dictoffset && !base->tp_dictoffset) {
1002 PyObject **dictptr = _PyObject_GetDictPtr(self);
1003 if (dictptr != NULL) {
1004 PyObject *dict = *dictptr;
1005 if (dict != NULL) {
1006 Py_DECREF(dict);
1007 *dictptr = NULL;
1012 /* Call the base tp_dealloc(); first retrack self if
1013 * basedealloc knows about gc.
1015 if (PyType_IS_GC(base))
1016 _PyObject_GC_TRACK(self);
1017 assert(basedealloc);
1018 basedealloc(self);
1020 /* Can't reference self beyond this point */
1021 Py_DECREF(type);
1023 endlabel:
1024 ++_PyTrash_delete_nesting;
1025 Py_TRASHCAN_SAFE_END(self);
1026 --_PyTrash_delete_nesting;
1028 /* Explanation of the weirdness around the trashcan macros:
1030 Q. What do the trashcan macros do?
1032 A. Read the comment titled "Trashcan mechanism" in object.h.
1033 For one, this explains why there must be a call to GC-untrack
1034 before the trashcan begin macro. Without understanding the
1035 trashcan code, the answers to the following questions don't make
1036 sense.
1038 Q. Why do we GC-untrack before the trashcan and then immediately
1039 GC-track again afterward?
1041 A. In the case that the base class is GC-aware, the base class
1042 probably GC-untracks the object. If it does that using the
1043 UNTRACK macro, this will crash when the object is already
1044 untracked. Because we don't know what the base class does, the
1045 only safe thing is to make sure the object is tracked when we
1046 call the base class dealloc. But... The trashcan begin macro
1047 requires that the object is *untracked* before it is called. So
1048 the dance becomes:
1050 GC untrack
1051 trashcan begin
1052 GC track
1054 Q. Why did the last question say "immediately GC-track again"?
1055 It's nowhere near immediately.
1057 A. Because the code *used* to re-track immediately. Bad Idea.
1058 self has a refcount of 0, and if gc ever gets its hands on it
1059 (which can happen if any weakref callback gets invoked), it
1060 looks like trash to gc too, and gc also tries to delete self
1061 then. But we're already deleting self. Double dealloction is
1062 a subtle disaster.
1064 Q. Why the bizarre (net-zero) manipulation of
1065 _PyTrash_delete_nesting around the trashcan macros?
1067 A. Some base classes (e.g. list) also use the trashcan mechanism.
1068 The following scenario used to be possible:
1070 - suppose the trashcan level is one below the trashcan limit
1072 - subtype_dealloc() is called
1074 - the trashcan limit is not yet reached, so the trashcan level
1075 is incremented and the code between trashcan begin and end is
1076 executed
1078 - this destroys much of the object's contents, including its
1079 slots and __dict__
1081 - basedealloc() is called; this is really list_dealloc(), or
1082 some other type which also uses the trashcan macros
1084 - the trashcan limit is now reached, so the object is put on the
1085 trashcan's to-be-deleted-later list
1087 - basedealloc() returns
1089 - subtype_dealloc() decrefs the object's type
1091 - subtype_dealloc() returns
1093 - later, the trashcan code starts deleting the objects from its
1094 to-be-deleted-later list
1096 - subtype_dealloc() is called *AGAIN* for the same object
1098 - at the very least (if the destroyed slots and __dict__ don't
1099 cause problems) the object's type gets decref'ed a second
1100 time, which is *BAD*!!!
1102 The remedy is to make sure that if the code between trashcan
1103 begin and end in subtype_dealloc() is called, the code between
1104 trashcan begin and end in basedealloc() will also be called.
1105 This is done by decrementing the level after passing into the
1106 trashcan block, and incrementing it just before leaving the
1107 block.
1109 But now it's possible that a chain of objects consisting solely
1110 of objects whose deallocator is subtype_dealloc() will defeat
1111 the trashcan mechanism completely: the decremented level means
1112 that the effective level never reaches the limit. Therefore, we
1113 *increment* the level *before* entering the trashcan block, and
1114 matchingly decrement it after leaving. This means the trashcan
1115 code will trigger a little early, but that's no big deal.
1117 Q. Are there any live examples of code in need of all this
1118 complexity?
1120 A. Yes. See SF bug 668433 for code that crashed (when Python was
1121 compiled in debug mode) before the trashcan level manipulations
1122 were added. For more discussion, see SF patches 581742, 575073
1123 and bug 574207.
1127 static PyTypeObject *solid_base(PyTypeObject *type);
1129 /* type test with subclassing support */
1132 PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1134 PyObject *mro;
1136 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1137 return b == a || b == &PyBaseObject_Type;
1139 mro = a->tp_mro;
1140 if (mro != NULL) {
1141 /* Deal with multiple inheritance without recursion
1142 by walking the MRO tuple */
1143 Py_ssize_t i, n;
1144 assert(PyTuple_Check(mro));
1145 n = PyTuple_GET_SIZE(mro);
1146 for (i = 0; i < n; i++) {
1147 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1148 return 1;
1150 return 0;
1152 else {
1153 /* a is not completely initilized yet; follow tp_base */
1154 do {
1155 if (a == b)
1156 return 1;
1157 a = a->tp_base;
1158 } while (a != NULL);
1159 return b == &PyBaseObject_Type;
1163 /* Internal routines to do a method lookup in the type
1164 without looking in the instance dictionary
1165 (so we can't use PyObject_GetAttr) but still binding
1166 it to the instance. The arguments are the object,
1167 the method name as a C string, and the address of a
1168 static variable used to cache the interned Python string.
1170 Two variants:
1172 - lookup_maybe() returns NULL without raising an exception
1173 when the _PyType_Lookup() call fails;
1175 - lookup_method() always raises an exception upon errors.
1178 static PyObject *
1179 lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
1181 PyObject *res;
1183 if (*attrobj == NULL) {
1184 *attrobj = PyString_InternFromString(attrstr);
1185 if (*attrobj == NULL)
1186 return NULL;
1188 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1189 if (res != NULL) {
1190 descrgetfunc f;
1191 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1192 Py_INCREF(res);
1193 else
1194 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1196 return res;
1199 static PyObject *
1200 lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1202 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1203 if (res == NULL && !PyErr_Occurred())
1204 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1205 return res;
1208 /* A variation of PyObject_CallMethod that uses lookup_method()
1209 instead of PyObject_GetAttrString(). This uses the same convention
1210 as lookup_method to cache the interned name string object. */
1212 static PyObject *
1213 call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1215 va_list va;
1216 PyObject *args, *func = 0, *retval;
1217 va_start(va, format);
1219 func = lookup_maybe(o, name, nameobj);
1220 if (func == NULL) {
1221 va_end(va);
1222 if (!PyErr_Occurred())
1223 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1224 return NULL;
1227 if (format && *format)
1228 args = Py_VaBuildValue(format, va);
1229 else
1230 args = PyTuple_New(0);
1232 va_end(va);
1234 if (args == NULL)
1235 return NULL;
1237 assert(PyTuple_Check(args));
1238 retval = PyObject_Call(func, args, NULL);
1240 Py_DECREF(args);
1241 Py_DECREF(func);
1243 return retval;
1246 /* Clone of call_method() that returns NotImplemented when the lookup fails. */
1248 static PyObject *
1249 call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1251 va_list va;
1252 PyObject *args, *func = 0, *retval;
1253 va_start(va, format);
1255 func = lookup_maybe(o, name, nameobj);
1256 if (func == NULL) {
1257 va_end(va);
1258 if (!PyErr_Occurred()) {
1259 Py_INCREF(Py_NotImplemented);
1260 return Py_NotImplemented;
1262 return NULL;
1265 if (format && *format)
1266 args = Py_VaBuildValue(format, va);
1267 else
1268 args = PyTuple_New(0);
1270 va_end(va);
1272 if (args == NULL)
1273 return NULL;
1275 assert(PyTuple_Check(args));
1276 retval = PyObject_Call(func, args, NULL);
1278 Py_DECREF(args);
1279 Py_DECREF(func);
1281 return retval;
1284 static int
1285 fill_classic_mro(PyObject *mro, PyObject *cls)
1287 PyObject *bases, *base;
1288 Py_ssize_t i, n;
1290 assert(PyList_Check(mro));
1291 assert(PyClass_Check(cls));
1292 i = PySequence_Contains(mro, cls);
1293 if (i < 0)
1294 return -1;
1295 if (!i) {
1296 if (PyList_Append(mro, cls) < 0)
1297 return -1;
1299 bases = ((PyClassObject *)cls)->cl_bases;
1300 assert(bases && PyTuple_Check(bases));
1301 n = PyTuple_GET_SIZE(bases);
1302 for (i = 0; i < n; i++) {
1303 base = PyTuple_GET_ITEM(bases, i);
1304 if (fill_classic_mro(mro, base) < 0)
1305 return -1;
1307 return 0;
1310 static PyObject *
1311 classic_mro(PyObject *cls)
1313 PyObject *mro;
1315 assert(PyClass_Check(cls));
1316 mro = PyList_New(0);
1317 if (mro != NULL) {
1318 if (fill_classic_mro(mro, cls) == 0)
1319 return mro;
1320 Py_DECREF(mro);
1322 return NULL;
1326 Method resolution order algorithm C3 described in
1327 "A Monotonic Superclass Linearization for Dylan",
1328 by Kim Barrett, Bob Cassel, Paul Haahr,
1329 David A. Moon, Keith Playford, and P. Tucker Withington.
1330 (OOPSLA 1996)
1332 Some notes about the rules implied by C3:
1334 No duplicate bases.
1335 It isn't legal to repeat a class in a list of base classes.
1337 The next three properties are the 3 constraints in "C3".
1339 Local precendece order.
1340 If A precedes B in C's MRO, then A will precede B in the MRO of all
1341 subclasses of C.
1343 Monotonicity.
1344 The MRO of a class must be an extension without reordering of the
1345 MRO of each of its superclasses.
1347 Extended Precedence Graph (EPG).
1348 Linearization is consistent if there is a path in the EPG from
1349 each class to all its successors in the linearization. See
1350 the paper for definition of EPG.
1353 static int
1354 tail_contains(PyObject *list, int whence, PyObject *o) {
1355 Py_ssize_t j, size;
1356 size = PyList_GET_SIZE(list);
1358 for (j = whence+1; j < size; j++) {
1359 if (PyList_GET_ITEM(list, j) == o)
1360 return 1;
1362 return 0;
1365 static PyObject *
1366 class_name(PyObject *cls)
1368 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1369 if (name == NULL) {
1370 PyErr_Clear();
1371 Py_XDECREF(name);
1372 name = PyObject_Repr(cls);
1374 if (name == NULL)
1375 return NULL;
1376 if (!PyString_Check(name)) {
1377 Py_DECREF(name);
1378 return NULL;
1380 return name;
1383 static int
1384 check_duplicates(PyObject *list)
1386 Py_ssize_t i, j, n;
1387 /* Let's use a quadratic time algorithm,
1388 assuming that the bases lists is short.
1390 n = PyList_GET_SIZE(list);
1391 for (i = 0; i < n; i++) {
1392 PyObject *o = PyList_GET_ITEM(list, i);
1393 for (j = i + 1; j < n; j++) {
1394 if (PyList_GET_ITEM(list, j) == o) {
1395 o = class_name(o);
1396 PyErr_Format(PyExc_TypeError,
1397 "duplicate base class %s",
1398 o ? PyString_AS_STRING(o) : "?");
1399 Py_XDECREF(o);
1400 return -1;
1404 return 0;
1407 /* Raise a TypeError for an MRO order disagreement.
1409 It's hard to produce a good error message. In the absence of better
1410 insight into error reporting, report the classes that were candidates
1411 to be put next into the MRO. There is some conflict between the
1412 order in which they should be put in the MRO, but it's hard to
1413 diagnose what constraint can't be satisfied.
1416 static void
1417 set_mro_error(PyObject *to_merge, int *remain)
1419 Py_ssize_t i, n, off, to_merge_size;
1420 char buf[1000];
1421 PyObject *k, *v;
1422 PyObject *set = PyDict_New();
1423 if (!set) return;
1425 to_merge_size = PyList_GET_SIZE(to_merge);
1426 for (i = 0; i < to_merge_size; i++) {
1427 PyObject *L = PyList_GET_ITEM(to_merge, i);
1428 if (remain[i] < PyList_GET_SIZE(L)) {
1429 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1430 if (PyDict_SetItem(set, c, Py_None) < 0) {
1431 Py_DECREF(set);
1432 return;
1436 n = PyDict_Size(set);
1438 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1439 consistent method resolution\norder (MRO) for bases");
1440 i = 0;
1441 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1442 PyObject *name = class_name(k);
1443 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1444 name ? PyString_AS_STRING(name) : "?");
1445 Py_XDECREF(name);
1446 if (--n && (size_t)(off+1) < sizeof(buf)) {
1447 buf[off++] = ',';
1448 buf[off] = '\0';
1451 PyErr_SetString(PyExc_TypeError, buf);
1452 Py_DECREF(set);
1455 static int
1456 pmerge(PyObject *acc, PyObject* to_merge) {
1457 Py_ssize_t i, j, to_merge_size, empty_cnt;
1458 int *remain;
1459 int ok;
1461 to_merge_size = PyList_GET_SIZE(to_merge);
1463 /* remain stores an index into each sublist of to_merge.
1464 remain[i] is the index of the next base in to_merge[i]
1465 that is not included in acc.
1467 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1468 if (remain == NULL)
1469 return -1;
1470 for (i = 0; i < to_merge_size; i++)
1471 remain[i] = 0;
1473 again:
1474 empty_cnt = 0;
1475 for (i = 0; i < to_merge_size; i++) {
1476 PyObject *candidate;
1478 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1480 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1481 empty_cnt++;
1482 continue;
1485 /* Choose next candidate for MRO.
1487 The input sequences alone can determine the choice.
1488 If not, choose the class which appears in the MRO
1489 of the earliest direct superclass of the new class.
1492 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1493 for (j = 0; j < to_merge_size; j++) {
1494 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1495 if (tail_contains(j_lst, remain[j], candidate)) {
1496 goto skip; /* continue outer loop */
1499 ok = PyList_Append(acc, candidate);
1500 if (ok < 0) {
1501 PyMem_Free(remain);
1502 return -1;
1504 for (j = 0; j < to_merge_size; j++) {
1505 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1506 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1507 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1508 remain[j]++;
1511 goto again;
1512 skip: ;
1515 if (empty_cnt == to_merge_size) {
1516 PyMem_FREE(remain);
1517 return 0;
1519 set_mro_error(to_merge, remain);
1520 PyMem_FREE(remain);
1521 return -1;
1524 static PyObject *
1525 mro_implementation(PyTypeObject *type)
1527 Py_ssize_t i, n;
1528 int ok;
1529 PyObject *bases, *result;
1530 PyObject *to_merge, *bases_aslist;
1532 if (type->tp_dict == NULL) {
1533 if (PyType_Ready(type) < 0)
1534 return NULL;
1537 /* Find a superclass linearization that honors the constraints
1538 of the explicit lists of bases and the constraints implied by
1539 each base class.
1541 to_merge is a list of lists, where each list is a superclass
1542 linearization implied by a base class. The last element of
1543 to_merge is the declared list of bases.
1546 bases = type->tp_bases;
1547 n = PyTuple_GET_SIZE(bases);
1549 to_merge = PyList_New(n+1);
1550 if (to_merge == NULL)
1551 return NULL;
1553 for (i = 0; i < n; i++) {
1554 PyObject *base = PyTuple_GET_ITEM(bases, i);
1555 PyObject *parentMRO;
1556 if (PyType_Check(base))
1557 parentMRO = PySequence_List(
1558 ((PyTypeObject*)base)->tp_mro);
1559 else
1560 parentMRO = classic_mro(base);
1561 if (parentMRO == NULL) {
1562 Py_DECREF(to_merge);
1563 return NULL;
1566 PyList_SET_ITEM(to_merge, i, parentMRO);
1569 bases_aslist = PySequence_List(bases);
1570 if (bases_aslist == NULL) {
1571 Py_DECREF(to_merge);
1572 return NULL;
1574 /* This is just a basic sanity check. */
1575 if (check_duplicates(bases_aslist) < 0) {
1576 Py_DECREF(to_merge);
1577 Py_DECREF(bases_aslist);
1578 return NULL;
1580 PyList_SET_ITEM(to_merge, n, bases_aslist);
1582 result = Py_BuildValue("[O]", (PyObject *)type);
1583 if (result == NULL) {
1584 Py_DECREF(to_merge);
1585 return NULL;
1588 ok = pmerge(result, to_merge);
1589 Py_DECREF(to_merge);
1590 if (ok < 0) {
1591 Py_DECREF(result);
1592 return NULL;
1595 return result;
1598 static PyObject *
1599 mro_external(PyObject *self)
1601 PyTypeObject *type = (PyTypeObject *)self;
1603 return mro_implementation(type);
1606 static int
1607 mro_internal(PyTypeObject *type)
1609 PyObject *mro, *result, *tuple;
1610 int checkit = 0;
1612 if (Py_TYPE(type) == &PyType_Type) {
1613 result = mro_implementation(type);
1615 else {
1616 static PyObject *mro_str;
1617 checkit = 1;
1618 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1619 if (mro == NULL)
1620 return -1;
1621 result = PyObject_CallObject(mro, NULL);
1622 Py_DECREF(mro);
1624 if (result == NULL)
1625 return -1;
1626 tuple = PySequence_Tuple(result);
1627 Py_DECREF(result);
1628 if (tuple == NULL)
1629 return -1;
1630 if (checkit) {
1631 Py_ssize_t i, len;
1632 PyObject *cls;
1633 PyTypeObject *solid;
1635 solid = solid_base(type);
1637 len = PyTuple_GET_SIZE(tuple);
1639 for (i = 0; i < len; i++) {
1640 PyTypeObject *t;
1641 cls = PyTuple_GET_ITEM(tuple, i);
1642 if (PyClass_Check(cls))
1643 continue;
1644 else if (!PyType_Check(cls)) {
1645 PyErr_Format(PyExc_TypeError,
1646 "mro() returned a non-class ('%.500s')",
1647 Py_TYPE(cls)->tp_name);
1648 Py_DECREF(tuple);
1649 return -1;
1651 t = (PyTypeObject*)cls;
1652 if (!PyType_IsSubtype(solid, solid_base(t))) {
1653 PyErr_Format(PyExc_TypeError,
1654 "mro() returned base with unsuitable layout ('%.500s')",
1655 t->tp_name);
1656 Py_DECREF(tuple);
1657 return -1;
1661 type->tp_mro = tuple;
1663 type_mro_modified(type, type->tp_mro);
1664 /* corner case: the old-style super class might have been hidden
1665 from the custom MRO */
1666 type_mro_modified(type, type->tp_bases);
1668 PyType_Modified(type);
1670 return 0;
1674 /* Calculate the best base amongst multiple base classes.
1675 This is the first one that's on the path to the "solid base". */
1677 static PyTypeObject *
1678 best_base(PyObject *bases)
1680 Py_ssize_t i, n;
1681 PyTypeObject *base, *winner, *candidate, *base_i;
1682 PyObject *base_proto;
1684 assert(PyTuple_Check(bases));
1685 n = PyTuple_GET_SIZE(bases);
1686 assert(n > 0);
1687 base = NULL;
1688 winner = NULL;
1689 for (i = 0; i < n; i++) {
1690 base_proto = PyTuple_GET_ITEM(bases, i);
1691 if (PyClass_Check(base_proto))
1692 continue;
1693 if (!PyType_Check(base_proto)) {
1694 PyErr_SetString(
1695 PyExc_TypeError,
1696 "bases must be types");
1697 return NULL;
1699 base_i = (PyTypeObject *)base_proto;
1700 if (base_i->tp_dict == NULL) {
1701 if (PyType_Ready(base_i) < 0)
1702 return NULL;
1704 candidate = solid_base(base_i);
1705 if (winner == NULL) {
1706 winner = candidate;
1707 base = base_i;
1709 else if (PyType_IsSubtype(winner, candidate))
1711 else if (PyType_IsSubtype(candidate, winner)) {
1712 winner = candidate;
1713 base = base_i;
1715 else {
1716 PyErr_SetString(
1717 PyExc_TypeError,
1718 "multiple bases have "
1719 "instance lay-out conflict");
1720 return NULL;
1723 if (base == NULL)
1724 PyErr_SetString(PyExc_TypeError,
1725 "a new-style class can't have only classic bases");
1726 return base;
1729 static int
1730 extra_ivars(PyTypeObject *type, PyTypeObject *base)
1732 size_t t_size = type->tp_basicsize;
1733 size_t b_size = base->tp_basicsize;
1735 assert(t_size >= b_size); /* Else type smaller than base! */
1736 if (type->tp_itemsize || base->tp_itemsize) {
1737 /* If itemsize is involved, stricter rules */
1738 return t_size != b_size ||
1739 type->tp_itemsize != base->tp_itemsize;
1741 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1742 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1743 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1744 t_size -= sizeof(PyObject *);
1745 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1746 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1747 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1748 t_size -= sizeof(PyObject *);
1750 return t_size != b_size;
1753 static PyTypeObject *
1754 solid_base(PyTypeObject *type)
1756 PyTypeObject *base;
1758 if (type->tp_base)
1759 base = solid_base(type->tp_base);
1760 else
1761 base = &PyBaseObject_Type;
1762 if (extra_ivars(type, base))
1763 return type;
1764 else
1765 return base;
1768 static void object_dealloc(PyObject *);
1769 static int object_init(PyObject *, PyObject *, PyObject *);
1770 static int update_slot(PyTypeObject *, PyObject *);
1771 static void fixup_slot_dispatchers(PyTypeObject *);
1774 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1775 * inherited from various builtin types. The builtin base usually provides
1776 * its own __dict__ descriptor, so we use that when we can.
1778 static PyTypeObject *
1779 get_builtin_base_with_dict(PyTypeObject *type)
1781 while (type->tp_base != NULL) {
1782 if (type->tp_dictoffset != 0 &&
1783 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1784 return type;
1785 type = type->tp_base;
1787 return NULL;
1790 static PyObject *
1791 get_dict_descriptor(PyTypeObject *type)
1793 static PyObject *dict_str;
1794 PyObject *descr;
1796 if (dict_str == NULL) {
1797 dict_str = PyString_InternFromString("__dict__");
1798 if (dict_str == NULL)
1799 return NULL;
1801 descr = _PyType_Lookup(type, dict_str);
1802 if (descr == NULL || !PyDescr_IsData(descr))
1803 return NULL;
1805 return descr;
1808 static void
1809 raise_dict_descr_error(PyObject *obj)
1811 PyErr_Format(PyExc_TypeError,
1812 "this __dict__ descriptor does not support "
1813 "'%.200s' objects", obj->ob_type->tp_name);
1816 static PyObject *
1817 subtype_dict(PyObject *obj, void *context)
1819 PyObject **dictptr;
1820 PyObject *dict;
1821 PyTypeObject *base;
1823 base = get_builtin_base_with_dict(obj->ob_type);
1824 if (base != NULL) {
1825 descrgetfunc func;
1826 PyObject *descr = get_dict_descriptor(base);
1827 if (descr == NULL) {
1828 raise_dict_descr_error(obj);
1829 return NULL;
1831 func = descr->ob_type->tp_descr_get;
1832 if (func == NULL) {
1833 raise_dict_descr_error(obj);
1834 return NULL;
1836 return func(descr, obj, (PyObject *)(obj->ob_type));
1839 dictptr = _PyObject_GetDictPtr(obj);
1840 if (dictptr == NULL) {
1841 PyErr_SetString(PyExc_AttributeError,
1842 "This object has no __dict__");
1843 return NULL;
1845 dict = *dictptr;
1846 if (dict == NULL)
1847 *dictptr = dict = PyDict_New();
1848 Py_XINCREF(dict);
1849 return dict;
1852 static int
1853 subtype_setdict(PyObject *obj, PyObject *value, void *context)
1855 PyObject **dictptr;
1856 PyObject *dict;
1857 PyTypeObject *base;
1859 base = get_builtin_base_with_dict(obj->ob_type);
1860 if (base != NULL) {
1861 descrsetfunc func;
1862 PyObject *descr = get_dict_descriptor(base);
1863 if (descr == NULL) {
1864 raise_dict_descr_error(obj);
1865 return -1;
1867 func = descr->ob_type->tp_descr_set;
1868 if (func == NULL) {
1869 raise_dict_descr_error(obj);
1870 return -1;
1872 return func(descr, obj, value);
1875 dictptr = _PyObject_GetDictPtr(obj);
1876 if (dictptr == NULL) {
1877 PyErr_SetString(PyExc_AttributeError,
1878 "This object has no __dict__");
1879 return -1;
1881 if (value != NULL && !PyDict_Check(value)) {
1882 PyErr_Format(PyExc_TypeError,
1883 "__dict__ must be set to a dictionary, "
1884 "not a '%.200s'", Py_TYPE(value)->tp_name);
1885 return -1;
1887 dict = *dictptr;
1888 Py_XINCREF(value);
1889 *dictptr = value;
1890 Py_XDECREF(dict);
1891 return 0;
1894 static PyObject *
1895 subtype_getweakref(PyObject *obj, void *context)
1897 PyObject **weaklistptr;
1898 PyObject *result;
1900 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1901 PyErr_SetString(PyExc_AttributeError,
1902 "This object has no __weakref__");
1903 return NULL;
1905 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1906 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1907 (size_t)(Py_TYPE(obj)->tp_basicsize));
1908 weaklistptr = (PyObject **)
1909 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1910 if (*weaklistptr == NULL)
1911 result = Py_None;
1912 else
1913 result = *weaklistptr;
1914 Py_INCREF(result);
1915 return result;
1918 /* Three variants on the subtype_getsets list. */
1920 static PyGetSetDef subtype_getsets_full[] = {
1921 {"__dict__", subtype_dict, subtype_setdict,
1922 PyDoc_STR("dictionary for instance variables (if defined)")},
1923 {"__weakref__", subtype_getweakref, NULL,
1924 PyDoc_STR("list of weak references to the object (if defined)")},
1928 static PyGetSetDef subtype_getsets_dict_only[] = {
1929 {"__dict__", subtype_dict, subtype_setdict,
1930 PyDoc_STR("dictionary for instance variables (if defined)")},
1934 static PyGetSetDef subtype_getsets_weakref_only[] = {
1935 {"__weakref__", subtype_getweakref, NULL,
1936 PyDoc_STR("list of weak references to the object (if defined)")},
1940 static int
1941 valid_identifier(PyObject *s)
1943 unsigned char *p;
1944 Py_ssize_t i, n;
1946 if (!PyString_Check(s)) {
1947 PyErr_Format(PyExc_TypeError,
1948 "__slots__ items must be strings, not '%.200s'",
1949 Py_TYPE(s)->tp_name);
1950 return 0;
1952 p = (unsigned char *) PyString_AS_STRING(s);
1953 n = PyString_GET_SIZE(s);
1954 /* We must reject an empty name. As a hack, we bump the
1955 length to 1 so that the loop will balk on the trailing \0. */
1956 if (n == 0)
1957 n = 1;
1958 for (i = 0; i < n; i++, p++) {
1959 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1960 PyErr_SetString(PyExc_TypeError,
1961 "__slots__ must be identifiers");
1962 return 0;
1965 return 1;
1968 #ifdef Py_USING_UNICODE
1969 /* Replace Unicode objects in slots. */
1971 static PyObject *
1972 _unicode_to_string(PyObject *slots, Py_ssize_t nslots)
1974 PyObject *tmp = NULL;
1975 PyObject *slot_name, *new_name;
1976 Py_ssize_t i;
1978 for (i = 0; i < nslots; i++) {
1979 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1980 if (tmp == NULL) {
1981 tmp = PySequence_List(slots);
1982 if (tmp == NULL)
1983 return NULL;
1985 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1986 NULL);
1987 if (new_name == NULL) {
1988 Py_DECREF(tmp);
1989 return NULL;
1991 Py_INCREF(new_name);
1992 PyList_SET_ITEM(tmp, i, new_name);
1993 Py_DECREF(slot_name);
1996 if (tmp != NULL) {
1997 slots = PyList_AsTuple(tmp);
1998 Py_DECREF(tmp);
2000 return slots;
2002 #endif
2004 /* Forward */
2005 static int
2006 object_init(PyObject *self, PyObject *args, PyObject *kwds);
2008 static int
2009 type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2011 int res;
2013 assert(args != NULL && PyTuple_Check(args));
2014 assert(kwds == NULL || PyDict_Check(kwds));
2016 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2017 PyErr_SetString(PyExc_TypeError,
2018 "type.__init__() takes no keyword arguments");
2019 return -1;
2022 if (args != NULL && PyTuple_Check(args) &&
2023 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2024 PyErr_SetString(PyExc_TypeError,
2025 "type.__init__() takes 1 or 3 arguments");
2026 return -1;
2029 /* Call object.__init__(self) now. */
2030 /* XXX Could call super(type, cls).__init__() but what's the point? */
2031 args = PyTuple_GetSlice(args, 0, 0);
2032 res = object_init(cls, args, NULL);
2033 Py_DECREF(args);
2034 return res;
2037 static PyObject *
2038 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2040 PyObject *name, *bases, *dict;
2041 static char *kwlist[] = {"name", "bases", "dict", 0};
2042 PyObject *slots, *tmp, *newslots;
2043 PyTypeObject *type, *base, *tmptype, *winner;
2044 PyHeapTypeObject *et;
2045 PyMemberDef *mp;
2046 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
2047 int j, may_add_dict, may_add_weak;
2049 assert(args != NULL && PyTuple_Check(args));
2050 assert(kwds == NULL || PyDict_Check(kwds));
2052 /* Special case: type(x) should return x->ob_type */
2054 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2055 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
2057 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2058 PyObject *x = PyTuple_GET_ITEM(args, 0);
2059 Py_INCREF(Py_TYPE(x));
2060 return (PyObject *) Py_TYPE(x);
2063 /* SF bug 475327 -- if that didn't trigger, we need 3
2064 arguments. but PyArg_ParseTupleAndKeywords below may give
2065 a msg saying type() needs exactly 3. */
2066 if (nargs + nkwds != 3) {
2067 PyErr_SetString(PyExc_TypeError,
2068 "type() takes 1 or 3 arguments");
2069 return NULL;
2073 /* Check arguments: (name, bases, dict) */
2074 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
2075 &name,
2076 &PyTuple_Type, &bases,
2077 &PyDict_Type, &dict))
2078 return NULL;
2080 /* Determine the proper metatype to deal with this,
2081 and check for metatype conflicts while we're at it.
2082 Note that if some other metatype wins to contract,
2083 it's possible that its instances are not types. */
2084 nbases = PyTuple_GET_SIZE(bases);
2085 winner = metatype;
2086 for (i = 0; i < nbases; i++) {
2087 tmp = PyTuple_GET_ITEM(bases, i);
2088 tmptype = tmp->ob_type;
2089 if (tmptype == &PyClass_Type)
2090 continue; /* Special case classic classes */
2091 if (PyType_IsSubtype(winner, tmptype))
2092 continue;
2093 if (PyType_IsSubtype(tmptype, winner)) {
2094 winner = tmptype;
2095 continue;
2097 PyErr_SetString(PyExc_TypeError,
2098 "metaclass conflict: "
2099 "the metaclass of a derived class "
2100 "must be a (non-strict) subclass "
2101 "of the metaclasses of all its bases");
2102 return NULL;
2104 if (winner != metatype) {
2105 if (winner->tp_new != type_new) /* Pass it to the winner */
2106 return winner->tp_new(winner, args, kwds);
2107 metatype = winner;
2110 /* Adjust for empty tuple bases */
2111 if (nbases == 0) {
2112 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2113 if (bases == NULL)
2114 return NULL;
2115 nbases = 1;
2117 else
2118 Py_INCREF(bases);
2120 /* XXX From here until type is allocated, "return NULL" leaks bases! */
2122 /* Calculate best base, and check that all bases are type objects */
2123 base = best_base(bases);
2124 if (base == NULL) {
2125 Py_DECREF(bases);
2126 return NULL;
2128 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2129 PyErr_Format(PyExc_TypeError,
2130 "type '%.100s' is not an acceptable base type",
2131 base->tp_name);
2132 Py_DECREF(bases);
2133 return NULL;
2136 /* Check for a __slots__ sequence variable in dict, and count it */
2137 slots = PyDict_GetItemString(dict, "__slots__");
2138 nslots = 0;
2139 add_dict = 0;
2140 add_weak = 0;
2141 may_add_dict = base->tp_dictoffset == 0;
2142 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2143 if (slots == NULL) {
2144 if (may_add_dict) {
2145 add_dict++;
2147 if (may_add_weak) {
2148 add_weak++;
2151 else {
2152 /* Have slots */
2154 /* Make it into a tuple */
2155 if (PyString_Check(slots) || PyUnicode_Check(slots))
2156 slots = PyTuple_Pack(1, slots);
2157 else
2158 slots = PySequence_Tuple(slots);
2159 if (slots == NULL) {
2160 Py_DECREF(bases);
2161 return NULL;
2163 assert(PyTuple_Check(slots));
2165 /* Are slots allowed? */
2166 nslots = PyTuple_GET_SIZE(slots);
2167 if (nslots > 0 && base->tp_itemsize != 0) {
2168 PyErr_Format(PyExc_TypeError,
2169 "nonempty __slots__ "
2170 "not supported for subtype of '%s'",
2171 base->tp_name);
2172 bad_slots:
2173 Py_DECREF(bases);
2174 Py_DECREF(slots);
2175 return NULL;
2178 #ifdef Py_USING_UNICODE
2179 tmp = _unicode_to_string(slots, nslots);
2180 if (tmp == NULL)
2181 goto bad_slots;
2182 if (tmp != slots) {
2183 Py_DECREF(slots);
2184 slots = tmp;
2186 #endif
2187 /* Check for valid slot names and two special cases */
2188 for (i = 0; i < nslots; i++) {
2189 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2190 char *s;
2191 if (!valid_identifier(tmp))
2192 goto bad_slots;
2193 assert(PyString_Check(tmp));
2194 s = PyString_AS_STRING(tmp);
2195 if (strcmp(s, "__dict__") == 0) {
2196 if (!may_add_dict || add_dict) {
2197 PyErr_SetString(PyExc_TypeError,
2198 "__dict__ slot disallowed: "
2199 "we already got one");
2200 goto bad_slots;
2202 add_dict++;
2204 if (strcmp(s, "__weakref__") == 0) {
2205 if (!may_add_weak || add_weak) {
2206 PyErr_SetString(PyExc_TypeError,
2207 "__weakref__ slot disallowed: "
2208 "either we already got one, "
2209 "or __itemsize__ != 0");
2210 goto bad_slots;
2212 add_weak++;
2216 /* Copy slots into a list, mangle names and sort them.
2217 Sorted names are needed for __class__ assignment.
2218 Convert them back to tuple at the end.
2220 newslots = PyList_New(nslots - add_dict - add_weak);
2221 if (newslots == NULL)
2222 goto bad_slots;
2223 for (i = j = 0; i < nslots; i++) {
2224 char *s;
2225 tmp = PyTuple_GET_ITEM(slots, i);
2226 s = PyString_AS_STRING(tmp);
2227 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2228 (add_weak && strcmp(s, "__weakref__") == 0))
2229 continue;
2230 tmp =_Py_Mangle(name, tmp);
2231 if (!tmp)
2232 goto bad_slots;
2233 PyList_SET_ITEM(newslots, j, tmp);
2234 j++;
2236 assert(j == nslots - add_dict - add_weak);
2237 nslots = j;
2238 Py_DECREF(slots);
2239 if (PyList_Sort(newslots) == -1) {
2240 Py_DECREF(bases);
2241 Py_DECREF(newslots);
2242 return NULL;
2244 slots = PyList_AsTuple(newslots);
2245 Py_DECREF(newslots);
2246 if (slots == NULL) {
2247 Py_DECREF(bases);
2248 return NULL;
2251 /* Secondary bases may provide weakrefs or dict */
2252 if (nbases > 1 &&
2253 ((may_add_dict && !add_dict) ||
2254 (may_add_weak && !add_weak))) {
2255 for (i = 0; i < nbases; i++) {
2256 tmp = PyTuple_GET_ITEM(bases, i);
2257 if (tmp == (PyObject *)base)
2258 continue; /* Skip primary base */
2259 if (PyClass_Check(tmp)) {
2260 /* Classic base class provides both */
2261 if (may_add_dict && !add_dict)
2262 add_dict++;
2263 if (may_add_weak && !add_weak)
2264 add_weak++;
2265 break;
2267 assert(PyType_Check(tmp));
2268 tmptype = (PyTypeObject *)tmp;
2269 if (may_add_dict && !add_dict &&
2270 tmptype->tp_dictoffset != 0)
2271 add_dict++;
2272 if (may_add_weak && !add_weak &&
2273 tmptype->tp_weaklistoffset != 0)
2274 add_weak++;
2275 if (may_add_dict && !add_dict)
2276 continue;
2277 if (may_add_weak && !add_weak)
2278 continue;
2279 /* Nothing more to check */
2280 break;
2285 /* XXX From here until type is safely allocated,
2286 "return NULL" may leak slots! */
2288 /* Allocate the type object */
2289 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2290 if (type == NULL) {
2291 Py_XDECREF(slots);
2292 Py_DECREF(bases);
2293 return NULL;
2296 /* Keep name and slots alive in the extended type object */
2297 et = (PyHeapTypeObject *)type;
2298 Py_INCREF(name);
2299 et->ht_name = name;
2300 et->ht_slots = slots;
2302 /* Initialize tp_flags */
2303 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2304 Py_TPFLAGS_BASETYPE;
2305 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2306 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2308 /* It's a new-style number unless it specifically inherits any
2309 old-style numeric behavior */
2310 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2311 (base->tp_as_number == NULL))
2312 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2314 /* Initialize essential fields */
2315 type->tp_as_number = &et->as_number;
2316 type->tp_as_sequence = &et->as_sequence;
2317 type->tp_as_mapping = &et->as_mapping;
2318 type->tp_as_buffer = &et->as_buffer;
2319 type->tp_name = PyString_AS_STRING(name);
2321 /* Set tp_base and tp_bases */
2322 type->tp_bases = bases;
2323 Py_INCREF(base);
2324 type->tp_base = base;
2326 /* Initialize tp_dict from passed-in dict */
2327 type->tp_dict = dict = PyDict_Copy(dict);
2328 if (dict == NULL) {
2329 Py_DECREF(type);
2330 return NULL;
2333 /* Set __module__ in the dict */
2334 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2335 tmp = PyEval_GetGlobals();
2336 if (tmp != NULL) {
2337 tmp = PyDict_GetItemString(tmp, "__name__");
2338 if (tmp != NULL) {
2339 if (PyDict_SetItemString(dict, "__module__",
2340 tmp) < 0)
2341 return NULL;
2346 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2347 and is a string. The __doc__ accessor will first look for tp_doc;
2348 if that fails, it will still look into __dict__.
2351 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2352 if (doc != NULL && PyString_Check(doc)) {
2353 const size_t n = (size_t)PyString_GET_SIZE(doc);
2354 char *tp_doc = (char *)PyObject_MALLOC(n+1);
2355 if (tp_doc == NULL) {
2356 Py_DECREF(type);
2357 return NULL;
2359 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
2360 type->tp_doc = tp_doc;
2364 /* Special-case __new__: if it's a plain function,
2365 make it a static function */
2366 tmp = PyDict_GetItemString(dict, "__new__");
2367 if (tmp != NULL && PyFunction_Check(tmp)) {
2368 tmp = PyStaticMethod_New(tmp);
2369 if (tmp == NULL) {
2370 Py_DECREF(type);
2371 return NULL;
2373 PyDict_SetItemString(dict, "__new__", tmp);
2374 Py_DECREF(tmp);
2377 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2378 mp = PyHeapType_GET_MEMBERS(et);
2379 slotoffset = base->tp_basicsize;
2380 if (slots != NULL) {
2381 for (i = 0; i < nslots; i++, mp++) {
2382 mp->name = PyString_AS_STRING(
2383 PyTuple_GET_ITEM(slots, i));
2384 mp->type = T_OBJECT_EX;
2385 mp->offset = slotoffset;
2387 /* __dict__ and __weakref__ are already filtered out */
2388 assert(strcmp(mp->name, "__dict__") != 0);
2389 assert(strcmp(mp->name, "__weakref__") != 0);
2391 slotoffset += sizeof(PyObject *);
2394 if (add_dict) {
2395 if (base->tp_itemsize)
2396 type->tp_dictoffset = -(long)sizeof(PyObject *);
2397 else
2398 type->tp_dictoffset = slotoffset;
2399 slotoffset += sizeof(PyObject *);
2401 if (add_weak) {
2402 assert(!base->tp_itemsize);
2403 type->tp_weaklistoffset = slotoffset;
2404 slotoffset += sizeof(PyObject *);
2406 type->tp_basicsize = slotoffset;
2407 type->tp_itemsize = base->tp_itemsize;
2408 type->tp_members = PyHeapType_GET_MEMBERS(et);
2410 if (type->tp_weaklistoffset && type->tp_dictoffset)
2411 type->tp_getset = subtype_getsets_full;
2412 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2413 type->tp_getset = subtype_getsets_weakref_only;
2414 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2415 type->tp_getset = subtype_getsets_dict_only;
2416 else
2417 type->tp_getset = NULL;
2419 /* Special case some slots */
2420 if (type->tp_dictoffset != 0 || nslots > 0) {
2421 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2422 type->tp_getattro = PyObject_GenericGetAttr;
2423 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2424 type->tp_setattro = PyObject_GenericSetAttr;
2426 type->tp_dealloc = subtype_dealloc;
2428 /* Enable GC unless there are really no instance variables possible */
2429 if (!(type->tp_basicsize == sizeof(PyObject) &&
2430 type->tp_itemsize == 0))
2431 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2433 /* Always override allocation strategy to use regular heap */
2434 type->tp_alloc = PyType_GenericAlloc;
2435 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2436 type->tp_free = PyObject_GC_Del;
2437 type->tp_traverse = subtype_traverse;
2438 type->tp_clear = subtype_clear;
2440 else
2441 type->tp_free = PyObject_Del;
2443 /* Initialize the rest */
2444 if (PyType_Ready(type) < 0) {
2445 Py_DECREF(type);
2446 return NULL;
2449 /* Put the proper slots in place */
2450 fixup_slot_dispatchers(type);
2452 return (PyObject *)type;
2455 /* Internal API to look for a name through the MRO.
2456 This returns a borrowed reference, and doesn't set an exception! */
2457 PyObject *
2458 _PyType_Lookup(PyTypeObject *type, PyObject *name)
2460 Py_ssize_t i, n;
2461 PyObject *mro, *res, *base, *dict;
2462 unsigned int h;
2464 if (MCACHE_CACHEABLE_NAME(name) &&
2465 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2466 /* fast path */
2467 h = MCACHE_HASH_METHOD(type, name);
2468 if (method_cache[h].version == type->tp_version_tag &&
2469 method_cache[h].name == name)
2470 return method_cache[h].value;
2473 /* Look in tp_dict of types in MRO */
2474 mro = type->tp_mro;
2476 /* If mro is NULL, the type is either not yet initialized
2477 by PyType_Ready(), or already cleared by type_clear().
2478 Either way the safest thing to do is to return NULL. */
2479 if (mro == NULL)
2480 return NULL;
2482 res = NULL;
2483 assert(PyTuple_Check(mro));
2484 n = PyTuple_GET_SIZE(mro);
2485 for (i = 0; i < n; i++) {
2486 base = PyTuple_GET_ITEM(mro, i);
2487 if (PyClass_Check(base))
2488 dict = ((PyClassObject *)base)->cl_dict;
2489 else {
2490 assert(PyType_Check(base));
2491 dict = ((PyTypeObject *)base)->tp_dict;
2493 assert(dict && PyDict_Check(dict));
2494 res = PyDict_GetItem(dict, name);
2495 if (res != NULL)
2496 break;
2499 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2500 h = MCACHE_HASH_METHOD(type, name);
2501 method_cache[h].version = type->tp_version_tag;
2502 method_cache[h].value = res; /* borrowed */
2503 Py_INCREF(name);
2504 Py_DECREF(method_cache[h].name);
2505 method_cache[h].name = name;
2507 return res;
2510 /* This is similar to PyObject_GenericGetAttr(),
2511 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2512 static PyObject *
2513 type_getattro(PyTypeObject *type, PyObject *name)
2515 PyTypeObject *metatype = Py_TYPE(type);
2516 PyObject *meta_attribute, *attribute;
2517 descrgetfunc meta_get;
2519 /* Initialize this type (we'll assume the metatype is initialized) */
2520 if (type->tp_dict == NULL) {
2521 if (PyType_Ready(type) < 0)
2522 return NULL;
2525 /* No readable descriptor found yet */
2526 meta_get = NULL;
2528 /* Look for the attribute in the metatype */
2529 meta_attribute = _PyType_Lookup(metatype, name);
2531 if (meta_attribute != NULL) {
2532 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
2534 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2535 /* Data descriptors implement tp_descr_set to intercept
2536 * writes. Assume the attribute is not overridden in
2537 * type's tp_dict (and bases): call the descriptor now.
2539 return meta_get(meta_attribute, (PyObject *)type,
2540 (PyObject *)metatype);
2542 Py_INCREF(meta_attribute);
2545 /* No data descriptor found on metatype. Look in tp_dict of this
2546 * type and its bases */
2547 attribute = _PyType_Lookup(type, name);
2548 if (attribute != NULL) {
2549 /* Implement descriptor functionality, if any */
2550 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
2552 Py_XDECREF(meta_attribute);
2554 if (local_get != NULL) {
2555 /* NULL 2nd argument indicates the descriptor was
2556 * found on the target object itself (or a base) */
2557 return local_get(attribute, (PyObject *)NULL,
2558 (PyObject *)type);
2561 Py_INCREF(attribute);
2562 return attribute;
2565 /* No attribute found in local __dict__ (or bases): use the
2566 * descriptor from the metatype, if any */
2567 if (meta_get != NULL) {
2568 PyObject *res;
2569 res = meta_get(meta_attribute, (PyObject *)type,
2570 (PyObject *)metatype);
2571 Py_DECREF(meta_attribute);
2572 return res;
2575 /* If an ordinary attribute was found on the metatype, return it now */
2576 if (meta_attribute != NULL) {
2577 return meta_attribute;
2580 /* Give up */
2581 PyErr_Format(PyExc_AttributeError,
2582 "type object '%.50s' has no attribute '%.400s'",
2583 type->tp_name, PyString_AS_STRING(name));
2584 return NULL;
2587 static int
2588 type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2590 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2591 PyErr_Format(
2592 PyExc_TypeError,
2593 "can't set attributes of built-in/extension type '%s'",
2594 type->tp_name);
2595 return -1;
2597 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2598 return -1;
2599 return update_slot(type, name);
2602 static void
2603 type_dealloc(PyTypeObject *type)
2605 PyHeapTypeObject *et;
2607 /* Assert this is a heap-allocated type object */
2608 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2609 _PyObject_GC_UNTRACK(type);
2610 PyObject_ClearWeakRefs((PyObject *)type);
2611 et = (PyHeapTypeObject *)type;
2612 Py_XDECREF(type->tp_base);
2613 Py_XDECREF(type->tp_dict);
2614 Py_XDECREF(type->tp_bases);
2615 Py_XDECREF(type->tp_mro);
2616 Py_XDECREF(type->tp_cache);
2617 Py_XDECREF(type->tp_subclasses);
2618 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2619 * of most other objects. It's okay to cast it to char *.
2621 PyObject_Free((char *)type->tp_doc);
2622 Py_XDECREF(et->ht_name);
2623 Py_XDECREF(et->ht_slots);
2624 Py_TYPE(type)->tp_free((PyObject *)type);
2627 static PyObject *
2628 type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2630 PyObject *list, *raw, *ref;
2631 Py_ssize_t i, n;
2633 list = PyList_New(0);
2634 if (list == NULL)
2635 return NULL;
2636 raw = type->tp_subclasses;
2637 if (raw == NULL)
2638 return list;
2639 assert(PyList_Check(raw));
2640 n = PyList_GET_SIZE(raw);
2641 for (i = 0; i < n; i++) {
2642 ref = PyList_GET_ITEM(raw, i);
2643 assert(PyWeakref_CheckRef(ref));
2644 ref = PyWeakref_GET_OBJECT(ref);
2645 if (ref != Py_None) {
2646 if (PyList_Append(list, ref) < 0) {
2647 Py_DECREF(list);
2648 return NULL;
2652 return list;
2655 static PyMethodDef type_methods[] = {
2656 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2657 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2658 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2659 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2663 PyDoc_STRVAR(type_doc,
2664 "type(object) -> the object's type\n"
2665 "type(name, bases, dict) -> a new type");
2667 static int
2668 type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2670 /* Because of type_is_gc(), the collector only calls this
2671 for heaptypes. */
2672 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2674 Py_VISIT(type->tp_dict);
2675 Py_VISIT(type->tp_cache);
2676 Py_VISIT(type->tp_mro);
2677 Py_VISIT(type->tp_bases);
2678 Py_VISIT(type->tp_base);
2680 /* There's no need to visit type->tp_subclasses or
2681 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2682 in cycles; tp_subclasses is a list of weak references,
2683 and slots is a tuple of strings. */
2685 return 0;
2688 static int
2689 type_clear(PyTypeObject *type)
2691 /* Because of type_is_gc(), the collector only calls this
2692 for heaptypes. */
2693 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2695 /* The only field we need to clear is tp_mro, which is part of a
2696 hard cycle (its first element is the class itself) that won't
2697 be broken otherwise (it's a tuple and tuples don't have a
2698 tp_clear handler). None of the other fields need to be
2699 cleared, and here's why:
2701 tp_dict:
2702 It is a dict, so the collector will call its tp_clear.
2704 tp_cache:
2705 Not used; if it were, it would be a dict.
2707 tp_bases, tp_base:
2708 If these are involved in a cycle, there must be at least
2709 one other, mutable object in the cycle, e.g. a base
2710 class's dict; the cycle will be broken that way.
2712 tp_subclasses:
2713 A list of weak references can't be part of a cycle; and
2714 lists have their own tp_clear.
2716 slots (in PyHeapTypeObject):
2717 A tuple of strings can't be part of a cycle.
2720 Py_CLEAR(type->tp_mro);
2722 return 0;
2725 static int
2726 type_is_gc(PyTypeObject *type)
2728 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2731 PyTypeObject PyType_Type = {
2732 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2733 "type", /* tp_name */
2734 sizeof(PyHeapTypeObject), /* tp_basicsize */
2735 sizeof(PyMemberDef), /* tp_itemsize */
2736 (destructor)type_dealloc, /* tp_dealloc */
2737 0, /* tp_print */
2738 0, /* tp_getattr */
2739 0, /* tp_setattr */
2740 type_compare, /* tp_compare */
2741 (reprfunc)type_repr, /* tp_repr */
2742 0, /* tp_as_number */
2743 0, /* tp_as_sequence */
2744 0, /* tp_as_mapping */
2745 (hashfunc)_Py_HashPointer, /* tp_hash */
2746 (ternaryfunc)type_call, /* tp_call */
2747 0, /* tp_str */
2748 (getattrofunc)type_getattro, /* tp_getattro */
2749 (setattrofunc)type_setattro, /* tp_setattro */
2750 0, /* tp_as_buffer */
2751 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2752 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2753 type_doc, /* tp_doc */
2754 (traverseproc)type_traverse, /* tp_traverse */
2755 (inquiry)type_clear, /* tp_clear */
2756 type_richcompare, /* tp_richcompare */
2757 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2758 0, /* tp_iter */
2759 0, /* tp_iternext */
2760 type_methods, /* tp_methods */
2761 type_members, /* tp_members */
2762 type_getsets, /* tp_getset */
2763 0, /* tp_base */
2764 0, /* tp_dict */
2765 0, /* tp_descr_get */
2766 0, /* tp_descr_set */
2767 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2768 type_init, /* tp_init */
2769 0, /* tp_alloc */
2770 type_new, /* tp_new */
2771 PyObject_GC_Del, /* tp_free */
2772 (inquiry)type_is_gc, /* tp_is_gc */
2776 /* The base type of all types (eventually)... except itself. */
2778 /* You may wonder why object.__new__() only complains about arguments
2779 when object.__init__() is not overridden, and vice versa.
2781 Consider the use cases:
2783 1. When neither is overridden, we want to hear complaints about
2784 excess (i.e., any) arguments, since their presence could
2785 indicate there's a bug.
2787 2. When defining an Immutable type, we are likely to override only
2788 __new__(), since __init__() is called too late to initialize an
2789 Immutable object. Since __new__() defines the signature for the
2790 type, it would be a pain to have to override __init__() just to
2791 stop it from complaining about excess arguments.
2793 3. When defining a Mutable type, we are likely to override only
2794 __init__(). So here the converse reasoning applies: we don't
2795 want to have to override __new__() just to stop it from
2796 complaining.
2798 4. When __init__() is overridden, and the subclass __init__() calls
2799 object.__init__(), the latter should complain about excess
2800 arguments; ditto for __new__().
2802 Use cases 2 and 3 make it unattractive to unconditionally check for
2803 excess arguments. The best solution that addresses all four use
2804 cases is as follows: __init__() complains about excess arguments
2805 unless __new__() is overridden and __init__() is not overridden
2806 (IOW, if __init__() is overridden or __new__() is not overridden);
2807 symmetrically, __new__() complains about excess arguments unless
2808 __init__() is overridden and __new__() is not overridden
2809 (IOW, if __new__() is overridden or __init__() is not overridden).
2811 However, for backwards compatibility, this breaks too much code.
2812 Therefore, in 2.6, we'll *warn* about excess arguments when both
2813 methods are overridden; for all other cases we'll use the above
2814 rules.
2818 /* Forward */
2819 static PyObject *
2820 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2822 static int
2823 excess_args(PyObject *args, PyObject *kwds)
2825 return PyTuple_GET_SIZE(args) ||
2826 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2829 static int
2830 object_init(PyObject *self, PyObject *args, PyObject *kwds)
2832 int err = 0;
2833 if (excess_args(args, kwds)) {
2834 PyTypeObject *type = Py_TYPE(self);
2835 if (type->tp_init != object_init &&
2836 type->tp_new != object_new)
2838 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2839 "object.__init__() takes no parameters",
2842 else if (type->tp_init != object_init ||
2843 type->tp_new == object_new)
2845 PyErr_SetString(PyExc_TypeError,
2846 "object.__init__() takes no parameters");
2847 err = -1;
2850 return err;
2853 static PyObject *
2854 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2856 int err = 0;
2857 if (excess_args(args, kwds)) {
2858 if (type->tp_new != object_new &&
2859 type->tp_init != object_init)
2861 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2862 "object.__new__() takes no parameters",
2865 else if (type->tp_new != object_new ||
2866 type->tp_init == object_init)
2868 PyErr_SetString(PyExc_TypeError,
2869 "object.__new__() takes no parameters");
2870 err = -1;
2873 if (err < 0)
2874 return NULL;
2876 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2877 static PyObject *comma = NULL;
2878 PyObject *abstract_methods = NULL;
2879 PyObject *builtins;
2880 PyObject *sorted;
2881 PyObject *sorted_methods = NULL;
2882 PyObject *joined = NULL;
2883 const char *joined_str;
2885 /* Compute ", ".join(sorted(type.__abstractmethods__))
2886 into joined. */
2887 abstract_methods = type_abstractmethods(type, NULL);
2888 if (abstract_methods == NULL)
2889 goto error;
2890 builtins = PyEval_GetBuiltins();
2891 if (builtins == NULL)
2892 goto error;
2893 sorted = PyDict_GetItemString(builtins, "sorted");
2894 if (sorted == NULL)
2895 goto error;
2896 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2897 abstract_methods,
2898 NULL);
2899 if (sorted_methods == NULL)
2900 goto error;
2901 if (comma == NULL) {
2902 comma = PyString_InternFromString(", ");
2903 if (comma == NULL)
2904 goto error;
2906 joined = PyObject_CallMethod(comma, "join",
2907 "O", sorted_methods);
2908 if (joined == NULL)
2909 goto error;
2910 joined_str = PyString_AsString(joined);
2911 if (joined_str == NULL)
2912 goto error;
2914 PyErr_Format(PyExc_TypeError,
2915 "Can't instantiate abstract class %s "
2916 "with abstract methods %s",
2917 type->tp_name,
2918 joined_str);
2919 error:
2920 Py_XDECREF(joined);
2921 Py_XDECREF(sorted_methods);
2922 Py_XDECREF(abstract_methods);
2923 return NULL;
2925 return type->tp_alloc(type, 0);
2928 static void
2929 object_dealloc(PyObject *self)
2931 Py_TYPE(self)->tp_free(self);
2934 static PyObject *
2935 object_repr(PyObject *self)
2937 PyTypeObject *type;
2938 PyObject *mod, *name, *rtn;
2940 type = Py_TYPE(self);
2941 mod = type_module(type, NULL);
2942 if (mod == NULL)
2943 PyErr_Clear();
2944 else if (!PyString_Check(mod)) {
2945 Py_DECREF(mod);
2946 mod = NULL;
2948 name = type_name(type, NULL);
2949 if (name == NULL)
2950 return NULL;
2951 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
2952 rtn = PyString_FromFormat("<%s.%s object at %p>",
2953 PyString_AS_STRING(mod),
2954 PyString_AS_STRING(name),
2955 self);
2956 else
2957 rtn = PyString_FromFormat("<%s object at %p>",
2958 type->tp_name, self);
2959 Py_XDECREF(mod);
2960 Py_DECREF(name);
2961 return rtn;
2964 static PyObject *
2965 object_str(PyObject *self)
2967 unaryfunc f;
2969 f = Py_TYPE(self)->tp_repr;
2970 if (f == NULL)
2971 f = object_repr;
2972 return f(self);
2975 static PyObject *
2976 object_get_class(PyObject *self, void *closure)
2978 Py_INCREF(Py_TYPE(self));
2979 return (PyObject *)(Py_TYPE(self));
2982 static int
2983 equiv_structs(PyTypeObject *a, PyTypeObject *b)
2985 return a == b ||
2986 (a != NULL &&
2987 b != NULL &&
2988 a->tp_basicsize == b->tp_basicsize &&
2989 a->tp_itemsize == b->tp_itemsize &&
2990 a->tp_dictoffset == b->tp_dictoffset &&
2991 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2992 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2993 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2996 static int
2997 same_slots_added(PyTypeObject *a, PyTypeObject *b)
2999 PyTypeObject *base = a->tp_base;
3000 Py_ssize_t size;
3001 PyObject *slots_a, *slots_b;
3003 if (base != b->tp_base)
3004 return 0;
3005 if (equiv_structs(a, base) && equiv_structs(b, base))
3006 return 1;
3007 size = base->tp_basicsize;
3008 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3009 size += sizeof(PyObject *);
3010 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3011 size += sizeof(PyObject *);
3013 /* Check slots compliance */
3014 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3015 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3016 if (slots_a && slots_b) {
3017 if (PyObject_Compare(slots_a, slots_b) != 0)
3018 return 0;
3019 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3021 return size == a->tp_basicsize && size == b->tp_basicsize;
3024 static int
3025 compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
3027 PyTypeObject *newbase, *oldbase;
3029 if (newto->tp_dealloc != oldto->tp_dealloc ||
3030 newto->tp_free != oldto->tp_free)
3032 PyErr_Format(PyExc_TypeError,
3033 "%s assignment: "
3034 "'%s' deallocator differs from '%s'",
3035 attr,
3036 newto->tp_name,
3037 oldto->tp_name);
3038 return 0;
3040 newbase = newto;
3041 oldbase = oldto;
3042 while (equiv_structs(newbase, newbase->tp_base))
3043 newbase = newbase->tp_base;
3044 while (equiv_structs(oldbase, oldbase->tp_base))
3045 oldbase = oldbase->tp_base;
3046 if (newbase != oldbase &&
3047 (newbase->tp_base != oldbase->tp_base ||
3048 !same_slots_added(newbase, oldbase))) {
3049 PyErr_Format(PyExc_TypeError,
3050 "%s assignment: "
3051 "'%s' object layout differs from '%s'",
3052 attr,
3053 newto->tp_name,
3054 oldto->tp_name);
3055 return 0;
3058 return 1;
3061 static int
3062 object_set_class(PyObject *self, PyObject *value, void *closure)
3064 PyTypeObject *oldto = Py_TYPE(self);
3065 PyTypeObject *newto;
3067 if (value == NULL) {
3068 PyErr_SetString(PyExc_TypeError,
3069 "can't delete __class__ attribute");
3070 return -1;
3072 if (!PyType_Check(value)) {
3073 PyErr_Format(PyExc_TypeError,
3074 "__class__ must be set to new-style class, not '%s' object",
3075 Py_TYPE(value)->tp_name);
3076 return -1;
3078 newto = (PyTypeObject *)value;
3079 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3080 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3082 PyErr_Format(PyExc_TypeError,
3083 "__class__ assignment: only for heap types");
3084 return -1;
3086 if (compatible_for_assignment(newto, oldto, "__class__")) {
3087 Py_INCREF(newto);
3088 Py_TYPE(self) = newto;
3089 Py_DECREF(oldto);
3090 return 0;
3092 else {
3093 return -1;
3097 static PyGetSetDef object_getsets[] = {
3098 {"__class__", object_get_class, object_set_class,
3099 PyDoc_STR("the object's class")},
3104 /* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
3105 We fall back to helpers in copy_reg for:
3106 - pickle protocols < 2
3107 - calculating the list of slot names (done only once per class)
3108 - the __newobj__ function (which is used as a token but never called)
3111 static PyObject *
3112 import_copyreg(void)
3114 static PyObject *copyreg_str;
3116 if (!copyreg_str) {
3117 copyreg_str = PyString_InternFromString("copy_reg");
3118 if (copyreg_str == NULL)
3119 return NULL;
3122 return PyImport_Import(copyreg_str);
3125 static PyObject *
3126 slotnames(PyObject *cls)
3128 PyObject *clsdict;
3129 PyObject *copyreg;
3130 PyObject *slotnames;
3132 if (!PyType_Check(cls)) {
3133 Py_INCREF(Py_None);
3134 return Py_None;
3137 clsdict = ((PyTypeObject *)cls)->tp_dict;
3138 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
3139 if (slotnames != NULL && PyList_Check(slotnames)) {
3140 Py_INCREF(slotnames);
3141 return slotnames;
3144 copyreg = import_copyreg();
3145 if (copyreg == NULL)
3146 return NULL;
3148 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3149 Py_DECREF(copyreg);
3150 if (slotnames != NULL &&
3151 slotnames != Py_None &&
3152 !PyList_Check(slotnames))
3154 PyErr_SetString(PyExc_TypeError,
3155 "copy_reg._slotnames didn't return a list or None");
3156 Py_DECREF(slotnames);
3157 slotnames = NULL;
3160 return slotnames;
3163 static PyObject *
3164 reduce_2(PyObject *obj)
3166 PyObject *cls, *getnewargs;
3167 PyObject *args = NULL, *args2 = NULL;
3168 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3169 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3170 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3171 Py_ssize_t i, n;
3173 cls = PyObject_GetAttrString(obj, "__class__");
3174 if (cls == NULL)
3175 return NULL;
3177 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3178 if (getnewargs != NULL) {
3179 args = PyObject_CallObject(getnewargs, NULL);
3180 Py_DECREF(getnewargs);
3181 if (args != NULL && !PyTuple_Check(args)) {
3182 PyErr_Format(PyExc_TypeError,
3183 "__getnewargs__ should return a tuple, "
3184 "not '%.200s'", Py_TYPE(args)->tp_name);
3185 goto end;
3188 else {
3189 PyErr_Clear();
3190 args = PyTuple_New(0);
3192 if (args == NULL)
3193 goto end;
3195 getstate = PyObject_GetAttrString(obj, "__getstate__");
3196 if (getstate != NULL) {
3197 state = PyObject_CallObject(getstate, NULL);
3198 Py_DECREF(getstate);
3199 if (state == NULL)
3200 goto end;
3202 else {
3203 PyErr_Clear();
3204 state = PyObject_GetAttrString(obj, "__dict__");
3205 if (state == NULL) {
3206 PyErr_Clear();
3207 state = Py_None;
3208 Py_INCREF(state);
3210 names = slotnames(cls);
3211 if (names == NULL)
3212 goto end;
3213 if (names != Py_None) {
3214 assert(PyList_Check(names));
3215 slots = PyDict_New();
3216 if (slots == NULL)
3217 goto end;
3218 n = 0;
3219 /* Can't pre-compute the list size; the list
3220 is stored on the class so accessible to other
3221 threads, which may be run by DECREF */
3222 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3223 PyObject *name, *value;
3224 name = PyList_GET_ITEM(names, i);
3225 value = PyObject_GetAttr(obj, name);
3226 if (value == NULL)
3227 PyErr_Clear();
3228 else {
3229 int err = PyDict_SetItem(slots, name,
3230 value);
3231 Py_DECREF(value);
3232 if (err)
3233 goto end;
3234 n++;
3237 if (n) {
3238 state = Py_BuildValue("(NO)", state, slots);
3239 if (state == NULL)
3240 goto end;
3245 if (!PyList_Check(obj)) {
3246 listitems = Py_None;
3247 Py_INCREF(listitems);
3249 else {
3250 listitems = PyObject_GetIter(obj);
3251 if (listitems == NULL)
3252 goto end;
3255 if (!PyDict_Check(obj)) {
3256 dictitems = Py_None;
3257 Py_INCREF(dictitems);
3259 else {
3260 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3261 if (dictitems == NULL)
3262 goto end;
3265 copyreg = import_copyreg();
3266 if (copyreg == NULL)
3267 goto end;
3268 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
3269 if (newobj == NULL)
3270 goto end;
3272 n = PyTuple_GET_SIZE(args);
3273 args2 = PyTuple_New(n+1);
3274 if (args2 == NULL)
3275 goto end;
3276 PyTuple_SET_ITEM(args2, 0, cls);
3277 cls = NULL;
3278 for (i = 0; i < n; i++) {
3279 PyObject *v = PyTuple_GET_ITEM(args, i);
3280 Py_INCREF(v);
3281 PyTuple_SET_ITEM(args2, i+1, v);
3284 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
3286 end:
3287 Py_XDECREF(cls);
3288 Py_XDECREF(args);
3289 Py_XDECREF(args2);
3290 Py_XDECREF(slots);
3291 Py_XDECREF(state);
3292 Py_XDECREF(names);
3293 Py_XDECREF(listitems);
3294 Py_XDECREF(dictitems);
3295 Py_XDECREF(copyreg);
3296 Py_XDECREF(newobj);
3297 return res;
3301 * There were two problems when object.__reduce__ and object.__reduce_ex__
3302 * were implemented in the same function:
3303 * - trying to pickle an object with a custom __reduce__ method that
3304 * fell back to object.__reduce__ in certain circumstances led to
3305 * infinite recursion at Python level and eventual RuntimeError.
3306 * - Pickling objects that lied about their type by overwriting the
3307 * __class__ descriptor could lead to infinite recursion at C level
3308 * and eventual segfault.
3310 * Because of backwards compatibility, the two methods still have to
3311 * behave in the same way, even if this is not required by the pickle
3312 * protocol. This common functionality was moved to the _common_reduce
3313 * function.
3315 static PyObject *
3316 _common_reduce(PyObject *self, int proto)
3318 PyObject *copyreg, *res;
3320 if (proto >= 2)
3321 return reduce_2(self);
3323 copyreg = import_copyreg();
3324 if (!copyreg)
3325 return NULL;
3327 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3328 Py_DECREF(copyreg);
3330 return res;
3333 static PyObject *
3334 object_reduce(PyObject *self, PyObject *args)
3336 int proto = 0;
3338 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3339 return NULL;
3341 return _common_reduce(self, proto);
3344 static PyObject *
3345 object_reduce_ex(PyObject *self, PyObject *args)
3347 PyObject *reduce, *res;
3348 int proto = 0;
3350 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3351 return NULL;
3353 reduce = PyObject_GetAttrString(self, "__reduce__");
3354 if (reduce == NULL)
3355 PyErr_Clear();
3356 else {
3357 PyObject *cls, *clsreduce, *objreduce;
3358 int override;
3359 cls = PyObject_GetAttrString(self, "__class__");
3360 if (cls == NULL) {
3361 Py_DECREF(reduce);
3362 return NULL;
3364 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3365 Py_DECREF(cls);
3366 if (clsreduce == NULL) {
3367 Py_DECREF(reduce);
3368 return NULL;
3370 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3371 "__reduce__");
3372 override = (clsreduce != objreduce);
3373 Py_DECREF(clsreduce);
3374 if (override) {
3375 res = PyObject_CallObject(reduce, NULL);
3376 Py_DECREF(reduce);
3377 return res;
3379 else
3380 Py_DECREF(reduce);
3383 return _common_reduce(self, proto);
3386 static PyObject *
3387 object_subclasshook(PyObject *cls, PyObject *args)
3389 Py_INCREF(Py_NotImplemented);
3390 return Py_NotImplemented;
3393 PyDoc_STRVAR(object_subclasshook_doc,
3394 "Abstract classes can override this to customize issubclass().\n"
3395 "\n"
3396 "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3397 "It should return True, False or NotImplemented. If it returns\n"
3398 "NotImplemented, the normal algorithm is used. Otherwise, it\n"
3399 "overrides the normal algorithm (and the outcome is cached).\n");
3402 from PEP 3101, this code implements:
3404 class object:
3405 def __format__(self, format_spec):
3406 if isinstance(format_spec, str):
3407 return format(str(self), format_spec)
3408 elif isinstance(format_spec, unicode):
3409 return format(unicode(self), format_spec)
3411 static PyObject *
3412 object_format(PyObject *self, PyObject *args)
3414 PyObject *format_spec;
3415 PyObject *self_as_str = NULL;
3416 PyObject *result = NULL;
3417 PyObject *format_meth = NULL;
3419 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3420 return NULL;
3421 #ifdef Py_USING_UNICODE
3422 if (PyUnicode_Check(format_spec)) {
3423 self_as_str = PyObject_Unicode(self);
3424 } else if (PyString_Check(format_spec)) {
3425 #else
3426 if (PyString_Check(format_spec)) {
3427 #endif
3428 self_as_str = PyObject_Str(self);
3429 } else {
3430 PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
3431 return NULL;
3434 if (self_as_str != NULL) {
3435 /* find the format function */
3436 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3437 if (format_meth != NULL) {
3438 /* and call it */
3439 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3443 Py_XDECREF(self_as_str);
3444 Py_XDECREF(format_meth);
3446 return result;
3449 static PyObject *
3450 object_sizeof(PyObject *self, PyObject *args)
3452 Py_ssize_t res, isize;
3454 res = 0;
3455 isize = self->ob_type->tp_itemsize;
3456 if (isize > 0)
3457 res = self->ob_type->ob_size * isize;
3458 res += self->ob_type->tp_basicsize;
3460 return PyInt_FromSsize_t(res);
3463 static PyMethodDef object_methods[] = {
3464 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3465 PyDoc_STR("helper for pickle")},
3466 {"__reduce__", object_reduce, METH_VARARGS,
3467 PyDoc_STR("helper for pickle")},
3468 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3469 object_subclasshook_doc},
3470 {"__format__", object_format, METH_VARARGS,
3471 PyDoc_STR("default object formatter")},
3472 {"__sizeof__", object_sizeof, METH_NOARGS,
3473 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
3478 PyTypeObject PyBaseObject_Type = {
3479 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3480 "object", /* tp_name */
3481 sizeof(PyObject), /* tp_basicsize */
3482 0, /* tp_itemsize */
3483 object_dealloc, /* tp_dealloc */
3484 0, /* tp_print */
3485 0, /* tp_getattr */
3486 0, /* tp_setattr */
3487 0, /* tp_compare */
3488 object_repr, /* tp_repr */
3489 0, /* tp_as_number */
3490 0, /* tp_as_sequence */
3491 0, /* tp_as_mapping */
3492 (hashfunc)_Py_HashPointer, /* tp_hash */
3493 0, /* tp_call */
3494 object_str, /* tp_str */
3495 PyObject_GenericGetAttr, /* tp_getattro */
3496 PyObject_GenericSetAttr, /* tp_setattro */
3497 0, /* tp_as_buffer */
3498 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3499 PyDoc_STR("The most base type"), /* tp_doc */
3500 0, /* tp_traverse */
3501 0, /* tp_clear */
3502 0, /* tp_richcompare */
3503 0, /* tp_weaklistoffset */
3504 0, /* tp_iter */
3505 0, /* tp_iternext */
3506 object_methods, /* tp_methods */
3507 0, /* tp_members */
3508 object_getsets, /* tp_getset */
3509 0, /* tp_base */
3510 0, /* tp_dict */
3511 0, /* tp_descr_get */
3512 0, /* tp_descr_set */
3513 0, /* tp_dictoffset */
3514 object_init, /* tp_init */
3515 PyType_GenericAlloc, /* tp_alloc */
3516 object_new, /* tp_new */
3517 PyObject_Del, /* tp_free */
3521 /* Initialize the __dict__ in a type object */
3523 static int
3524 add_methods(PyTypeObject *type, PyMethodDef *meth)
3526 PyObject *dict = type->tp_dict;
3528 for (; meth->ml_name != NULL; meth++) {
3529 PyObject *descr;
3530 if (PyDict_GetItemString(dict, meth->ml_name) &&
3531 !(meth->ml_flags & METH_COEXIST))
3532 continue;
3533 if (meth->ml_flags & METH_CLASS) {
3534 if (meth->ml_flags & METH_STATIC) {
3535 PyErr_SetString(PyExc_ValueError,
3536 "method cannot be both class and static");
3537 return -1;
3539 descr = PyDescr_NewClassMethod(type, meth);
3541 else if (meth->ml_flags & METH_STATIC) {
3542 PyObject *cfunc = PyCFunction_New(meth, NULL);
3543 if (cfunc == NULL)
3544 return -1;
3545 descr = PyStaticMethod_New(cfunc);
3546 Py_DECREF(cfunc);
3548 else {
3549 descr = PyDescr_NewMethod(type, meth);
3551 if (descr == NULL)
3552 return -1;
3553 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3554 return -1;
3555 Py_DECREF(descr);
3557 return 0;
3560 static int
3561 add_members(PyTypeObject *type, PyMemberDef *memb)
3563 PyObject *dict = type->tp_dict;
3565 for (; memb->name != NULL; memb++) {
3566 PyObject *descr;
3567 if (PyDict_GetItemString(dict, memb->name))
3568 continue;
3569 descr = PyDescr_NewMember(type, memb);
3570 if (descr == NULL)
3571 return -1;
3572 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3573 return -1;
3574 Py_DECREF(descr);
3576 return 0;
3579 static int
3580 add_getset(PyTypeObject *type, PyGetSetDef *gsp)
3582 PyObject *dict = type->tp_dict;
3584 for (; gsp->name != NULL; gsp++) {
3585 PyObject *descr;
3586 if (PyDict_GetItemString(dict, gsp->name))
3587 continue;
3588 descr = PyDescr_NewGetSet(type, gsp);
3590 if (descr == NULL)
3591 return -1;
3592 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3593 return -1;
3594 Py_DECREF(descr);
3596 return 0;
3599 static void
3600 inherit_special(PyTypeObject *type, PyTypeObject *base)
3602 Py_ssize_t oldsize, newsize;
3604 /* Special flag magic */
3605 if (!type->tp_as_buffer && base->tp_as_buffer) {
3606 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3607 type->tp_flags |=
3608 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3610 if (!type->tp_as_sequence && base->tp_as_sequence) {
3611 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3612 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3614 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3615 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3616 if ((!type->tp_as_number && base->tp_as_number) ||
3617 (!type->tp_as_sequence && base->tp_as_sequence)) {
3618 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3619 if (!type->tp_as_number && !type->tp_as_sequence) {
3620 type->tp_flags |= base->tp_flags &
3621 Py_TPFLAGS_HAVE_INPLACEOPS;
3624 /* Wow */
3626 if (!type->tp_as_number && base->tp_as_number) {
3627 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3628 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3631 /* Copying basicsize is connected to the GC flags */
3632 oldsize = base->tp_basicsize;
3633 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3634 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3635 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3636 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3637 (!type->tp_traverse && !type->tp_clear)) {
3638 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3639 if (type->tp_traverse == NULL)
3640 type->tp_traverse = base->tp_traverse;
3641 if (type->tp_clear == NULL)
3642 type->tp_clear = base->tp_clear;
3644 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3645 /* The condition below could use some explanation.
3646 It appears that tp_new is not inherited for static types
3647 whose base class is 'object'; this seems to be a precaution
3648 so that old extension types don't suddenly become
3649 callable (object.__new__ wouldn't insure the invariants
3650 that the extension type's own factory function ensures).
3651 Heap types, of course, are under our control, so they do
3652 inherit tp_new; static extension types that specify some
3653 other built-in type as the default are considered
3654 new-style-aware so they also inherit object.__new__. */
3655 if (base != &PyBaseObject_Type ||
3656 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3657 if (type->tp_new == NULL)
3658 type->tp_new = base->tp_new;
3661 type->tp_basicsize = newsize;
3663 /* Copy other non-function slots */
3665 #undef COPYVAL
3666 #define COPYVAL(SLOT) \
3667 if (type->SLOT == 0) type->SLOT = base->SLOT
3669 COPYVAL(tp_itemsize);
3670 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3671 COPYVAL(tp_weaklistoffset);
3673 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3674 COPYVAL(tp_dictoffset);
3677 /* Setup fast subclass flags */
3678 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3679 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3680 else if (PyType_IsSubtype(base, &PyType_Type))
3681 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3682 else if (PyType_IsSubtype(base, &PyInt_Type))
3683 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3684 else if (PyType_IsSubtype(base, &PyLong_Type))
3685 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3686 else if (PyType_IsSubtype(base, &PyString_Type))
3687 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3688 #ifdef Py_USING_UNICODE
3689 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3690 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3691 #endif
3692 else if (PyType_IsSubtype(base, &PyTuple_Type))
3693 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3694 else if (PyType_IsSubtype(base, &PyList_Type))
3695 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3696 else if (PyType_IsSubtype(base, &PyDict_Type))
3697 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
3700 static int
3701 overrides_name(PyTypeObject *type, char *name)
3703 PyObject *dict = type->tp_dict;
3705 assert(dict != NULL);
3706 if (PyDict_GetItemString(dict, name) != NULL) {
3707 return 1;
3709 return 0;
3712 #define OVERRIDES_HASH(x) overrides_name(x, "__hash__")
3713 #define OVERRIDES_CMP(x) overrides_name(x, "__cmp__")
3714 #define OVERRIDES_EQ(x) overrides_name(x, "__eq__")
3716 static void
3717 inherit_slots(PyTypeObject *type, PyTypeObject *base)
3719 PyTypeObject *basebase;
3721 #undef SLOTDEFINED
3722 #undef COPYSLOT
3723 #undef COPYNUM
3724 #undef COPYSEQ
3725 #undef COPYMAP
3726 #undef COPYBUF
3728 #define SLOTDEFINED(SLOT) \
3729 (base->SLOT != 0 && \
3730 (basebase == NULL || base->SLOT != basebase->SLOT))
3732 #define COPYSLOT(SLOT) \
3733 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
3735 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3736 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3737 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
3738 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
3740 /* This won't inherit indirect slots (from tp_as_number etc.)
3741 if type doesn't provide the space. */
3743 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3744 basebase = base->tp_base;
3745 if (basebase->tp_as_number == NULL)
3746 basebase = NULL;
3747 COPYNUM(nb_add);
3748 COPYNUM(nb_subtract);
3749 COPYNUM(nb_multiply);
3750 COPYNUM(nb_divide);
3751 COPYNUM(nb_remainder);
3752 COPYNUM(nb_divmod);
3753 COPYNUM(nb_power);
3754 COPYNUM(nb_negative);
3755 COPYNUM(nb_positive);
3756 COPYNUM(nb_absolute);
3757 COPYNUM(nb_nonzero);
3758 COPYNUM(nb_invert);
3759 COPYNUM(nb_lshift);
3760 COPYNUM(nb_rshift);
3761 COPYNUM(nb_and);
3762 COPYNUM(nb_xor);
3763 COPYNUM(nb_or);
3764 COPYNUM(nb_coerce);
3765 COPYNUM(nb_int);
3766 COPYNUM(nb_long);
3767 COPYNUM(nb_float);
3768 COPYNUM(nb_oct);
3769 COPYNUM(nb_hex);
3770 COPYNUM(nb_inplace_add);
3771 COPYNUM(nb_inplace_subtract);
3772 COPYNUM(nb_inplace_multiply);
3773 COPYNUM(nb_inplace_divide);
3774 COPYNUM(nb_inplace_remainder);
3775 COPYNUM(nb_inplace_power);
3776 COPYNUM(nb_inplace_lshift);
3777 COPYNUM(nb_inplace_rshift);
3778 COPYNUM(nb_inplace_and);
3779 COPYNUM(nb_inplace_xor);
3780 COPYNUM(nb_inplace_or);
3781 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3782 COPYNUM(nb_true_divide);
3783 COPYNUM(nb_floor_divide);
3784 COPYNUM(nb_inplace_true_divide);
3785 COPYNUM(nb_inplace_floor_divide);
3787 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3788 COPYNUM(nb_index);
3792 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3793 basebase = base->tp_base;
3794 if (basebase->tp_as_sequence == NULL)
3795 basebase = NULL;
3796 COPYSEQ(sq_length);
3797 COPYSEQ(sq_concat);
3798 COPYSEQ(sq_repeat);
3799 COPYSEQ(sq_item);
3800 COPYSEQ(sq_slice);
3801 COPYSEQ(sq_ass_item);
3802 COPYSEQ(sq_ass_slice);
3803 COPYSEQ(sq_contains);
3804 COPYSEQ(sq_inplace_concat);
3805 COPYSEQ(sq_inplace_repeat);
3808 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3809 basebase = base->tp_base;
3810 if (basebase->tp_as_mapping == NULL)
3811 basebase = NULL;
3812 COPYMAP(mp_length);
3813 COPYMAP(mp_subscript);
3814 COPYMAP(mp_ass_subscript);
3817 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3818 basebase = base->tp_base;
3819 if (basebase->tp_as_buffer == NULL)
3820 basebase = NULL;
3821 COPYBUF(bf_getreadbuffer);
3822 COPYBUF(bf_getwritebuffer);
3823 COPYBUF(bf_getsegcount);
3824 COPYBUF(bf_getcharbuffer);
3825 COPYBUF(bf_getbuffer);
3826 COPYBUF(bf_releasebuffer);
3829 basebase = base->tp_base;
3831 COPYSLOT(tp_dealloc);
3832 COPYSLOT(tp_print);
3833 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3834 type->tp_getattr = base->tp_getattr;
3835 type->tp_getattro = base->tp_getattro;
3837 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3838 type->tp_setattr = base->tp_setattr;
3839 type->tp_setattro = base->tp_setattro;
3841 /* tp_compare see tp_richcompare */
3842 COPYSLOT(tp_repr);
3843 /* tp_hash see tp_richcompare */
3844 COPYSLOT(tp_call);
3845 COPYSLOT(tp_str);
3846 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
3847 if (type->tp_compare == NULL &&
3848 type->tp_richcompare == NULL &&
3849 type->tp_hash == NULL)
3851 type->tp_compare = base->tp_compare;
3852 type->tp_richcompare = base->tp_richcompare;
3853 type->tp_hash = base->tp_hash;
3854 /* Check for changes to inherited methods in Py3k*/
3855 if (Py_Py3kWarningFlag) {
3856 if (base->tp_hash &&
3857 (base->tp_hash != PyObject_HashNotImplemented) &&
3858 !OVERRIDES_HASH(type)) {
3859 if (OVERRIDES_CMP(type)) {
3860 PyErr_WarnPy3k("Overriding "
3861 "__cmp__ blocks inheritance "
3862 "of __hash__ in 3.x",
3865 if (OVERRIDES_EQ(type)) {
3866 PyErr_WarnPy3k("Overriding "
3867 "__eq__ blocks inheritance "
3868 "of __hash__ in 3.x",
3875 else {
3876 COPYSLOT(tp_compare);
3878 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3879 COPYSLOT(tp_iter);
3880 COPYSLOT(tp_iternext);
3882 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3883 COPYSLOT(tp_descr_get);
3884 COPYSLOT(tp_descr_set);
3885 COPYSLOT(tp_dictoffset);
3886 COPYSLOT(tp_init);
3887 COPYSLOT(tp_alloc);
3888 COPYSLOT(tp_is_gc);
3889 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3890 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3891 /* They agree about gc. */
3892 COPYSLOT(tp_free);
3894 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3895 type->tp_free == NULL &&
3896 base->tp_free == _PyObject_Del) {
3897 /* A bit of magic to plug in the correct default
3898 * tp_free function when a derived class adds gc,
3899 * didn't define tp_free, and the base uses the
3900 * default non-gc tp_free.
3902 type->tp_free = PyObject_GC_Del;
3904 /* else they didn't agree about gc, and there isn't something
3905 * obvious to be done -- the type is on its own.
3910 static int add_operators(PyTypeObject *);
3913 PyType_Ready(PyTypeObject *type)
3915 PyObject *dict, *bases;
3916 PyTypeObject *base;
3917 Py_ssize_t i, n;
3919 if (type->tp_flags & Py_TPFLAGS_READY) {
3920 assert(type->tp_dict != NULL);
3921 return 0;
3923 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
3925 type->tp_flags |= Py_TPFLAGS_READYING;
3927 #ifdef Py_TRACE_REFS
3928 /* PyType_Ready is the closest thing we have to a choke point
3929 * for type objects, so is the best place I can think of to try
3930 * to get type objects into the doubly-linked list of all objects.
3931 * Still, not all type objects go thru PyType_Ready.
3933 _Py_AddToAllObjects((PyObject *)type, 0);
3934 #endif
3936 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3937 base = type->tp_base;
3938 if (base == NULL && type != &PyBaseObject_Type) {
3939 base = type->tp_base = &PyBaseObject_Type;
3940 Py_INCREF(base);
3943 /* Now the only way base can still be NULL is if type is
3944 * &PyBaseObject_Type.
3947 /* Initialize the base class */
3948 if (base && base->tp_dict == NULL) {
3949 if (PyType_Ready(base) < 0)
3950 goto error;
3953 /* Initialize ob_type if NULL. This means extensions that want to be
3954 compilable separately on Windows can call PyType_Ready() instead of
3955 initializing the ob_type field of their type objects. */
3956 /* The test for base != NULL is really unnecessary, since base is only
3957 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3958 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3959 know that. */
3960 if (Py_TYPE(type) == NULL && base != NULL)
3961 Py_TYPE(type) = Py_TYPE(base);
3963 /* Initialize tp_bases */
3964 bases = type->tp_bases;
3965 if (bases == NULL) {
3966 if (base == NULL)
3967 bases = PyTuple_New(0);
3968 else
3969 bases = PyTuple_Pack(1, base);
3970 if (bases == NULL)
3971 goto error;
3972 type->tp_bases = bases;
3975 /* Initialize tp_dict */
3976 dict = type->tp_dict;
3977 if (dict == NULL) {
3978 dict = PyDict_New();
3979 if (dict == NULL)
3980 goto error;
3981 type->tp_dict = dict;
3984 /* Add type-specific descriptors to tp_dict */
3985 if (add_operators(type) < 0)
3986 goto error;
3987 if (type->tp_methods != NULL) {
3988 if (add_methods(type, type->tp_methods) < 0)
3989 goto error;
3991 if (type->tp_members != NULL) {
3992 if (add_members(type, type->tp_members) < 0)
3993 goto error;
3995 if (type->tp_getset != NULL) {
3996 if (add_getset(type, type->tp_getset) < 0)
3997 goto error;
4000 /* Calculate method resolution order */
4001 if (mro_internal(type) < 0) {
4002 goto error;
4005 /* Inherit special flags from dominant base */
4006 if (type->tp_base != NULL)
4007 inherit_special(type, type->tp_base);
4009 /* Initialize tp_dict properly */
4010 bases = type->tp_mro;
4011 assert(bases != NULL);
4012 assert(PyTuple_Check(bases));
4013 n = PyTuple_GET_SIZE(bases);
4014 for (i = 1; i < n; i++) {
4015 PyObject *b = PyTuple_GET_ITEM(bases, i);
4016 if (PyType_Check(b))
4017 inherit_slots(type, (PyTypeObject *)b);
4020 /* Sanity check for tp_free. */
4021 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4022 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4023 /* This base class needs to call tp_free, but doesn't have
4024 * one, or its tp_free is for non-gc'ed objects.
4026 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4027 "gc and is a base type but has inappropriate "
4028 "tp_free slot",
4029 type->tp_name);
4030 goto error;
4033 /* if the type dictionary doesn't contain a __doc__, set it from
4034 the tp_doc slot.
4036 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
4037 if (type->tp_doc != NULL) {
4038 PyObject *doc = PyString_FromString(type->tp_doc);
4039 if (doc == NULL)
4040 goto error;
4041 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
4042 Py_DECREF(doc);
4043 } else {
4044 PyDict_SetItemString(type->tp_dict,
4045 "__doc__", Py_None);
4049 /* Some more special stuff */
4050 base = type->tp_base;
4051 if (base != NULL) {
4052 if (type->tp_as_number == NULL)
4053 type->tp_as_number = base->tp_as_number;
4054 if (type->tp_as_sequence == NULL)
4055 type->tp_as_sequence = base->tp_as_sequence;
4056 if (type->tp_as_mapping == NULL)
4057 type->tp_as_mapping = base->tp_as_mapping;
4058 if (type->tp_as_buffer == NULL)
4059 type->tp_as_buffer = base->tp_as_buffer;
4062 /* Link into each base class's list of subclasses */
4063 bases = type->tp_bases;
4064 n = PyTuple_GET_SIZE(bases);
4065 for (i = 0; i < n; i++) {
4066 PyObject *b = PyTuple_GET_ITEM(bases, i);
4067 if (PyType_Check(b) &&
4068 add_subclass((PyTypeObject *)b, type) < 0)
4069 goto error;
4072 /* All done -- set the ready flag */
4073 assert(type->tp_dict != NULL);
4074 type->tp_flags =
4075 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4076 return 0;
4078 error:
4079 type->tp_flags &= ~Py_TPFLAGS_READYING;
4080 return -1;
4083 static int
4084 add_subclass(PyTypeObject *base, PyTypeObject *type)
4086 Py_ssize_t i;
4087 int result;
4088 PyObject *list, *ref, *newobj;
4090 list = base->tp_subclasses;
4091 if (list == NULL) {
4092 base->tp_subclasses = list = PyList_New(0);
4093 if (list == NULL)
4094 return -1;
4096 assert(PyList_Check(list));
4097 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4098 i = PyList_GET_SIZE(list);
4099 while (--i >= 0) {
4100 ref = PyList_GET_ITEM(list, i);
4101 assert(PyWeakref_CheckRef(ref));
4102 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4103 return PyList_SetItem(list, i, newobj);
4105 result = PyList_Append(list, newobj);
4106 Py_DECREF(newobj);
4107 return result;
4110 static void
4111 remove_subclass(PyTypeObject *base, PyTypeObject *type)
4113 Py_ssize_t i;
4114 PyObject *list, *ref;
4116 list = base->tp_subclasses;
4117 if (list == NULL) {
4118 return;
4120 assert(PyList_Check(list));
4121 i = PyList_GET_SIZE(list);
4122 while (--i >= 0) {
4123 ref = PyList_GET_ITEM(list, i);
4124 assert(PyWeakref_CheckRef(ref));
4125 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4126 /* this can't fail, right? */
4127 PySequence_DelItem(list, i);
4128 return;
4133 static int
4134 check_num_args(PyObject *ob, int n)
4136 if (!PyTuple_CheckExact(ob)) {
4137 PyErr_SetString(PyExc_SystemError,
4138 "PyArg_UnpackTuple() argument list is not a tuple");
4139 return 0;
4141 if (n == PyTuple_GET_SIZE(ob))
4142 return 1;
4143 PyErr_Format(
4144 PyExc_TypeError,
4145 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4146 return 0;
4149 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
4151 /* There's a wrapper *function* for each distinct function typedef used
4152 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
4153 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4154 Most tables have only one entry; the tables for binary operators have two
4155 entries, one regular and one with reversed arguments. */
4157 static PyObject *
4158 wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
4160 lenfunc func = (lenfunc)wrapped;
4161 Py_ssize_t res;
4163 if (!check_num_args(args, 0))
4164 return NULL;
4165 res = (*func)(self);
4166 if (res == -1 && PyErr_Occurred())
4167 return NULL;
4168 return PyInt_FromLong((long)res);
4171 static PyObject *
4172 wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4174 inquiry func = (inquiry)wrapped;
4175 int res;
4177 if (!check_num_args(args, 0))
4178 return NULL;
4179 res = (*func)(self);
4180 if (res == -1 && PyErr_Occurred())
4181 return NULL;
4182 return PyBool_FromLong((long)res);
4185 static PyObject *
4186 wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4188 binaryfunc func = (binaryfunc)wrapped;
4189 PyObject *other;
4191 if (!check_num_args(args, 1))
4192 return NULL;
4193 other = PyTuple_GET_ITEM(args, 0);
4194 return (*func)(self, other);
4197 static PyObject *
4198 wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4200 binaryfunc func = (binaryfunc)wrapped;
4201 PyObject *other;
4203 if (!check_num_args(args, 1))
4204 return NULL;
4205 other = PyTuple_GET_ITEM(args, 0);
4206 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
4207 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
4208 Py_INCREF(Py_NotImplemented);
4209 return Py_NotImplemented;
4211 return (*func)(self, other);
4214 static PyObject *
4215 wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4217 binaryfunc func = (binaryfunc)wrapped;
4218 PyObject *other;
4220 if (!check_num_args(args, 1))
4221 return NULL;
4222 other = PyTuple_GET_ITEM(args, 0);
4223 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
4224 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
4225 Py_INCREF(Py_NotImplemented);
4226 return Py_NotImplemented;
4228 return (*func)(other, self);
4231 static PyObject *
4232 wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4234 coercion func = (coercion)wrapped;
4235 PyObject *other, *res;
4236 int ok;
4238 if (!check_num_args(args, 1))
4239 return NULL;
4240 other = PyTuple_GET_ITEM(args, 0);
4241 ok = func(&self, &other);
4242 if (ok < 0)
4243 return NULL;
4244 if (ok > 0) {
4245 Py_INCREF(Py_NotImplemented);
4246 return Py_NotImplemented;
4248 res = PyTuple_New(2);
4249 if (res == NULL) {
4250 Py_DECREF(self);
4251 Py_DECREF(other);
4252 return NULL;
4254 PyTuple_SET_ITEM(res, 0, self);
4255 PyTuple_SET_ITEM(res, 1, other);
4256 return res;
4259 static PyObject *
4260 wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4262 ternaryfunc func = (ternaryfunc)wrapped;
4263 PyObject *other;
4264 PyObject *third = Py_None;
4266 /* Note: This wrapper only works for __pow__() */
4268 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4269 return NULL;
4270 return (*func)(self, other, third);
4273 static PyObject *
4274 wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4276 ternaryfunc func = (ternaryfunc)wrapped;
4277 PyObject *other;
4278 PyObject *third = Py_None;
4280 /* Note: This wrapper only works for __pow__() */
4282 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4283 return NULL;
4284 return (*func)(other, self, third);
4287 static PyObject *
4288 wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4290 unaryfunc func = (unaryfunc)wrapped;
4292 if (!check_num_args(args, 0))
4293 return NULL;
4294 return (*func)(self);
4297 static PyObject *
4298 wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
4300 ssizeargfunc func = (ssizeargfunc)wrapped;
4301 PyObject* o;
4302 Py_ssize_t i;
4304 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4305 return NULL;
4306 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4307 if (i == -1 && PyErr_Occurred())
4308 return NULL;
4309 return (*func)(self, i);
4312 static Py_ssize_t
4313 getindex(PyObject *self, PyObject *arg)
4315 Py_ssize_t i;
4317 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4318 if (i == -1 && PyErr_Occurred())
4319 return -1;
4320 if (i < 0) {
4321 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4322 if (sq && sq->sq_length) {
4323 Py_ssize_t n = (*sq->sq_length)(self);
4324 if (n < 0)
4325 return -1;
4326 i += n;
4329 return i;
4332 static PyObject *
4333 wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4335 ssizeargfunc func = (ssizeargfunc)wrapped;
4336 PyObject *arg;
4337 Py_ssize_t i;
4339 if (PyTuple_GET_SIZE(args) == 1) {
4340 arg = PyTuple_GET_ITEM(args, 0);
4341 i = getindex(self, arg);
4342 if (i == -1 && PyErr_Occurred())
4343 return NULL;
4344 return (*func)(self, i);
4346 check_num_args(args, 1);
4347 assert(PyErr_Occurred());
4348 return NULL;
4351 static PyObject *
4352 wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
4354 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4355 Py_ssize_t i, j;
4357 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4358 return NULL;
4359 return (*func)(self, i, j);
4362 static PyObject *
4363 wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
4365 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4366 Py_ssize_t i;
4367 int res;
4368 PyObject *arg, *value;
4370 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4371 return NULL;
4372 i = getindex(self, arg);
4373 if (i == -1 && PyErr_Occurred())
4374 return NULL;
4375 res = (*func)(self, i, value);
4376 if (res == -1 && PyErr_Occurred())
4377 return NULL;
4378 Py_INCREF(Py_None);
4379 return Py_None;
4382 static PyObject *
4383 wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
4385 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4386 Py_ssize_t i;
4387 int res;
4388 PyObject *arg;
4390 if (!check_num_args(args, 1))
4391 return NULL;
4392 arg = PyTuple_GET_ITEM(args, 0);
4393 i = getindex(self, arg);
4394 if (i == -1 && PyErr_Occurred())
4395 return NULL;
4396 res = (*func)(self, i, NULL);
4397 if (res == -1 && PyErr_Occurred())
4398 return NULL;
4399 Py_INCREF(Py_None);
4400 return Py_None;
4403 static PyObject *
4404 wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
4406 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4407 Py_ssize_t i, j;
4408 int res;
4409 PyObject *value;
4411 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
4412 return NULL;
4413 res = (*func)(self, i, j, value);
4414 if (res == -1 && PyErr_Occurred())
4415 return NULL;
4416 Py_INCREF(Py_None);
4417 return Py_None;
4420 static PyObject *
4421 wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4423 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4424 Py_ssize_t i, j;
4425 int res;
4427 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4428 return NULL;
4429 res = (*func)(self, i, j, NULL);
4430 if (res == -1 && PyErr_Occurred())
4431 return NULL;
4432 Py_INCREF(Py_None);
4433 return Py_None;
4436 /* XXX objobjproc is a misnomer; should be objargpred */
4437 static PyObject *
4438 wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4440 objobjproc func = (objobjproc)wrapped;
4441 int res;
4442 PyObject *value;
4444 if (!check_num_args(args, 1))
4445 return NULL;
4446 value = PyTuple_GET_ITEM(args, 0);
4447 res = (*func)(self, value);
4448 if (res == -1 && PyErr_Occurred())
4449 return NULL;
4450 else
4451 return PyBool_FromLong(res);
4454 static PyObject *
4455 wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4457 objobjargproc func = (objobjargproc)wrapped;
4458 int res;
4459 PyObject *key, *value;
4461 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4462 return NULL;
4463 res = (*func)(self, key, value);
4464 if (res == -1 && PyErr_Occurred())
4465 return NULL;
4466 Py_INCREF(Py_None);
4467 return Py_None;
4470 static PyObject *
4471 wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4473 objobjargproc func = (objobjargproc)wrapped;
4474 int res;
4475 PyObject *key;
4477 if (!check_num_args(args, 1))
4478 return NULL;
4479 key = PyTuple_GET_ITEM(args, 0);
4480 res = (*func)(self, key, NULL);
4481 if (res == -1 && PyErr_Occurred())
4482 return NULL;
4483 Py_INCREF(Py_None);
4484 return Py_None;
4487 static PyObject *
4488 wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4490 cmpfunc func = (cmpfunc)wrapped;
4491 int res;
4492 PyObject *other;
4494 if (!check_num_args(args, 1))
4495 return NULL;
4496 other = PyTuple_GET_ITEM(args, 0);
4497 if (Py_TYPE(other)->tp_compare != func &&
4498 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
4499 PyErr_Format(
4500 PyExc_TypeError,
4501 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
4502 Py_TYPE(self)->tp_name,
4503 Py_TYPE(self)->tp_name,
4504 Py_TYPE(other)->tp_name);
4505 return NULL;
4507 res = (*func)(self, other);
4508 if (PyErr_Occurred())
4509 return NULL;
4510 return PyInt_FromLong((long)res);
4513 /* Helper to check for object.__setattr__ or __delattr__ applied to a type.
4514 This is called the Carlo Verre hack after its discoverer. */
4515 static int
4516 hackcheck(PyObject *self, setattrofunc func, char *what)
4518 PyTypeObject *type = Py_TYPE(self);
4519 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4520 type = type->tp_base;
4521 /* If type is NULL now, this is a really weird type.
4522 In the spirit of backwards compatibility (?), just shut up. */
4523 if (type && type->tp_setattro != func) {
4524 PyErr_Format(PyExc_TypeError,
4525 "can't apply this %s to %s object",
4526 what,
4527 type->tp_name);
4528 return 0;
4530 return 1;
4533 static PyObject *
4534 wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4536 setattrofunc func = (setattrofunc)wrapped;
4537 int res;
4538 PyObject *name, *value;
4540 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4541 return NULL;
4542 if (!hackcheck(self, func, "__setattr__"))
4543 return NULL;
4544 res = (*func)(self, name, value);
4545 if (res < 0)
4546 return NULL;
4547 Py_INCREF(Py_None);
4548 return Py_None;
4551 static PyObject *
4552 wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4554 setattrofunc func = (setattrofunc)wrapped;
4555 int res;
4556 PyObject *name;
4558 if (!check_num_args(args, 1))
4559 return NULL;
4560 name = PyTuple_GET_ITEM(args, 0);
4561 if (!hackcheck(self, func, "__delattr__"))
4562 return NULL;
4563 res = (*func)(self, name, NULL);
4564 if (res < 0)
4565 return NULL;
4566 Py_INCREF(Py_None);
4567 return Py_None;
4570 static PyObject *
4571 wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4573 hashfunc func = (hashfunc)wrapped;
4574 long res;
4576 if (!check_num_args(args, 0))
4577 return NULL;
4578 res = (*func)(self);
4579 if (res == -1 && PyErr_Occurred())
4580 return NULL;
4581 return PyInt_FromLong(res);
4584 static PyObject *
4585 wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
4587 ternaryfunc func = (ternaryfunc)wrapped;
4589 return (*func)(self, args, kwds);
4592 static PyObject *
4593 wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4595 richcmpfunc func = (richcmpfunc)wrapped;
4596 PyObject *other;
4598 if (!check_num_args(args, 1))
4599 return NULL;
4600 other = PyTuple_GET_ITEM(args, 0);
4601 return (*func)(self, other, op);
4604 #undef RICHCMP_WRAPPER
4605 #define RICHCMP_WRAPPER(NAME, OP) \
4606 static PyObject * \
4607 richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4609 return wrap_richcmpfunc(self, args, wrapped, OP); \
4612 RICHCMP_WRAPPER(lt, Py_LT)
4613 RICHCMP_WRAPPER(le, Py_LE)
4614 RICHCMP_WRAPPER(eq, Py_EQ)
4615 RICHCMP_WRAPPER(ne, Py_NE)
4616 RICHCMP_WRAPPER(gt, Py_GT)
4617 RICHCMP_WRAPPER(ge, Py_GE)
4619 static PyObject *
4620 wrap_next(PyObject *self, PyObject *args, void *wrapped)
4622 unaryfunc func = (unaryfunc)wrapped;
4623 PyObject *res;
4625 if (!check_num_args(args, 0))
4626 return NULL;
4627 res = (*func)(self);
4628 if (res == NULL && !PyErr_Occurred())
4629 PyErr_SetNone(PyExc_StopIteration);
4630 return res;
4633 static PyObject *
4634 wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4636 descrgetfunc func = (descrgetfunc)wrapped;
4637 PyObject *obj;
4638 PyObject *type = NULL;
4640 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4641 return NULL;
4642 if (obj == Py_None)
4643 obj = NULL;
4644 if (type == Py_None)
4645 type = NULL;
4646 if (type == NULL &&obj == NULL) {
4647 PyErr_SetString(PyExc_TypeError,
4648 "__get__(None, None) is invalid");
4649 return NULL;
4651 return (*func)(self, obj, type);
4654 static PyObject *
4655 wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
4657 descrsetfunc func = (descrsetfunc)wrapped;
4658 PyObject *obj, *value;
4659 int ret;
4661 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4662 return NULL;
4663 ret = (*func)(self, obj, value);
4664 if (ret < 0)
4665 return NULL;
4666 Py_INCREF(Py_None);
4667 return Py_None;
4670 static PyObject *
4671 wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4673 descrsetfunc func = (descrsetfunc)wrapped;
4674 PyObject *obj;
4675 int ret;
4677 if (!check_num_args(args, 1))
4678 return NULL;
4679 obj = PyTuple_GET_ITEM(args, 0);
4680 ret = (*func)(self, obj, NULL);
4681 if (ret < 0)
4682 return NULL;
4683 Py_INCREF(Py_None);
4684 return Py_None;
4687 static PyObject *
4688 wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
4690 initproc func = (initproc)wrapped;
4692 if (func(self, args, kwds) < 0)
4693 return NULL;
4694 Py_INCREF(Py_None);
4695 return Py_None;
4698 static PyObject *
4699 tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
4701 PyTypeObject *type, *subtype, *staticbase;
4702 PyObject *arg0, *res;
4704 if (self == NULL || !PyType_Check(self))
4705 Py_FatalError("__new__() called with non-type 'self'");
4706 type = (PyTypeObject *)self;
4707 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4708 PyErr_Format(PyExc_TypeError,
4709 "%s.__new__(): not enough arguments",
4710 type->tp_name);
4711 return NULL;
4713 arg0 = PyTuple_GET_ITEM(args, 0);
4714 if (!PyType_Check(arg0)) {
4715 PyErr_Format(PyExc_TypeError,
4716 "%s.__new__(X): X is not a type object (%s)",
4717 type->tp_name,
4718 Py_TYPE(arg0)->tp_name);
4719 return NULL;
4721 subtype = (PyTypeObject *)arg0;
4722 if (!PyType_IsSubtype(subtype, type)) {
4723 PyErr_Format(PyExc_TypeError,
4724 "%s.__new__(%s): %s is not a subtype of %s",
4725 type->tp_name,
4726 subtype->tp_name,
4727 subtype->tp_name,
4728 type->tp_name);
4729 return NULL;
4732 /* Check that the use doesn't do something silly and unsafe like
4733 object.__new__(dict). To do this, we check that the
4734 most derived base that's not a heap type is this type. */
4735 staticbase = subtype;
4736 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4737 staticbase = staticbase->tp_base;
4738 /* If staticbase is NULL now, it is a really weird type.
4739 In the spirit of backwards compatibility (?), just shut up. */
4740 if (staticbase && staticbase->tp_new != type->tp_new) {
4741 PyErr_Format(PyExc_TypeError,
4742 "%s.__new__(%s) is not safe, use %s.__new__()",
4743 type->tp_name,
4744 subtype->tp_name,
4745 staticbase == NULL ? "?" : staticbase->tp_name);
4746 return NULL;
4749 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4750 if (args == NULL)
4751 return NULL;
4752 res = type->tp_new(subtype, args, kwds);
4753 Py_DECREF(args);
4754 return res;
4757 static struct PyMethodDef tp_new_methoddef[] = {
4758 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4759 PyDoc_STR("T.__new__(S, ...) -> "
4760 "a new object with type S, a subtype of T")},
4764 static int
4765 add_tp_new_wrapper(PyTypeObject *type)
4767 PyObject *func;
4769 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4770 return 0;
4771 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4772 if (func == NULL)
4773 return -1;
4774 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4775 Py_DECREF(func);
4776 return -1;
4778 Py_DECREF(func);
4779 return 0;
4782 /* Slot wrappers that call the corresponding __foo__ slot. See comments
4783 below at override_slots() for more explanation. */
4785 #define SLOT0(FUNCNAME, OPSTR) \
4786 static PyObject * \
4787 FUNCNAME(PyObject *self) \
4789 static PyObject *cache_str; \
4790 return call_method(self, OPSTR, &cache_str, "()"); \
4793 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
4794 static PyObject * \
4795 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
4797 static PyObject *cache_str; \
4798 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
4801 /* Boolean helper for SLOT1BINFULL().
4802 right.__class__ is a nontrivial subclass of left.__class__. */
4803 static int
4804 method_is_overloaded(PyObject *left, PyObject *right, char *name)
4806 PyObject *a, *b;
4807 int ok;
4809 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4810 if (b == NULL) {
4811 PyErr_Clear();
4812 /* If right doesn't have it, it's not overloaded */
4813 return 0;
4816 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4817 if (a == NULL) {
4818 PyErr_Clear();
4819 Py_DECREF(b);
4820 /* If right has it but left doesn't, it's overloaded */
4821 return 1;
4824 ok = PyObject_RichCompareBool(a, b, Py_NE);
4825 Py_DECREF(a);
4826 Py_DECREF(b);
4827 if (ok < 0) {
4828 PyErr_Clear();
4829 return 0;
4832 return ok;
4836 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
4837 static PyObject * \
4838 FUNCNAME(PyObject *self, PyObject *other) \
4840 static PyObject *cache_str, *rcache_str; \
4841 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4842 Py_TYPE(other)->tp_as_number != NULL && \
4843 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4844 if (Py_TYPE(self)->tp_as_number != NULL && \
4845 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4846 PyObject *r; \
4847 if (do_other && \
4848 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4849 method_is_overloaded(self, other, ROPSTR)) { \
4850 r = call_maybe( \
4851 other, ROPSTR, &rcache_str, "(O)", self); \
4852 if (r != Py_NotImplemented) \
4853 return r; \
4854 Py_DECREF(r); \
4855 do_other = 0; \
4857 r = call_maybe( \
4858 self, OPSTR, &cache_str, "(O)", other); \
4859 if (r != Py_NotImplemented || \
4860 Py_TYPE(other) == Py_TYPE(self)) \
4861 return r; \
4862 Py_DECREF(r); \
4864 if (do_other) { \
4865 return call_maybe( \
4866 other, ROPSTR, &rcache_str, "(O)", self); \
4868 Py_INCREF(Py_NotImplemented); \
4869 return Py_NotImplemented; \
4872 #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4873 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4875 #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4876 static PyObject * \
4877 FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4879 static PyObject *cache_str; \
4880 return call_method(self, OPSTR, &cache_str, \
4881 "(" ARGCODES ")", arg1, arg2); \
4884 static Py_ssize_t
4885 slot_sq_length(PyObject *self)
4887 static PyObject *len_str;
4888 PyObject *res = call_method(self, "__len__", &len_str, "()");
4889 Py_ssize_t len;
4891 if (res == NULL)
4892 return -1;
4893 len = PyInt_AsSsize_t(res);
4894 Py_DECREF(res);
4895 if (len < 0) {
4896 if (!PyErr_Occurred())
4897 PyErr_SetString(PyExc_ValueError,
4898 "__len__() should return >= 0");
4899 return -1;
4901 return len;
4904 /* Super-optimized version of slot_sq_item.
4905 Other slots could do the same... */
4906 static PyObject *
4907 slot_sq_item(PyObject *self, Py_ssize_t i)
4909 static PyObject *getitem_str;
4910 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4911 descrgetfunc f;
4913 if (getitem_str == NULL) {
4914 getitem_str = PyString_InternFromString("__getitem__");
4915 if (getitem_str == NULL)
4916 return NULL;
4918 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4919 if (func != NULL) {
4920 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4921 Py_INCREF(func);
4922 else {
4923 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4924 if (func == NULL) {
4925 return NULL;
4928 ival = PyInt_FromSsize_t(i);
4929 if (ival != NULL) {
4930 args = PyTuple_New(1);
4931 if (args != NULL) {
4932 PyTuple_SET_ITEM(args, 0, ival);
4933 retval = PyObject_Call(func, args, NULL);
4934 Py_XDECREF(args);
4935 Py_XDECREF(func);
4936 return retval;
4940 else {
4941 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4943 Py_XDECREF(args);
4944 Py_XDECREF(ival);
4945 Py_XDECREF(func);
4946 return NULL;
4949 static PyObject*
4950 slot_sq_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j)
4952 static PyObject *getslice_str;
4954 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
4955 "use __getitem__", 1) < 0)
4956 return NULL;
4957 return call_method(self, "__getslice__", &getslice_str,
4958 "nn", i, j);
4961 static int
4962 slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
4964 PyObject *res;
4965 static PyObject *delitem_str, *setitem_str;
4967 if (value == NULL)
4968 res = call_method(self, "__delitem__", &delitem_str,
4969 "(n)", index);
4970 else
4971 res = call_method(self, "__setitem__", &setitem_str,
4972 "(nO)", index, value);
4973 if (res == NULL)
4974 return -1;
4975 Py_DECREF(res);
4976 return 0;
4979 static int
4980 slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
4982 PyObject *res;
4983 static PyObject *delslice_str, *setslice_str;
4985 if (value == NULL) {
4986 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been removed; "
4987 "use __delitem__", 1) < 0)
4988 return -1;
4989 res = call_method(self, "__delslice__", &delslice_str,
4990 "(nn)", i, j);
4992 else {
4993 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been removed; "
4994 "use __setitem__", 1) < 0)
4995 return -1;
4996 res = call_method(self, "__setslice__", &setslice_str,
4997 "(nnO)", i, j, value);
4999 if (res == NULL)
5000 return -1;
5001 Py_DECREF(res);
5002 return 0;
5005 static int
5006 slot_sq_contains(PyObject *self, PyObject *value)
5008 PyObject *func, *res, *args;
5009 int result = -1;
5011 static PyObject *contains_str;
5013 func = lookup_maybe(self, "__contains__", &contains_str);
5014 if (func != NULL) {
5015 args = PyTuple_Pack(1, value);
5016 if (args == NULL)
5017 res = NULL;
5018 else {
5019 res = PyObject_Call(func, args, NULL);
5020 Py_DECREF(args);
5022 Py_DECREF(func);
5023 if (res != NULL) {
5024 result = PyObject_IsTrue(res);
5025 Py_DECREF(res);
5028 else if (! PyErr_Occurred()) {
5029 /* Possible results: -1 and 1 */
5030 result = (int)_PySequence_IterSearch(self, value,
5031 PY_ITERSEARCH_CONTAINS);
5033 return result;
5036 #define slot_mp_length slot_sq_length
5038 SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
5040 static int
5041 slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5043 PyObject *res;
5044 static PyObject *delitem_str, *setitem_str;
5046 if (value == NULL)
5047 res = call_method(self, "__delitem__", &delitem_str,
5048 "(O)", key);
5049 else
5050 res = call_method(self, "__setitem__", &setitem_str,
5051 "(OO)", key, value);
5052 if (res == NULL)
5053 return -1;
5054 Py_DECREF(res);
5055 return 0;
5058 SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5059 SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5060 SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
5061 SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
5062 SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5063 SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5065 static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
5067 SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
5068 nb_power, "__pow__", "__rpow__")
5070 static PyObject *
5071 slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5073 static PyObject *pow_str;
5075 if (modulus == Py_None)
5076 return slot_nb_power_binary(self, other);
5077 /* Three-arg power doesn't use __rpow__. But ternary_op
5078 can call this when the second argument's type uses
5079 slot_nb_power, so check before calling self.__pow__. */
5080 if (Py_TYPE(self)->tp_as_number != NULL &&
5081 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
5082 return call_method(self, "__pow__", &pow_str,
5083 "(OO)", other, modulus);
5085 Py_INCREF(Py_NotImplemented);
5086 return Py_NotImplemented;
5089 SLOT0(slot_nb_negative, "__neg__")
5090 SLOT0(slot_nb_positive, "__pos__")
5091 SLOT0(slot_nb_absolute, "__abs__")
5093 static int
5094 slot_nb_nonzero(PyObject *self)
5096 PyObject *func, *args;
5097 static PyObject *nonzero_str, *len_str;
5098 int result = -1;
5100 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
5101 if (func == NULL) {
5102 if (PyErr_Occurred())
5103 return -1;
5104 func = lookup_maybe(self, "__len__", &len_str);
5105 if (func == NULL)
5106 return PyErr_Occurred() ? -1 : 1;
5108 args = PyTuple_New(0);
5109 if (args != NULL) {
5110 PyObject *temp = PyObject_Call(func, args, NULL);
5111 Py_DECREF(args);
5112 if (temp != NULL) {
5113 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
5114 result = PyObject_IsTrue(temp);
5115 else {
5116 PyErr_Format(PyExc_TypeError,
5117 "__nonzero__ should return "
5118 "bool or int, returned %s",
5119 temp->ob_type->tp_name);
5120 result = -1;
5122 Py_DECREF(temp);
5125 Py_DECREF(func);
5126 return result;
5130 static PyObject *
5131 slot_nb_index(PyObject *self)
5133 static PyObject *index_str;
5134 return call_method(self, "__index__", &index_str, "()");
5138 SLOT0(slot_nb_invert, "__invert__")
5139 SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5140 SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5141 SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5142 SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5143 SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
5145 static int
5146 slot_nb_coerce(PyObject **a, PyObject **b)
5148 static PyObject *coerce_str;
5149 PyObject *self = *a, *other = *b;
5151 if (self->ob_type->tp_as_number != NULL &&
5152 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5153 PyObject *r;
5154 r = call_maybe(
5155 self, "__coerce__", &coerce_str, "(O)", other);
5156 if (r == NULL)
5157 return -1;
5158 if (r == Py_NotImplemented) {
5159 Py_DECREF(r);
5161 else {
5162 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5163 PyErr_SetString(PyExc_TypeError,
5164 "__coerce__ didn't return a 2-tuple");
5165 Py_DECREF(r);
5166 return -1;
5168 *a = PyTuple_GET_ITEM(r, 0);
5169 Py_INCREF(*a);
5170 *b = PyTuple_GET_ITEM(r, 1);
5171 Py_INCREF(*b);
5172 Py_DECREF(r);
5173 return 0;
5176 if (other->ob_type->tp_as_number != NULL &&
5177 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5178 PyObject *r;
5179 r = call_maybe(
5180 other, "__coerce__", &coerce_str, "(O)", self);
5181 if (r == NULL)
5182 return -1;
5183 if (r == Py_NotImplemented) {
5184 Py_DECREF(r);
5185 return 1;
5187 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5188 PyErr_SetString(PyExc_TypeError,
5189 "__coerce__ didn't return a 2-tuple");
5190 Py_DECREF(r);
5191 return -1;
5193 *a = PyTuple_GET_ITEM(r, 1);
5194 Py_INCREF(*a);
5195 *b = PyTuple_GET_ITEM(r, 0);
5196 Py_INCREF(*b);
5197 Py_DECREF(r);
5198 return 0;
5200 return 1;
5203 SLOT0(slot_nb_int, "__int__")
5204 SLOT0(slot_nb_long, "__long__")
5205 SLOT0(slot_nb_float, "__float__")
5206 SLOT0(slot_nb_oct, "__oct__")
5207 SLOT0(slot_nb_hex, "__hex__")
5208 SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5209 SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5210 SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5211 SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
5212 SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
5213 /* Can't use SLOT1 here, because nb_inplace_power is ternary */
5214 static PyObject *
5215 slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5217 static PyObject *cache_str;
5218 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
5220 SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5221 SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5222 SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5223 SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5224 SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5225 SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
5226 "__floordiv__", "__rfloordiv__")
5227 SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5228 SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5229 SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
5231 static int
5232 half_compare(PyObject *self, PyObject *other)
5234 PyObject *func, *args, *res;
5235 static PyObject *cmp_str;
5236 Py_ssize_t c;
5238 func = lookup_method(self, "__cmp__", &cmp_str);
5239 if (func == NULL) {
5240 PyErr_Clear();
5242 else {
5243 args = PyTuple_Pack(1, other);
5244 if (args == NULL)
5245 res = NULL;
5246 else {
5247 res = PyObject_Call(func, args, NULL);
5248 Py_DECREF(args);
5250 Py_DECREF(func);
5251 if (res != Py_NotImplemented) {
5252 if (res == NULL)
5253 return -2;
5254 c = PyInt_AsLong(res);
5255 Py_DECREF(res);
5256 if (c == -1 && PyErr_Occurred())
5257 return -2;
5258 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5260 Py_DECREF(res);
5262 return 2;
5265 /* This slot is published for the benefit of try_3way_compare in object.c */
5267 _PyObject_SlotCompare(PyObject *self, PyObject *other)
5269 int c;
5271 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
5272 c = half_compare(self, other);
5273 if (c <= 1)
5274 return c;
5276 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
5277 c = half_compare(other, self);
5278 if (c < -1)
5279 return -2;
5280 if (c <= 1)
5281 return -c;
5283 return (void *)self < (void *)other ? -1 :
5284 (void *)self > (void *)other ? 1 : 0;
5287 static PyObject *
5288 slot_tp_repr(PyObject *self)
5290 PyObject *func, *res;
5291 static PyObject *repr_str;
5293 func = lookup_method(self, "__repr__", &repr_str);
5294 if (func != NULL) {
5295 res = PyEval_CallObject(func, NULL);
5296 Py_DECREF(func);
5297 return res;
5299 PyErr_Clear();
5300 return PyString_FromFormat("<%s object at %p>",
5301 Py_TYPE(self)->tp_name, self);
5304 static PyObject *
5305 slot_tp_str(PyObject *self)
5307 PyObject *func, *res;
5308 static PyObject *str_str;
5310 func = lookup_method(self, "__str__", &str_str);
5311 if (func != NULL) {
5312 res = PyEval_CallObject(func, NULL);
5313 Py_DECREF(func);
5314 return res;
5316 else {
5317 PyErr_Clear();
5318 return slot_tp_repr(self);
5322 static long
5323 slot_tp_hash(PyObject *self)
5325 PyObject *func;
5326 static PyObject *hash_str, *eq_str, *cmp_str;
5327 long h;
5329 func = lookup_method(self, "__hash__", &hash_str);
5331 if (func != NULL && func != Py_None) {
5332 PyObject *res = PyEval_CallObject(func, NULL);
5333 Py_DECREF(func);
5334 if (res == NULL)
5335 return -1;
5336 if (PyLong_Check(res))
5337 h = PyLong_Type.tp_hash(res);
5338 else
5339 h = PyInt_AsLong(res);
5340 Py_DECREF(res);
5342 else {
5343 Py_XDECREF(func); /* may be None */
5344 PyErr_Clear();
5345 func = lookup_method(self, "__eq__", &eq_str);
5346 if (func == NULL) {
5347 PyErr_Clear();
5348 func = lookup_method(self, "__cmp__", &cmp_str);
5350 if (func != NULL) {
5351 Py_DECREF(func);
5352 return PyObject_HashNotImplemented(self);
5354 PyErr_Clear();
5355 h = _Py_HashPointer((void *)self);
5357 if (h == -1 && !PyErr_Occurred())
5358 h = -2;
5359 return h;
5362 static PyObject *
5363 slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5365 static PyObject *call_str;
5366 PyObject *meth = lookup_method(self, "__call__", &call_str);
5367 PyObject *res;
5369 if (meth == NULL)
5370 return NULL;
5372 res = PyObject_Call(meth, args, kwds);
5374 Py_DECREF(meth);
5375 return res;
5378 /* There are two slot dispatch functions for tp_getattro.
5380 - slot_tp_getattro() is used when __getattribute__ is overridden
5381 but no __getattr__ hook is present;
5383 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5385 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5386 detects the absence of __getattr__ and then installs the simpler slot if
5387 necessary. */
5389 static PyObject *
5390 slot_tp_getattro(PyObject *self, PyObject *name)
5392 static PyObject *getattribute_str = NULL;
5393 return call_method(self, "__getattribute__", &getattribute_str,
5394 "(O)", name);
5397 static PyObject *
5398 call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5400 PyObject *res, *descr = NULL;
5401 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
5403 if (f != NULL) {
5404 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5405 if (descr == NULL)
5406 return NULL;
5407 else
5408 attr = descr;
5410 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5411 Py_XDECREF(descr);
5412 return res;
5415 static PyObject *
5416 slot_tp_getattr_hook(PyObject *self, PyObject *name)
5418 PyTypeObject *tp = Py_TYPE(self);
5419 PyObject *getattr, *getattribute, *res;
5420 static PyObject *getattribute_str = NULL;
5421 static PyObject *getattr_str = NULL;
5423 if (getattr_str == NULL) {
5424 getattr_str = PyString_InternFromString("__getattr__");
5425 if (getattr_str == NULL)
5426 return NULL;
5428 if (getattribute_str == NULL) {
5429 getattribute_str =
5430 PyString_InternFromString("__getattribute__");
5431 if (getattribute_str == NULL)
5432 return NULL;
5434 /* speed hack: we could use lookup_maybe, but that would resolve the
5435 method fully for each attribute lookup for classes with
5436 __getattr__, even when the attribute is present. So we use
5437 _PyType_Lookup and create the method only when needed, with
5438 call_attribute. */
5439 getattr = _PyType_Lookup(tp, getattr_str);
5440 if (getattr == NULL) {
5441 /* No __getattr__ hook: use a simpler dispatcher */
5442 tp->tp_getattro = slot_tp_getattro;
5443 return slot_tp_getattro(self, name);
5445 Py_INCREF(getattr);
5446 /* speed hack: we could use lookup_maybe, but that would resolve the
5447 method fully for each attribute lookup for classes with
5448 __getattr__, even when self has the default __getattribute__
5449 method. So we use _PyType_Lookup and create the method only when
5450 needed, with call_attribute. */
5451 getattribute = _PyType_Lookup(tp, getattribute_str);
5452 if (getattribute == NULL ||
5453 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5454 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5455 (void *)PyObject_GenericGetAttr))
5456 res = PyObject_GenericGetAttr(self, name);
5457 else {
5458 Py_INCREF(getattribute);
5459 res = call_attribute(self, getattribute, name);
5460 Py_DECREF(getattribute);
5462 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5463 PyErr_Clear();
5464 res = call_attribute(self, getattr, name);
5466 Py_DECREF(getattr);
5467 return res;
5470 static int
5471 slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5473 PyObject *res;
5474 static PyObject *delattr_str, *setattr_str;
5476 if (value == NULL)
5477 res = call_method(self, "__delattr__", &delattr_str,
5478 "(O)", name);
5479 else
5480 res = call_method(self, "__setattr__", &setattr_str,
5481 "(OO)", name, value);
5482 if (res == NULL)
5483 return -1;
5484 Py_DECREF(res);
5485 return 0;
5488 static char *name_op[] = {
5489 "__lt__",
5490 "__le__",
5491 "__eq__",
5492 "__ne__",
5493 "__gt__",
5494 "__ge__",
5497 static PyObject *
5498 half_richcompare(PyObject *self, PyObject *other, int op)
5500 PyObject *func, *args, *res;
5501 static PyObject *op_str[6];
5503 func = lookup_method(self, name_op[op], &op_str[op]);
5504 if (func == NULL) {
5505 PyErr_Clear();
5506 Py_INCREF(Py_NotImplemented);
5507 return Py_NotImplemented;
5509 args = PyTuple_Pack(1, other);
5510 if (args == NULL)
5511 res = NULL;
5512 else {
5513 res = PyObject_Call(func, args, NULL);
5514 Py_DECREF(args);
5516 Py_DECREF(func);
5517 return res;
5520 static PyObject *
5521 slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5523 PyObject *res;
5525 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
5526 res = half_richcompare(self, other, op);
5527 if (res != Py_NotImplemented)
5528 return res;
5529 Py_DECREF(res);
5531 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
5532 res = half_richcompare(other, self, _Py_SwappedOp[op]);
5533 if (res != Py_NotImplemented) {
5534 return res;
5536 Py_DECREF(res);
5538 Py_INCREF(Py_NotImplemented);
5539 return Py_NotImplemented;
5542 static PyObject *
5543 slot_tp_iter(PyObject *self)
5545 PyObject *func, *res;
5546 static PyObject *iter_str, *getitem_str;
5548 func = lookup_method(self, "__iter__", &iter_str);
5549 if (func != NULL) {
5550 PyObject *args;
5551 args = res = PyTuple_New(0);
5552 if (args != NULL) {
5553 res = PyObject_Call(func, args, NULL);
5554 Py_DECREF(args);
5556 Py_DECREF(func);
5557 return res;
5559 PyErr_Clear();
5560 func = lookup_method(self, "__getitem__", &getitem_str);
5561 if (func == NULL) {
5562 PyErr_Format(PyExc_TypeError,
5563 "'%.200s' object is not iterable",
5564 Py_TYPE(self)->tp_name);
5565 return NULL;
5567 Py_DECREF(func);
5568 return PySeqIter_New(self);
5571 static PyObject *
5572 slot_tp_iternext(PyObject *self)
5574 static PyObject *next_str;
5575 return call_method(self, "next", &next_str, "()");
5578 static PyObject *
5579 slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5581 PyTypeObject *tp = Py_TYPE(self);
5582 PyObject *get;
5583 static PyObject *get_str = NULL;
5585 if (get_str == NULL) {
5586 get_str = PyString_InternFromString("__get__");
5587 if (get_str == NULL)
5588 return NULL;
5590 get = _PyType_Lookup(tp, get_str);
5591 if (get == NULL) {
5592 /* Avoid further slowdowns */
5593 if (tp->tp_descr_get == slot_tp_descr_get)
5594 tp->tp_descr_get = NULL;
5595 Py_INCREF(self);
5596 return self;
5598 if (obj == NULL)
5599 obj = Py_None;
5600 if (type == NULL)
5601 type = Py_None;
5602 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
5605 static int
5606 slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5608 PyObject *res;
5609 static PyObject *del_str, *set_str;
5611 if (value == NULL)
5612 res = call_method(self, "__delete__", &del_str,
5613 "(O)", target);
5614 else
5615 res = call_method(self, "__set__", &set_str,
5616 "(OO)", target, value);
5617 if (res == NULL)
5618 return -1;
5619 Py_DECREF(res);
5620 return 0;
5623 static int
5624 slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5626 static PyObject *init_str;
5627 PyObject *meth = lookup_method(self, "__init__", &init_str);
5628 PyObject *res;
5630 if (meth == NULL)
5631 return -1;
5632 res = PyObject_Call(meth, args, kwds);
5633 Py_DECREF(meth);
5634 if (res == NULL)
5635 return -1;
5636 if (res != Py_None) {
5637 PyErr_Format(PyExc_TypeError,
5638 "__init__() should return None, not '%.200s'",
5639 Py_TYPE(res)->tp_name);
5640 Py_DECREF(res);
5641 return -1;
5643 Py_DECREF(res);
5644 return 0;
5647 static PyObject *
5648 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5650 static PyObject *new_str;
5651 PyObject *func;
5652 PyObject *newargs, *x;
5653 Py_ssize_t i, n;
5655 if (new_str == NULL) {
5656 new_str = PyString_InternFromString("__new__");
5657 if (new_str == NULL)
5658 return NULL;
5660 func = PyObject_GetAttr((PyObject *)type, new_str);
5661 if (func == NULL)
5662 return NULL;
5663 assert(PyTuple_Check(args));
5664 n = PyTuple_GET_SIZE(args);
5665 newargs = PyTuple_New(n+1);
5666 if (newargs == NULL)
5667 return NULL;
5668 Py_INCREF(type);
5669 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5670 for (i = 0; i < n; i++) {
5671 x = PyTuple_GET_ITEM(args, i);
5672 Py_INCREF(x);
5673 PyTuple_SET_ITEM(newargs, i+1, x);
5675 x = PyObject_Call(func, newargs, kwds);
5676 Py_DECREF(newargs);
5677 Py_DECREF(func);
5678 return x;
5681 static void
5682 slot_tp_del(PyObject *self)
5684 static PyObject *del_str = NULL;
5685 PyObject *del, *res;
5686 PyObject *error_type, *error_value, *error_traceback;
5688 /* Temporarily resurrect the object. */
5689 assert(self->ob_refcnt == 0);
5690 self->ob_refcnt = 1;
5692 /* Save the current exception, if any. */
5693 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5695 /* Execute __del__ method, if any. */
5696 del = lookup_maybe(self, "__del__", &del_str);
5697 if (del != NULL) {
5698 res = PyEval_CallObject(del, NULL);
5699 if (res == NULL)
5700 PyErr_WriteUnraisable(del);
5701 else
5702 Py_DECREF(res);
5703 Py_DECREF(del);
5706 /* Restore the saved exception. */
5707 PyErr_Restore(error_type, error_value, error_traceback);
5709 /* Undo the temporary resurrection; can't use DECREF here, it would
5710 * cause a recursive call.
5712 assert(self->ob_refcnt > 0);
5713 if (--self->ob_refcnt == 0)
5714 return; /* this is the normal path out */
5716 /* __del__ resurrected it! Make it look like the original Py_DECREF
5717 * never happened.
5720 Py_ssize_t refcnt = self->ob_refcnt;
5721 _Py_NewReference(self);
5722 self->ob_refcnt = refcnt;
5724 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5725 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5726 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5727 * we need to undo that. */
5728 _Py_DEC_REFTOTAL;
5729 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5730 * chain, so no more to do there.
5731 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5732 * _Py_NewReference bumped tp_allocs: both of those need to be
5733 * undone.
5735 #ifdef COUNT_ALLOCS
5736 --Py_TYPE(self)->tp_frees;
5737 --Py_TYPE(self)->tp_allocs;
5738 #endif
5742 /* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
5743 functions. The offsets here are relative to the 'PyHeapTypeObject'
5744 structure, which incorporates the additional structures used for numbers,
5745 sequences and mappings.
5746 Note that multiple names may map to the same slot (e.g. __eq__,
5747 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
5748 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5749 terminated with an all-zero entry. (This table is further initialized and
5750 sorted in init_slotdefs() below.) */
5752 typedef struct wrapperbase slotdef;
5754 #undef TPSLOT
5755 #undef FLSLOT
5756 #undef ETSLOT
5757 #undef SQSLOT
5758 #undef MPSLOT
5759 #undef NBSLOT
5760 #undef UNSLOT
5761 #undef IBSLOT
5762 #undef BINSLOT
5763 #undef RBINSLOT
5765 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5766 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5767 PyDoc_STR(DOC)}
5768 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5769 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5770 PyDoc_STR(DOC), FLAGS}
5771 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5772 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5773 PyDoc_STR(DOC)}
5774 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5775 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5776 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5777 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5778 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5779 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5780 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5781 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5782 "x." NAME "() <==> " DOC)
5783 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5784 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5785 "x." NAME "(y) <==> x" DOC "y")
5786 #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5787 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5788 "x." NAME "(y) <==> x" DOC "y")
5789 #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5790 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5791 "x." NAME "(y) <==> y" DOC "x")
5792 #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5793 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5794 "x." NAME "(y) <==> " DOC)
5795 #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5796 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5797 "x." NAME "(y) <==> " DOC)
5799 static slotdef slotdefs[] = {
5800 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5801 "x.__len__() <==> len(x)"),
5802 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5803 The logic in abstract.c always falls back to nb_add/nb_multiply in
5804 this case. Defining both the nb_* and the sq_* slots to call the
5805 user-defined methods has unexpected side-effects, as shown by
5806 test_descr.notimplemented() */
5807 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5808 "x.__add__(y) <==> x+y"),
5809 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5810 "x.__mul__(n) <==> x*n"),
5811 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5812 "x.__rmul__(n) <==> n*x"),
5813 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5814 "x.__getitem__(y) <==> x[y]"),
5815 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
5816 "x.__getslice__(i, j) <==> x[i:j]\n\
5818 Use of negative indices is not supported."),
5819 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5820 "x.__setitem__(i, y) <==> x[i]=y"),
5821 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5822 "x.__delitem__(y) <==> del x[y]"),
5823 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
5824 wrap_ssizessizeobjargproc,
5825 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5827 Use of negative indices is not supported."),
5828 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
5829 "x.__delslice__(i, j) <==> del x[i:j]\n\
5831 Use of negative indices is not supported."),
5832 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5833 "x.__contains__(y) <==> y in x"),
5834 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5835 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5836 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5837 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
5839 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5840 "x.__len__() <==> len(x)"),
5841 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5842 wrap_binaryfunc,
5843 "x.__getitem__(y) <==> x[y]"),
5844 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5845 wrap_objobjargproc,
5846 "x.__setitem__(i, y) <==> x[i]=y"),
5847 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5848 wrap_delitem,
5849 "x.__delitem__(y) <==> del x[y]"),
5851 BINSLOT("__add__", nb_add, slot_nb_add,
5852 "+"),
5853 RBINSLOT("__radd__", nb_add, slot_nb_add,
5854 "+"),
5855 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5856 "-"),
5857 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5858 "-"),
5859 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5860 "*"),
5861 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5862 "*"),
5863 BINSLOT("__div__", nb_divide, slot_nb_divide,
5864 "/"),
5865 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5866 "/"),
5867 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5868 "%"),
5869 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5870 "%"),
5871 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5872 "divmod(x, y)"),
5873 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5874 "divmod(y, x)"),
5875 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5876 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5877 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5878 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5879 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5880 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5881 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5882 "abs(x)"),
5883 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
5884 "x != 0"),
5885 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5886 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5887 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5888 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5889 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5890 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5891 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5892 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5893 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5894 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5895 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5896 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5897 "x.__coerce__(y) <==> coerce(x, y)"),
5898 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5899 "int(x)"),
5900 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5901 "long(x)"),
5902 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5903 "float(x)"),
5904 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5905 "oct(x)"),
5906 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5907 "hex(x)"),
5908 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5909 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5910 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5911 wrap_binaryfunc, "+"),
5912 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5913 wrap_binaryfunc, "-"),
5914 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5915 wrap_binaryfunc, "*"),
5916 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5917 wrap_binaryfunc, "/"),
5918 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5919 wrap_binaryfunc, "%"),
5920 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5921 wrap_binaryfunc, "**"),
5922 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5923 wrap_binaryfunc, "<<"),
5924 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5925 wrap_binaryfunc, ">>"),
5926 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5927 wrap_binaryfunc, "&"),
5928 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5929 wrap_binaryfunc, "^"),
5930 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5931 wrap_binaryfunc, "|"),
5932 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5933 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5934 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5935 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5936 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5937 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5938 IBSLOT("__itruediv__", nb_inplace_true_divide,
5939 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
5941 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5942 "x.__str__() <==> str(x)"),
5943 TPSLOT("__str__", tp_print, NULL, NULL, ""),
5944 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5945 "x.__repr__() <==> repr(x)"),
5946 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
5947 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5948 "x.__cmp__(y) <==> cmp(x,y)"),
5949 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5950 "x.__hash__() <==> hash(x)"),
5951 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5952 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5953 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5954 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5955 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5956 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5957 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5958 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5959 "x.__setattr__('name', value) <==> x.name = value"),
5960 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5961 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5962 "x.__delattr__('name') <==> del x.name"),
5963 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5964 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5965 "x.__lt__(y) <==> x<y"),
5966 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5967 "x.__le__(y) <==> x<=y"),
5968 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5969 "x.__eq__(y) <==> x==y"),
5970 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5971 "x.__ne__(y) <==> x!=y"),
5972 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5973 "x.__gt__(y) <==> x>y"),
5974 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5975 "x.__ge__(y) <==> x>=y"),
5976 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5977 "x.__iter__() <==> iter(x)"),
5978 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5979 "x.next() -> the next value, or raise StopIteration"),
5980 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5981 "descr.__get__(obj[, type]) -> value"),
5982 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5983 "descr.__set__(obj, value)"),
5984 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5985 wrap_descr_delete, "descr.__delete__(obj)"),
5986 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5987 "x.__init__(...) initializes x; "
5988 "see x.__class__.__doc__ for signature",
5989 PyWrapperFlag_KEYWORDS),
5990 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5991 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5992 {NULL}
5995 /* Given a type pointer and an offset gotten from a slotdef entry, return a
5996 pointer to the actual slot. This is not quite the same as simply adding
5997 the offset to the type pointer, since it takes care to indirect through the
5998 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5999 indirection pointer is NULL. */
6000 static void **
6001 slotptr(PyTypeObject *type, int ioffset)
6003 char *ptr;
6004 long offset = ioffset;
6006 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6007 assert(offset >= 0);
6008 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6009 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6010 ptr = (char *)type->tp_as_sequence;
6011 offset -= offsetof(PyHeapTypeObject, as_sequence);
6013 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6014 ptr = (char *)type->tp_as_mapping;
6015 offset -= offsetof(PyHeapTypeObject, as_mapping);
6017 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6018 ptr = (char *)type->tp_as_number;
6019 offset -= offsetof(PyHeapTypeObject, as_number);
6021 else {
6022 ptr = (char *)type;
6024 if (ptr != NULL)
6025 ptr += offset;
6026 return (void **)ptr;
6029 /* Length of array of slotdef pointers used to store slots with the
6030 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6031 the same __name__, for any __name__. Since that's a static property, it is
6032 appropriate to declare fixed-size arrays for this. */
6033 #define MAX_EQUIV 10
6035 /* Return a slot pointer for a given name, but ONLY if the attribute has
6036 exactly one slot function. The name must be an interned string. */
6037 static void **
6038 resolve_slotdups(PyTypeObject *type, PyObject *name)
6040 /* XXX Maybe this could be optimized more -- but is it worth it? */
6042 /* pname and ptrs act as a little cache */
6043 static PyObject *pname;
6044 static slotdef *ptrs[MAX_EQUIV];
6045 slotdef *p, **pp;
6046 void **res, **ptr;
6048 if (pname != name) {
6049 /* Collect all slotdefs that match name into ptrs. */
6050 pname = name;
6051 pp = ptrs;
6052 for (p = slotdefs; p->name_strobj; p++) {
6053 if (p->name_strobj == name)
6054 *pp++ = p;
6056 *pp = NULL;
6059 /* Look in all matching slots of the type; if exactly one of these has
6060 a filled-in slot, return its value. Otherwise return NULL. */
6061 res = NULL;
6062 for (pp = ptrs; *pp; pp++) {
6063 ptr = slotptr(type, (*pp)->offset);
6064 if (ptr == NULL || *ptr == NULL)
6065 continue;
6066 if (res != NULL)
6067 return NULL;
6068 res = ptr;
6070 return res;
6073 /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
6074 does some incredibly complex thinking and then sticks something into the
6075 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6076 interests, and then stores a generic wrapper or a specific function into
6077 the slot.) Return a pointer to the next slotdef with a different offset,
6078 because that's convenient for fixup_slot_dispatchers(). */
6079 static slotdef *
6080 update_one_slot(PyTypeObject *type, slotdef *p)
6082 PyObject *descr;
6083 PyWrapperDescrObject *d;
6084 void *generic = NULL, *specific = NULL;
6085 int use_generic = 0;
6086 int offset = p->offset;
6087 void **ptr = slotptr(type, offset);
6089 if (ptr == NULL) {
6090 do {
6091 ++p;
6092 } while (p->offset == offset);
6093 return p;
6095 do {
6096 descr = _PyType_Lookup(type, p->name_strobj);
6097 if (descr == NULL) {
6098 if (ptr == (void**)&type->tp_iternext) {
6099 specific = _PyObject_NextNotImplemented;
6101 continue;
6103 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
6104 void **tptr = resolve_slotdups(type, p->name_strobj);
6105 if (tptr == NULL || tptr == ptr)
6106 generic = p->function;
6107 d = (PyWrapperDescrObject *)descr;
6108 if (d->d_base->wrapper == p->wrapper &&
6109 PyType_IsSubtype(type, d->d_type))
6111 if (specific == NULL ||
6112 specific == d->d_wrapped)
6113 specific = d->d_wrapped;
6114 else
6115 use_generic = 1;
6118 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6119 PyCFunction_GET_FUNCTION(descr) ==
6120 (PyCFunction)tp_new_wrapper &&
6121 ptr == (void**)&type->tp_new)
6123 /* The __new__ wrapper is not a wrapper descriptor,
6124 so must be special-cased differently.
6125 If we don't do this, creating an instance will
6126 always use slot_tp_new which will look up
6127 __new__ in the MRO which will call tp_new_wrapper
6128 which will look through the base classes looking
6129 for a static base and call its tp_new (usually
6130 PyType_GenericNew), after performing various
6131 sanity checks and constructing a new argument
6132 list. Cut all that nonsense short -- this speeds
6133 up instance creation tremendously. */
6134 specific = (void *)type->tp_new;
6135 /* XXX I'm not 100% sure that there isn't a hole
6136 in this reasoning that requires additional
6137 sanity checks. I'll buy the first person to
6138 point out a bug in this reasoning a beer. */
6140 else if (descr == Py_None &&
6141 ptr == (void**)&type->tp_hash) {
6142 /* We specifically allow __hash__ to be set to None
6143 to prevent inheritance of the default
6144 implementation from object.__hash__ */
6145 specific = PyObject_HashNotImplemented;
6147 else {
6148 use_generic = 1;
6149 generic = p->function;
6151 } while ((++p)->offset == offset);
6152 if (specific && !use_generic)
6153 *ptr = specific;
6154 else
6155 *ptr = generic;
6156 return p;
6159 /* In the type, update the slots whose slotdefs are gathered in the pp array.
6160 This is a callback for update_subclasses(). */
6161 static int
6162 update_slots_callback(PyTypeObject *type, void *data)
6164 slotdef **pp = (slotdef **)data;
6166 for (; *pp; pp++)
6167 update_one_slot(type, *pp);
6168 return 0;
6171 /* Comparison function for qsort() to compare slotdefs by their offset, and
6172 for equal offset by their address (to force a stable sort). */
6173 static int
6174 slotdef_cmp(const void *aa, const void *bb)
6176 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6177 int c = a->offset - b->offset;
6178 if (c != 0)
6179 return c;
6180 else
6181 /* Cannot use a-b, as this gives off_t,
6182 which may lose precision when converted to int. */
6183 return (a > b) ? 1 : (a < b) ? -1 : 0;
6186 /* Initialize the slotdefs table by adding interned string objects for the
6187 names and sorting the entries. */
6188 static void
6189 init_slotdefs(void)
6191 slotdef *p;
6192 static int initialized = 0;
6194 if (initialized)
6195 return;
6196 for (p = slotdefs; p->name; p++) {
6197 p->name_strobj = PyString_InternFromString(p->name);
6198 if (!p->name_strobj)
6199 Py_FatalError("Out of memory interning slotdef names");
6201 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6202 slotdef_cmp);
6203 initialized = 1;
6206 /* Update the slots after assignment to a class (type) attribute. */
6207 static int
6208 update_slot(PyTypeObject *type, PyObject *name)
6210 slotdef *ptrs[MAX_EQUIV];
6211 slotdef *p;
6212 slotdef **pp;
6213 int offset;
6215 /* Clear the VALID_VERSION flag of 'type' and all its
6216 subclasses. This could possibly be unified with the
6217 update_subclasses() recursion below, but carefully:
6218 they each have their own conditions on which to stop
6219 recursing into subclasses. */
6220 PyType_Modified(type);
6222 init_slotdefs();
6223 pp = ptrs;
6224 for (p = slotdefs; p->name; p++) {
6225 /* XXX assume name is interned! */
6226 if (p->name_strobj == name)
6227 *pp++ = p;
6229 *pp = NULL;
6230 for (pp = ptrs; *pp; pp++) {
6231 p = *pp;
6232 offset = p->offset;
6233 while (p > slotdefs && (p-1)->offset == offset)
6234 --p;
6235 *pp = p;
6237 if (ptrs[0] == NULL)
6238 return 0; /* Not an attribute that affects any slots */
6239 return update_subclasses(type, name,
6240 update_slots_callback, (void *)ptrs);
6243 /* Store the proper functions in the slot dispatches at class (type)
6244 definition time, based upon which operations the class overrides in its
6245 dict. */
6246 static void
6247 fixup_slot_dispatchers(PyTypeObject *type)
6249 slotdef *p;
6251 init_slotdefs();
6252 for (p = slotdefs; p->name; )
6253 p = update_one_slot(type, p);
6256 static void
6257 update_all_slots(PyTypeObject* type)
6259 slotdef *p;
6261 init_slotdefs();
6262 for (p = slotdefs; p->name; p++) {
6263 /* update_slot returns int but can't actually fail */
6264 update_slot(type, p->name_strobj);
6268 /* recurse_down_subclasses() and update_subclasses() are mutually
6269 recursive functions to call a callback for all subclasses,
6270 but refraining from recursing into subclasses that define 'name'. */
6272 static int
6273 update_subclasses(PyTypeObject *type, PyObject *name,
6274 update_callback callback, void *data)
6276 if (callback(type, data) < 0)
6277 return -1;
6278 return recurse_down_subclasses(type, name, callback, data);
6281 static int
6282 recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6283 update_callback callback, void *data)
6285 PyTypeObject *subclass;
6286 PyObject *ref, *subclasses, *dict;
6287 Py_ssize_t i, n;
6289 subclasses = type->tp_subclasses;
6290 if (subclasses == NULL)
6291 return 0;
6292 assert(PyList_Check(subclasses));
6293 n = PyList_GET_SIZE(subclasses);
6294 for (i = 0; i < n; i++) {
6295 ref = PyList_GET_ITEM(subclasses, i);
6296 assert(PyWeakref_CheckRef(ref));
6297 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6298 assert(subclass != NULL);
6299 if ((PyObject *)subclass == Py_None)
6300 continue;
6301 assert(PyType_Check(subclass));
6302 /* Avoid recursing down into unaffected classes */
6303 dict = subclass->tp_dict;
6304 if (dict != NULL && PyDict_Check(dict) &&
6305 PyDict_GetItem(dict, name) != NULL)
6306 continue;
6307 if (update_subclasses(subclass, name, callback, data) < 0)
6308 return -1;
6310 return 0;
6313 /* This function is called by PyType_Ready() to populate the type's
6314 dictionary with method descriptors for function slots. For each
6315 function slot (like tp_repr) that's defined in the type, one or more
6316 corresponding descriptors are added in the type's tp_dict dictionary
6317 under the appropriate name (like __repr__). Some function slots
6318 cause more than one descriptor to be added (for example, the nb_add
6319 slot adds both __add__ and __radd__ descriptors) and some function
6320 slots compete for the same descriptor (for example both sq_item and
6321 mp_subscript generate a __getitem__ descriptor).
6323 In the latter case, the first slotdef entry encoutered wins. Since
6324 slotdef entries are sorted by the offset of the slot in the
6325 PyHeapTypeObject, this gives us some control over disambiguating
6326 between competing slots: the members of PyHeapTypeObject are listed
6327 from most general to least general, so the most general slot is
6328 preferred. In particular, because as_mapping comes before as_sequence,
6329 for a type that defines both mp_subscript and sq_item, mp_subscript
6330 wins.
6332 This only adds new descriptors and doesn't overwrite entries in
6333 tp_dict that were previously defined. The descriptors contain a
6334 reference to the C function they must call, so that it's safe if they
6335 are copied into a subtype's __dict__ and the subtype has a different
6336 C function in its slot -- calling the method defined by the
6337 descriptor will call the C function that was used to create it,
6338 rather than the C function present in the slot when it is called.
6339 (This is important because a subtype may have a C function in the
6340 slot that calls the method from the dictionary, and we want to avoid
6341 infinite recursion here.) */
6343 static int
6344 add_operators(PyTypeObject *type)
6346 PyObject *dict = type->tp_dict;
6347 slotdef *p;
6348 PyObject *descr;
6349 void **ptr;
6351 init_slotdefs();
6352 for (p = slotdefs; p->name; p++) {
6353 if (p->wrapper == NULL)
6354 continue;
6355 ptr = slotptr(type, p->offset);
6356 if (!ptr || !*ptr)
6357 continue;
6358 if (PyDict_GetItem(dict, p->name_strobj))
6359 continue;
6360 if (*ptr == PyObject_HashNotImplemented) {
6361 /* Classes may prevent the inheritance of the tp_hash
6362 slot by storing PyObject_HashNotImplemented in it. Make it
6363 visible as a None value for the __hash__ attribute. */
6364 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6365 return -1;
6367 else {
6368 descr = PyDescr_NewWrapper(type, p, *ptr);
6369 if (descr == NULL)
6370 return -1;
6371 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6372 return -1;
6373 Py_DECREF(descr);
6376 if (type->tp_new != NULL) {
6377 if (add_tp_new_wrapper(type) < 0)
6378 return -1;
6380 return 0;
6384 /* Cooperative 'super' */
6386 typedef struct {
6387 PyObject_HEAD
6388 PyTypeObject *type;
6389 PyObject *obj;
6390 PyTypeObject *obj_type;
6391 } superobject;
6393 static PyMemberDef super_members[] = {
6394 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6395 "the class invoking super()"},
6396 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6397 "the instance invoking super(); may be None"},
6398 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6399 "the type of the instance invoking super(); may be None"},
6403 static void
6404 super_dealloc(PyObject *self)
6406 superobject *su = (superobject *)self;
6408 _PyObject_GC_UNTRACK(self);
6409 Py_XDECREF(su->obj);
6410 Py_XDECREF(su->type);
6411 Py_XDECREF(su->obj_type);
6412 Py_TYPE(self)->tp_free(self);
6415 static PyObject *
6416 super_repr(PyObject *self)
6418 superobject *su = (superobject *)self;
6420 if (su->obj_type)
6421 return PyString_FromFormat(
6422 "<super: <class '%s'>, <%s object>>",
6423 su->type ? su->type->tp_name : "NULL",
6424 su->obj_type->tp_name);
6425 else
6426 return PyString_FromFormat(
6427 "<super: <class '%s'>, NULL>",
6428 su->type ? su->type->tp_name : "NULL");
6431 static PyObject *
6432 super_getattro(PyObject *self, PyObject *name)
6434 superobject *su = (superobject *)self;
6435 int skip = su->obj_type == NULL;
6437 if (!skip) {
6438 /* We want __class__ to return the class of the super object
6439 (i.e. super, or a subclass), not the class of su->obj. */
6440 skip = (PyString_Check(name) &&
6441 PyString_GET_SIZE(name) == 9 &&
6442 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6445 if (!skip) {
6446 PyObject *mro, *res, *tmp, *dict;
6447 PyTypeObject *starttype;
6448 descrgetfunc f;
6449 Py_ssize_t i, n;
6451 starttype = su->obj_type;
6452 mro = starttype->tp_mro;
6454 if (mro == NULL)
6455 n = 0;
6456 else {
6457 assert(PyTuple_Check(mro));
6458 n = PyTuple_GET_SIZE(mro);
6460 for (i = 0; i < n; i++) {
6461 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6462 break;
6464 i++;
6465 res = NULL;
6466 for (; i < n; i++) {
6467 tmp = PyTuple_GET_ITEM(mro, i);
6468 if (PyType_Check(tmp))
6469 dict = ((PyTypeObject *)tmp)->tp_dict;
6470 else if (PyClass_Check(tmp))
6471 dict = ((PyClassObject *)tmp)->cl_dict;
6472 else
6473 continue;
6474 res = PyDict_GetItem(dict, name);
6475 if (res != NULL) {
6476 Py_INCREF(res);
6477 f = Py_TYPE(res)->tp_descr_get;
6478 if (f != NULL) {
6479 tmp = f(res,
6480 /* Only pass 'obj' param if
6481 this is instance-mode super
6482 (See SF ID #743627)
6484 (su->obj == (PyObject *)
6485 su->obj_type
6486 ? (PyObject *)NULL
6487 : su->obj),
6488 (PyObject *)starttype);
6489 Py_DECREF(res);
6490 res = tmp;
6492 return res;
6496 return PyObject_GenericGetAttr(self, name);
6499 static PyTypeObject *
6500 supercheck(PyTypeObject *type, PyObject *obj)
6502 /* Check that a super() call makes sense. Return a type object.
6504 obj can be a new-style class, or an instance of one:
6506 - If it is a class, it must be a subclass of 'type'. This case is
6507 used for class methods; the return value is obj.
6509 - If it is an instance, it must be an instance of 'type'. This is
6510 the normal case; the return value is obj.__class__.
6512 But... when obj is an instance, we want to allow for the case where
6513 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6514 This will allow using super() with a proxy for obj.
6517 /* Check for first bullet above (special case) */
6518 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6519 Py_INCREF(obj);
6520 return (PyTypeObject *)obj;
6523 /* Normal case */
6524 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6525 Py_INCREF(Py_TYPE(obj));
6526 return Py_TYPE(obj);
6528 else {
6529 /* Try the slow way */
6530 static PyObject *class_str = NULL;
6531 PyObject *class_attr;
6533 if (class_str == NULL) {
6534 class_str = PyString_FromString("__class__");
6535 if (class_str == NULL)
6536 return NULL;
6539 class_attr = PyObject_GetAttr(obj, class_str);
6541 if (class_attr != NULL &&
6542 PyType_Check(class_attr) &&
6543 (PyTypeObject *)class_attr != Py_TYPE(obj))
6545 int ok = PyType_IsSubtype(
6546 (PyTypeObject *)class_attr, type);
6547 if (ok)
6548 return (PyTypeObject *)class_attr;
6551 if (class_attr == NULL)
6552 PyErr_Clear();
6553 else
6554 Py_DECREF(class_attr);
6557 PyErr_SetString(PyExc_TypeError,
6558 "super(type, obj): "
6559 "obj must be an instance or subtype of type");
6560 return NULL;
6563 static PyObject *
6564 super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6566 superobject *su = (superobject *)self;
6567 superobject *newobj;
6569 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6570 /* Not binding to an object, or already bound */
6571 Py_INCREF(self);
6572 return self;
6574 if (Py_TYPE(su) != &PySuper_Type)
6575 /* If su is an instance of a (strict) subclass of super,
6576 call its type */
6577 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6578 su->type, obj, NULL);
6579 else {
6580 /* Inline the common case */
6581 PyTypeObject *obj_type = supercheck(su->type, obj);
6582 if (obj_type == NULL)
6583 return NULL;
6584 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6585 NULL, NULL);
6586 if (newobj == NULL)
6587 return NULL;
6588 Py_INCREF(su->type);
6589 Py_INCREF(obj);
6590 newobj->type = su->type;
6591 newobj->obj = obj;
6592 newobj->obj_type = obj_type;
6593 return (PyObject *)newobj;
6597 static int
6598 super_init(PyObject *self, PyObject *args, PyObject *kwds)
6600 superobject *su = (superobject *)self;
6601 PyTypeObject *type;
6602 PyObject *obj = NULL;
6603 PyTypeObject *obj_type = NULL;
6605 if (!_PyArg_NoKeywords("super", kwds))
6606 return -1;
6607 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6608 return -1;
6609 if (obj == Py_None)
6610 obj = NULL;
6611 if (obj != NULL) {
6612 obj_type = supercheck(type, obj);
6613 if (obj_type == NULL)
6614 return -1;
6615 Py_INCREF(obj);
6617 Py_INCREF(type);
6618 su->type = type;
6619 su->obj = obj;
6620 su->obj_type = obj_type;
6621 return 0;
6624 PyDoc_STRVAR(super_doc,
6625 "super(type) -> unbound super object\n"
6626 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
6627 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
6628 "Typical use to call a cooperative superclass method:\n"
6629 "class C(B):\n"
6630 " def meth(self, arg):\n"
6631 " super(C, self).meth(arg)");
6633 static int
6634 super_traverse(PyObject *self, visitproc visit, void *arg)
6636 superobject *su = (superobject *)self;
6638 Py_VISIT(su->obj);
6639 Py_VISIT(su->type);
6640 Py_VISIT(su->obj_type);
6642 return 0;
6645 PyTypeObject PySuper_Type = {
6646 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6647 "super", /* tp_name */
6648 sizeof(superobject), /* tp_basicsize */
6649 0, /* tp_itemsize */
6650 /* methods */
6651 super_dealloc, /* tp_dealloc */
6652 0, /* tp_print */
6653 0, /* tp_getattr */
6654 0, /* tp_setattr */
6655 0, /* tp_compare */
6656 super_repr, /* tp_repr */
6657 0, /* tp_as_number */
6658 0, /* tp_as_sequence */
6659 0, /* tp_as_mapping */
6660 0, /* tp_hash */
6661 0, /* tp_call */
6662 0, /* tp_str */
6663 super_getattro, /* tp_getattro */
6664 0, /* tp_setattro */
6665 0, /* tp_as_buffer */
6666 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6667 Py_TPFLAGS_BASETYPE, /* tp_flags */
6668 super_doc, /* tp_doc */
6669 super_traverse, /* tp_traverse */
6670 0, /* tp_clear */
6671 0, /* tp_richcompare */
6672 0, /* tp_weaklistoffset */
6673 0, /* tp_iter */
6674 0, /* tp_iternext */
6675 0, /* tp_methods */
6676 super_members, /* tp_members */
6677 0, /* tp_getset */
6678 0, /* tp_base */
6679 0, /* tp_dict */
6680 super_descr_get, /* tp_descr_get */
6681 0, /* tp_descr_set */
6682 0, /* tp_dictoffset */
6683 super_init, /* tp_init */
6684 PyType_GenericAlloc, /* tp_alloc */
6685 PyType_GenericNew, /* tp_new */
6686 PyObject_GC_Del, /* tp_free */