2 /* Generic object operations; and implementation of None (NoObject) */
10 /* just for trashcan: */
12 #include "frameobject.h"
13 #include "traceback.h"
15 #if defined( Py_TRACE_REFS ) || defined( Py_REF_DEBUG )
16 DL_IMPORT(long) _Py_RefTotal
;
19 /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
20 These are used by the individual routines for object creation.
21 Do not call them otherwise, they do not initialize the object! */
24 static PyTypeObject
*type_list
;
25 extern int tuple_zero_allocs
, fast_tuple_allocs
;
26 extern int quick_int_allocs
, quick_neg_int_allocs
;
27 extern int null_strings
, one_strings
;
33 for (tp
= type_list
; tp
; tp
= tp
->tp_next
)
34 fprintf(stderr
, "%s alloc'd: %d, freed: %d, max in use: %d\n",
35 tp
->tp_name
, tp
->tp_alloc
, tp
->tp_free
,
37 fprintf(stderr
, "fast tuple allocs: %d, empty: %d\n",
38 fast_tuple_allocs
, tuple_zero_allocs
);
39 fprintf(stderr
, "fast int allocs: pos: %d, neg: %d\n",
40 quick_int_allocs
, quick_neg_int_allocs
);
41 fprintf(stderr
, "null strings: %d, 1-strings: %d\n",
42 null_strings
, one_strings
);
52 result
= PyList_New(0);
55 for (tp
= type_list
; tp
; tp
= tp
->tp_next
) {
56 v
= Py_BuildValue("(siii)", tp
->tp_name
, tp
->tp_alloc
,
57 tp
->tp_free
, tp
->tp_maxalloc
);
62 if (PyList_Append(result
, v
) < 0) {
73 inc_count(PyTypeObject
*tp
)
75 if (tp
->tp_alloc
== 0) {
76 /* first time; insert in linked list */
77 if (tp
->tp_next
!= NULL
) /* sanity check */
78 Py_FatalError("XXX inc_count sanity check");
79 tp
->tp_next
= type_list
;
83 if (tp
->tp_alloc
- tp
->tp_free
> tp
->tp_maxalloc
)
84 tp
->tp_maxalloc
= tp
->tp_alloc
- tp
->tp_free
;
89 PyObject_Init(PyObject
*op
, PyTypeObject
*tp
)
92 PyErr_SetString(PyExc_SystemError
,
93 "NULL object passed to PyObject_Init");
98 op
= (PyObject
*) PyObject_FROM_GC(op
);
100 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
102 _Py_NewReference(op
);
107 PyObject_InitVar(PyVarObject
*op
, PyTypeObject
*tp
, int size
)
110 PyErr_SetString(PyExc_SystemError
,
111 "NULL object passed to PyObject_InitVar");
115 if (PyType_IS_GC(tp
))
116 op
= (PyVarObject
*) PyObject_FROM_GC(op
);
118 /* Any changes should be reflected in PyObject_INIT_VAR */
121 _Py_NewReference((PyObject
*)op
);
126 _PyObject_New(PyTypeObject
*tp
)
129 op
= (PyObject
*) PyObject_MALLOC(_PyObject_SIZE(tp
));
131 return PyErr_NoMemory();
133 if (PyType_IS_GC(tp
))
134 op
= (PyObject
*) PyObject_FROM_GC(op
);
136 return PyObject_INIT(op
, tp
);
140 _PyObject_NewVar(PyTypeObject
*tp
, int size
)
143 op
= (PyVarObject
*) PyObject_MALLOC(_PyObject_VAR_SIZE(tp
, size
));
145 return (PyVarObject
*)PyErr_NoMemory();
147 if (PyType_IS_GC(tp
))
148 op
= (PyVarObject
*) PyObject_FROM_GC(op
);
150 return PyObject_INIT_VAR(op
, tp
, size
);
154 _PyObject_Del(PyObject
*op
)
157 if (op
&& PyType_IS_GC(op
->ob_type
)) {
158 op
= (PyObject
*) PyObject_AS_GC(op
);
164 #ifndef WITH_CYCLE_GC
165 /* extension modules might need these */
166 void _PyGC_Insert(PyObject
*op
) { }
167 void _PyGC_Remove(PyObject
*op
) { }
171 PyObject_Print(PyObject
*op
, FILE *fp
, int flags
)
174 if (PyErr_CheckSignals())
176 #ifdef USE_STACKCHECK
177 if (PyOS_CheckStack()) {
178 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
182 clearerr(fp
); /* Clear any previous error condition */
184 fprintf(fp
, "<nil>");
187 if (op
->ob_refcnt
<= 0)
188 fprintf(fp
, "<refcnt %u at %p>",
190 else if (op
->ob_type
->tp_print
== NULL
) {
191 if (op
->ob_type
->tp_repr
== NULL
) {
192 fprintf(fp
, "<%s object at %p>",
193 op
->ob_type
->tp_name
, op
);
197 if (flags
& Py_PRINT_RAW
)
198 s
= PyObject_Str(op
);
200 s
= PyObject_Repr(op
);
204 ret
= PyObject_Print(s
, fp
,
211 ret
= (*op
->ob_type
->tp_print
)(op
, fp
, flags
);
215 PyErr_SetFromErrno(PyExc_IOError
);
224 PyObject_Repr(PyObject
*v
)
226 if (PyErr_CheckSignals())
228 #ifdef USE_STACKCHECK
229 if (PyOS_CheckStack()) {
230 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
235 return PyString_FromString("<NULL>");
236 else if (v
->ob_type
->tp_repr
== NULL
) {
238 sprintf(buf
, "<%.80s object at %p>",
239 v
->ob_type
->tp_name
, v
);
240 return PyString_FromString(buf
);
244 res
= (*v
->ob_type
->tp_repr
)(v
);
247 if (PyUnicode_Check(res
)) {
249 str
= PyUnicode_AsUnicodeEscapeString(res
);
256 if (!PyString_Check(res
)) {
257 PyErr_Format(PyExc_TypeError
,
258 "__repr__ returned non-string (type %.200s)",
259 res
->ob_type
->tp_name
);
268 PyObject_Str(PyObject
*v
)
273 return PyString_FromString("<NULL>");
274 else if (PyString_Check(v
)) {
278 else if (v
->ob_type
->tp_str
!= NULL
)
279 res
= (*v
->ob_type
->tp_str
)(v
);
282 if (!PyInstance_Check(v
) ||
283 (func
= PyObject_GetAttrString(v
, "__str__")) == NULL
) {
285 return PyObject_Repr(v
);
287 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
292 if (PyUnicode_Check(res
)) {
294 str
= PyUnicode_AsEncodedString(res
, NULL
, NULL
);
301 if (!PyString_Check(res
)) {
302 PyErr_Format(PyExc_TypeError
,
303 "__str__ returned non-string (type %.200s)",
304 res
->ob_type
->tp_name
);
312 do_cmp(PyObject
*v
, PyObject
*w
)
315 /* __rcmp__ actually won't be called unless __cmp__ isn't defined,
316 because the check in cmpobject() reverses the objects first.
317 This is intentional -- it makes no sense to define cmp(x,y)
318 different than -cmp(y,x). */
319 if (PyInstance_Check(v
) || PyInstance_Check(w
))
320 return PyInstance_DoBinOp(v
, w
, "__cmp__", "__rcmp__", do_cmp
);
321 c
= PyObject_Compare(v
, w
);
322 if (c
&& PyErr_Occurred())
324 return PyInt_FromLong(c
);
327 PyObject
*_PyCompareState_Key
;
329 /* _PyCompareState_nesting is incremented before calling compare (for
330 some types) and decremented on exit. If the count exceeds the
331 nesting limit, enable code to detect circular data structures.
334 #define NESTING_LIMIT 60
336 #define NESTING_LIMIT 500
338 int _PyCompareState_nesting
= 0;
341 get_inprogress_dict(void)
343 PyObject
*tstate_dict
, *inprogress
;
345 tstate_dict
= PyThreadState_GetDict();
346 if (tstate_dict
== NULL
) {
347 PyErr_BadInternalCall();
350 inprogress
= PyDict_GetItem(tstate_dict
, _PyCompareState_Key
);
351 if (inprogress
== NULL
) {
352 inprogress
= PyDict_New();
353 if (inprogress
== NULL
)
355 if (PyDict_SetItem(tstate_dict
, _PyCompareState_Key
,
357 Py_DECREF(inprogress
);
360 Py_DECREF(inprogress
);
366 make_pair(PyObject
*v
, PyObject
*w
)
369 Py_uintptr_t iv
= (Py_uintptr_t
)v
;
370 Py_uintptr_t iw
= (Py_uintptr_t
)w
;
372 pair
= PyTuple_New(2);
377 PyTuple_SET_ITEM(pair
, 0, PyLong_FromVoidPtr((void *)v
));
378 PyTuple_SET_ITEM(pair
, 1, PyLong_FromVoidPtr((void *)w
));
380 PyTuple_SET_ITEM(pair
, 0, PyLong_FromVoidPtr((void *)w
));
381 PyTuple_SET_ITEM(pair
, 1, PyLong_FromVoidPtr((void *)v
));
387 PyObject_Compare(PyObject
*v
, PyObject
*w
)
389 PyTypeObject
*vtp
, *wtp
;
392 #if defined(USE_STACKCHECK)
393 if (PyOS_CheckStack()) {
394 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
398 if (v
== NULL
|| w
== NULL
) {
399 PyErr_BadInternalCall();
404 if (PyInstance_Check(v
) || PyInstance_Check(w
)) {
407 if (!PyInstance_Check(v
))
408 return -PyObject_Compare(w
, v
);
409 _PyCompareState_nesting
++;
410 if (_PyCompareState_nesting
> NESTING_LIMIT
) {
411 PyObject
*inprogress
, *pair
;
413 inprogress
= get_inprogress_dict();
414 if (inprogress
== NULL
) {
415 _PyCompareState_nesting
--;
418 pair
= make_pair(v
, w
);
419 if (PyDict_GetItem(inprogress
, pair
)) {
420 /* already comparing these objects. assume
421 they're equal until shown otherwise */
423 _PyCompareState_nesting
--;
426 if (PyDict_SetItem(inprogress
, pair
, pair
) == -1) {
427 _PyCompareState_nesting
--;
431 /* XXX DelItem shouldn't fail */
432 PyDict_DelItem(inprogress
, pair
);
437 _PyCompareState_nesting
--;
440 if (!PyInt_Check(res
)) {
442 PyErr_SetString(PyExc_TypeError
,
443 "comparison did not return an int");
446 c
= PyInt_AsLong(res
);
448 return (c
< 0) ? -1 : (c
> 0) ? 1 : 0;
450 if ((vtp
= v
->ob_type
) != (wtp
= w
->ob_type
)) {
451 char *vname
= vtp
->tp_name
;
452 char *wname
= wtp
->tp_name
;
453 if (vtp
->tp_as_number
!= NULL
&& wtp
->tp_as_number
!= NULL
) {
455 err
= PyNumber_CoerceEx(&v
, &w
);
461 if (vtp
->tp_compare
== NULL
)
462 cmp
= (v
< w
) ? -1 : 1;
464 cmp
= (*vtp
->tp_compare
)(v
, w
);
470 else if (PyUnicode_Check(v
) || PyUnicode_Check(w
)) {
471 int result
= PyUnicode_Compare(v
, w
);
472 if (result
== -1 && PyErr_Occurred() &&
473 PyErr_ExceptionMatches(PyExc_TypeError
))
474 /* TypeErrors are ignored: if Unicode coercion
475 fails due to one of the arguments not
476 having the right type, we continue as
477 defined by the coercion protocol (see
478 above). Luckily, decoding errors are
479 reported as ValueErrors and are not masked
480 by this technique. */
485 else if (vtp
->tp_as_number
!= NULL
)
487 else if (wtp
->tp_as_number
!= NULL
)
489 /* Numerical types compare smaller than all other types */
490 return strcmp(vname
, wname
);
492 if (vtp
->tp_compare
== NULL
) {
493 Py_uintptr_t iv
= (Py_uintptr_t
)v
;
494 Py_uintptr_t iw
= (Py_uintptr_t
)w
;
495 return (iv
< iw
) ? -1 : 1;
497 _PyCompareState_nesting
++;
498 if (_PyCompareState_nesting
> NESTING_LIMIT
499 && (vtp
->tp_as_mapping
500 || (vtp
->tp_as_sequence
&& !PyString_Check(v
)))) {
501 PyObject
*inprogress
, *pair
;
503 inprogress
= get_inprogress_dict();
504 if (inprogress
== NULL
) {
505 _PyCompareState_nesting
--;
508 pair
= make_pair(v
, w
);
509 if (PyDict_GetItem(inprogress
, pair
)) {
510 /* already comparing these objects. assume
511 they're equal until shown otherwise */
513 _PyCompareState_nesting
--;
516 if (PyDict_SetItem(inprogress
, pair
, pair
) == -1) {
517 _PyCompareState_nesting
--;
520 result
= (*vtp
->tp_compare
)(v
, w
);
521 PyDict_DelItem(inprogress
, pair
); /* XXX shouldn't fail */
524 result
= (*vtp
->tp_compare
)(v
, w
);
526 _PyCompareState_nesting
--;
531 /* Set of hash utility functions to help maintaining the invariant that
532 iff a==b then hash(a)==hash(b)
534 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
538 _Py_HashDouble(double v
)
540 double intpart
, fractpart
;
543 long x
; /* the final hash value */
544 /* This is designed so that Python numbers of different types
545 * that compare equal hash to the same value; otherwise comparisons
546 * of mapping keys will turn out weird.
549 #ifdef MPW /* MPW C modf expects pointer to extended as second argument */
552 fractpart
= modf(v
, &e
);
556 fractpart
= modf(v
, &intpart
);
558 if (fractpart
== 0.0) {
559 /* This must return the same hash as an equal int or long. */
560 if (intpart
> LONG_MAX
|| -intpart
> LONG_MAX
) {
561 /* Convert to long and use its hash. */
562 PyObject
*plong
; /* converted to Python long */
563 if (Py_IS_INFINITY(intpart
))
564 /* can't convert to long int -- arbitrary */
565 v
= v
< 0 ? -271828.0 : 314159.0;
566 plong
= PyLong_FromDouble(v
);
569 x
= PyObject_Hash(plong
);
573 /* Fits in a C long == a Python int, so is its own hash. */
579 /* The fractional part is non-zero, so we don't have to worry about
580 * making this match the hash of some other type.
581 * Use frexp to get at the bits in the double.
582 * Since the VAX D double format has 56 mantissa bits, which is the
583 * most of any double format in use, each of these parts may have as
584 * many as (but no more than) 56 significant bits.
585 * So, assuming sizeof(long) >= 4, each part can be broken into two
586 * longs; frexp and multiplication are used to do that.
587 * Also, since the Cray double format has 15 exponent bits, which is
588 * the most of any double format in use, shifting the exponent field
589 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
592 v
*= 2147483648.0; /* 2**31 */
593 hipart
= (long)v
; /* take the top 32 bits */
594 v
= (v
- (double)hipart
) * 2147483648.0; /* get the next 32 bits */
595 x
= hipart
+ (long)v
+ (expo
<< 15);
602 _Py_HashPointer(void *p
)
604 #if SIZEOF_LONG >= SIZEOF_VOID_P
607 /* convert to a Python long and hash that */
611 if ((longobj
= PyLong_FromVoidPtr(p
)) == NULL
) {
615 x
= PyObject_Hash(longobj
);
625 PyObject_Hash(PyObject
*v
)
627 PyTypeObject
*tp
= v
->ob_type
;
628 if (tp
->tp_hash
!= NULL
)
629 return (*tp
->tp_hash
)(v
);
630 if (tp
->tp_compare
== NULL
) {
631 return _Py_HashPointer(v
); /* Use address as hash value */
633 /* If there's a cmp but no hash defined, the object can't be hashed */
634 PyErr_SetString(PyExc_TypeError
, "unhashable type");
639 PyObject_GetAttrString(PyObject
*v
, char *name
)
641 if (v
->ob_type
->tp_getattro
!= NULL
) {
643 w
= PyString_InternFromString(name
);
646 res
= (*v
->ob_type
->tp_getattro
)(v
, w
);
651 if (v
->ob_type
->tp_getattr
== NULL
) {
652 PyErr_Format(PyExc_AttributeError
,
653 "'%.50s' object has no attribute '%.400s'",
659 return (*v
->ob_type
->tp_getattr
)(v
, name
);
664 PyObject_HasAttrString(PyObject
*v
, char *name
)
666 PyObject
*res
= PyObject_GetAttrString(v
, name
);
676 PyObject_SetAttrString(PyObject
*v
, char *name
, PyObject
*w
)
678 if (v
->ob_type
->tp_setattro
!= NULL
) {
681 s
= PyString_InternFromString(name
);
684 res
= (*v
->ob_type
->tp_setattro
)(v
, s
, w
);
689 if (v
->ob_type
->tp_setattr
== NULL
) {
690 if (v
->ob_type
->tp_getattr
== NULL
)
691 PyErr_SetString(PyExc_TypeError
,
692 "attribute-less object (assign or del)");
694 PyErr_SetString(PyExc_TypeError
,
695 "object has read-only attributes");
699 return (*v
->ob_type
->tp_setattr
)(v
, name
, w
);
703 /* Internal API needed by PyObject_GetAttr(): */
705 PyObject
*_PyUnicode_AsDefaultEncodedString(PyObject
*unicode
,
709 PyObject_GetAttr(PyObject
*v
, PyObject
*name
)
711 /* The Unicode to string conversion is done here because the
712 existing tp_getattro slots expect a string object as name
713 and we wouldn't want to break those. */
714 if (PyUnicode_Check(name
)) {
715 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
720 if (!PyString_Check(name
)) {
721 PyErr_SetString(PyExc_TypeError
,
722 "attribute name must be string");
725 if (v
->ob_type
->tp_getattro
!= NULL
)
726 return (*v
->ob_type
->tp_getattro
)(v
, name
);
728 return PyObject_GetAttrString(v
, PyString_AS_STRING(name
));
732 PyObject_HasAttr(PyObject
*v
, PyObject
*name
)
734 PyObject
*res
= PyObject_GetAttr(v
, name
);
744 PyObject_SetAttr(PyObject
*v
, PyObject
*name
, PyObject
*value
)
748 /* The Unicode to string conversion is done here because the
749 existing tp_setattro slots expect a string object as name
750 and we wouldn't want to break those. */
751 if (PyUnicode_Check(name
)) {
752 name
= PyUnicode_AsEncodedString(name
, NULL
, NULL
);
759 if (!PyString_Check(name
)){
760 PyErr_SetString(PyExc_TypeError
,
761 "attribute name must be string");
765 PyString_InternInPlace(&name
);
766 if (v
->ob_type
->tp_setattro
!= NULL
)
767 err
= (*v
->ob_type
->tp_setattro
)(v
, name
, value
);
769 err
= PyObject_SetAttrString(v
,
770 PyString_AS_STRING(name
), value
);
777 /* Test a value used as condition, e.g., in a for or if statement.
778 Return -1 if an error occurred */
781 PyObject_IsTrue(PyObject
*v
)
786 else if (v
->ob_type
->tp_as_number
!= NULL
&&
787 v
->ob_type
->tp_as_number
->nb_nonzero
!= NULL
)
788 res
= (*v
->ob_type
->tp_as_number
->nb_nonzero
)(v
);
789 else if (v
->ob_type
->tp_as_mapping
!= NULL
&&
790 v
->ob_type
->tp_as_mapping
->mp_length
!= NULL
)
791 res
= (*v
->ob_type
->tp_as_mapping
->mp_length
)(v
);
792 else if (v
->ob_type
->tp_as_sequence
!= NULL
&&
793 v
->ob_type
->tp_as_sequence
->sq_length
!= NULL
)
794 res
= (*v
->ob_type
->tp_as_sequence
->sq_length
)(v
);
802 /* equivalent of 'not v'
803 Return -1 if an error occurred */
806 PyObject_Not(PyObject
*v
)
809 res
= PyObject_IsTrue(v
);
815 /* Coerce two numeric types to the "larger" one.
816 Increment the reference count on each argument.
817 Return -1 and raise an exception if no coercion is possible
818 (and then no reference count is incremented).
822 PyNumber_CoerceEx(PyObject
**pv
, PyObject
**pw
)
824 register PyObject
*v
= *pv
;
825 register PyObject
*w
= *pw
;
828 if (v
->ob_type
== w
->ob_type
&& !PyInstance_Check(v
)) {
833 if (v
->ob_type
->tp_as_number
&& v
->ob_type
->tp_as_number
->nb_coerce
) {
834 res
= (*v
->ob_type
->tp_as_number
->nb_coerce
)(pv
, pw
);
838 if (w
->ob_type
->tp_as_number
&& w
->ob_type
->tp_as_number
->nb_coerce
) {
839 res
= (*w
->ob_type
->tp_as_number
->nb_coerce
)(pw
, pv
);
847 PyNumber_Coerce(PyObject
**pv
, PyObject
**pw
)
849 int err
= PyNumber_CoerceEx(pv
, pw
);
852 PyErr_SetString(PyExc_TypeError
, "number coercion failed");
857 /* Test whether an object can be called */
860 PyCallable_Check(PyObject
*x
)
864 if (x
->ob_type
->tp_call
!= NULL
||
865 PyFunction_Check(x
) ||
867 PyCFunction_Check(x
) ||
870 if (PyInstance_Check(x
)) {
871 PyObject
*call
= PyObject_GetAttrString(x
, "__call__");
876 /* Could test recursively but don't, for fear of endless
877 recursion if some joker sets self.__call__ = self */
886 NoObject is usable as a non-NULL undefined value, used by the macro None.
887 There is (and should be!) no way to create other objects of this type,
888 so there is exactly one (which is indestructible, by the way).
893 none_repr(PyObject
*op
)
895 return PyString_FromString("None");
898 static PyTypeObject PyNothing_Type
= {
899 PyObject_HEAD_INIT(&PyType_Type
)
904 0, /*tp_dealloc*/ /*never called*/
909 (reprfunc
)none_repr
, /*tp_repr*/
911 0, /*tp_as_sequence*/
916 PyObject _Py_NoneStruct
= {
917 PyObject_HEAD_INIT(&PyNothing_Type
)
923 static PyObject refchain
= {&refchain
, &refchain
};
926 _Py_ResetReferences(void)
928 refchain
._ob_prev
= refchain
._ob_next
= &refchain
;
933 _Py_NewReference(PyObject
*op
)
937 op
->_ob_next
= refchain
._ob_next
;
938 op
->_ob_prev
= &refchain
;
939 refchain
._ob_next
->_ob_prev
= op
;
940 refchain
._ob_next
= op
;
942 inc_count(op
->ob_type
);
947 _Py_ForgetReference(register PyObject
*op
)
949 #ifdef SLOW_UNREF_CHECK
950 register PyObject
*p
;
952 if (op
->ob_refcnt
< 0)
953 Py_FatalError("UNREF negative refcnt");
954 if (op
== &refchain
||
955 op
->_ob_prev
->_ob_next
!= op
|| op
->_ob_next
->_ob_prev
!= op
)
956 Py_FatalError("UNREF invalid object");
957 #ifdef SLOW_UNREF_CHECK
958 for (p
= refchain
._ob_next
; p
!= &refchain
; p
= p
->_ob_next
) {
962 if (p
== &refchain
) /* Not found */
963 Py_FatalError("UNREF unknown object");
965 op
->_ob_next
->_ob_prev
= op
->_ob_prev
;
966 op
->_ob_prev
->_ob_next
= op
->_ob_next
;
967 op
->_ob_next
= op
->_ob_prev
= NULL
;
969 op
->ob_type
->tp_free
++;
974 _Py_Dealloc(PyObject
*op
)
976 destructor dealloc
= op
->ob_type
->tp_dealloc
;
977 _Py_ForgetReference(op
);
982 _Py_PrintReferences(FILE *fp
)
985 fprintf(fp
, "Remaining objects:\n");
986 for (op
= refchain
._ob_next
; op
!= &refchain
; op
= op
->_ob_next
) {
987 fprintf(fp
, "[%d] ", op
->ob_refcnt
);
988 if (PyObject_Print(op
, fp
, 0) != 0)
995 _Py_GetObjects(PyObject
*self
, PyObject
*args
)
1001 if (!PyArg_ParseTuple(args
, "i|O", &n
, &t
))
1003 op
= refchain
._ob_next
;
1004 res
= PyList_New(0);
1007 for (i
= 0; (n
== 0 || i
< n
) && op
!= &refchain
; i
++) {
1008 while (op
== self
|| op
== args
|| op
== res
|| op
== t
||
1009 t
!= NULL
&& op
->ob_type
!= (PyTypeObject
*) t
) {
1011 if (op
== &refchain
)
1014 if (PyList_Append(res
, op
) < 0) {
1026 /* Hack to force loading of cobject.o */
1027 PyTypeObject
*_Py_cobject_hack
= &PyCObject_Type
;
1030 /* Hack to force loading of abstract.o */
1031 int (*_Py_abstract_hack
)(PyObject
*) = &PyObject_Size
;
1034 /* Python's malloc wrappers (see pymem.h) */
1037 PyMem_Malloc(size_t nbytes
)
1039 #if _PyMem_EXTRA > 0
1041 nbytes
= _PyMem_EXTRA
;
1043 return PyMem_MALLOC(nbytes
);
1047 PyMem_Realloc(void *p
, size_t nbytes
)
1049 #if _PyMem_EXTRA > 0
1051 nbytes
= _PyMem_EXTRA
;
1053 return PyMem_REALLOC(p
, nbytes
);
1063 /* Python's object malloc wrappers (see objimpl.h) */
1066 PyObject_Malloc(size_t nbytes
)
1068 return PyObject_MALLOC(nbytes
);
1072 PyObject_Realloc(void *p
, size_t nbytes
)
1074 return PyObject_REALLOC(p
, nbytes
);
1078 PyObject_Free(void *p
)
1084 /* These methods are used to control infinite recursion in repr, str, print,
1085 etc. Container objects that may recursively contain themselves,
1086 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1087 Py_ReprLeave() to avoid infinite recursion.
1089 Py_ReprEnter() returns 0 the first time it is called for a particular
1090 object and 1 every time thereafter. It returns -1 if an exception
1091 occurred. Py_ReprLeave() has no return value.
1093 See dictobject.c and listobject.c for examples of use.
1096 #define KEY "Py_Repr"
1099 Py_ReprEnter(PyObject
*obj
)
1105 dict
= PyThreadState_GetDict();
1108 list
= PyDict_GetItemString(dict
, KEY
);
1110 list
= PyList_New(0);
1113 if (PyDict_SetItemString(dict
, KEY
, list
) < 0)
1117 i
= PyList_GET_SIZE(list
);
1119 if (PyList_GET_ITEM(list
, i
) == obj
)
1122 PyList_Append(list
, obj
);
1127 Py_ReprLeave(PyObject
*obj
)
1133 dict
= PyThreadState_GetDict();
1136 list
= PyDict_GetItemString(dict
, KEY
);
1137 if (list
== NULL
|| !PyList_Check(list
))
1139 i
= PyList_GET_SIZE(list
);
1140 /* Count backwards because we always expect obj to be list[-1] */
1142 if (PyList_GET_ITEM(list
, i
) == obj
) {
1143 PyList_SetSlice(list
, i
, i
+ 1, NULL
);
1152 non-recursively destroy nested objects
1155 everything is now done in a macro.
1158 modified to use functions, after Tim Peter's suggestion.
1161 modified to restore a possible error.
1164 added better safe than sorry check for threadstate
1167 complete rewrite. We now build a chain via ob_type
1168 and save the limited number of types in ob_refcnt.
1169 This is perfect since we don't need any memory.
1170 A patch for free-threading would need just a lock.
1173 #define Py_TRASHCAN_TUPLE 1
1174 #define Py_TRASHCAN_LIST 2
1175 #define Py_TRASHCAN_DICT 3
1176 #define Py_TRASHCAN_FRAME 4
1177 #define Py_TRASHCAN_TRACEBACK 5
1178 /* extend here if other objects want protection */
1180 int _PyTrash_delete_nesting
= 0;
1182 PyObject
* _PyTrash_delete_later
= NULL
;
1185 _PyTrash_deposit_object(PyObject
*op
)
1189 if (PyTuple_Check(op
))
1190 typecode
= Py_TRASHCAN_TUPLE
;
1191 else if (PyList_Check(op
))
1192 typecode
= Py_TRASHCAN_LIST
;
1193 else if (PyDict_Check(op
))
1194 typecode
= Py_TRASHCAN_DICT
;
1195 else if (PyFrame_Check(op
))
1196 typecode
= Py_TRASHCAN_FRAME
;
1197 else if (PyTraceBack_Check(op
))
1198 typecode
= Py_TRASHCAN_TRACEBACK
;
1199 else /* We have a bug here -- those are the only types in GC */ {
1200 Py_FatalError("Type not supported in GC -- internal bug");
1201 return; /* pacify compiler -- execution never here */
1203 op
->ob_refcnt
= typecode
;
1205 op
->ob_type
= (PyTypeObject
*)_PyTrash_delete_later
;
1206 _PyTrash_delete_later
= op
;
1210 _PyTrash_destroy_chain(void)
1212 while (_PyTrash_delete_later
) {
1213 PyObject
*shredder
= _PyTrash_delete_later
;
1214 _PyTrash_delete_later
= (PyObject
*) shredder
->ob_type
;
1216 switch (shredder
->ob_refcnt
) {
1217 case Py_TRASHCAN_TUPLE
:
1218 shredder
->ob_type
= &PyTuple_Type
;
1220 case Py_TRASHCAN_LIST
:
1221 shredder
->ob_type
= &PyList_Type
;
1223 case Py_TRASHCAN_DICT
:
1224 shredder
->ob_type
= &PyDict_Type
;
1226 case Py_TRASHCAN_FRAME
:
1227 shredder
->ob_type
= &PyFrame_Type
;
1229 case Py_TRASHCAN_TRACEBACK
:
1230 shredder
->ob_type
= &PyTraceBack_Type
;
1233 _Py_NewReference(shredder
);
1235 ++_PyTrash_delete_nesting
;
1236 Py_DECREF(shredder
);
1237 --_PyTrash_delete_nesting
;