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
) {
192 if (flags
& Py_PRINT_RAW
)
193 s
= PyObject_Str(op
);
195 s
= PyObject_Repr(op
);
199 ret
= PyObject_Print(s
, fp
, Py_PRINT_RAW
);
204 ret
= (*op
->ob_type
->tp_print
)(op
, fp
, flags
);
208 PyErr_SetFromErrno(PyExc_IOError
);
216 /* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
217 void _PyObject_Dump(PyObject
* op
)
220 fprintf(stderr
, "NULL\n");
222 (void)PyObject_Print(op
, stderr
, 0);
223 fprintf(stderr
, "\nrefcounts: %d\n", op
->ob_refcnt
);
224 fprintf(stderr
, "address : %p\n", op
);
229 void _PyGC_Dump(PyGC_Head
* op
)
231 _PyObject_Dump(PyObject_FROM_GC(op
));
233 #endif /* WITH_CYCLE_GC */
236 PyObject_Repr(PyObject
*v
)
238 if (PyErr_CheckSignals())
240 #ifdef USE_STACKCHECK
241 if (PyOS_CheckStack()) {
242 PyErr_SetString(PyExc_MemoryError
, "stack overflow");
247 return PyString_FromString("<NULL>");
248 else if (v
->ob_type
->tp_repr
== NULL
) {
250 sprintf(buf
, "<%.80s object at %p>",
251 v
->ob_type
->tp_name
, v
);
252 return PyString_FromString(buf
);
256 res
= (*v
->ob_type
->tp_repr
)(v
);
259 if (PyUnicode_Check(res
)) {
261 str
= PyUnicode_AsUnicodeEscapeString(res
);
268 if (!PyString_Check(res
)) {
269 PyErr_Format(PyExc_TypeError
,
270 "__repr__ returned non-string (type %.200s)",
271 res
->ob_type
->tp_name
);
280 PyObject_Str(PyObject
*v
)
285 return PyString_FromString("<NULL>");
286 if (PyString_Check(v
)) {
290 if (v
->ob_type
->tp_str
== NULL
)
291 return PyObject_Repr(v
);
293 res
= (*v
->ob_type
->tp_str
)(v
);
296 if (PyUnicode_Check(res
)) {
298 str
= PyUnicode_AsEncodedString(res
, NULL
, NULL
);
305 if (!PyString_Check(res
)) {
306 PyErr_Format(PyExc_TypeError
,
307 "__str__ returned non-string (type %.200s)",
308 res
->ob_type
->tp_name
);
316 PyObject_Unicode(PyObject
*v
)
321 res
= PyString_FromString("<NULL>");
322 else if (PyUnicode_Check(v
)) {
326 else if (PyString_Check(v
)) {
330 else if (v
->ob_type
->tp_str
!= NULL
)
331 res
= (*v
->ob_type
->tp_str
)(v
);
334 static PyObject
*strstr
;
335 if (strstr
== NULL
) {
336 strstr
= PyString_InternFromString("__str__");
340 if (!PyInstance_Check(v
) ||
341 (func
= PyObject_GetAttr(v
, strstr
)) == NULL
) {
343 res
= PyObject_Repr(v
);
346 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
352 if (!PyUnicode_Check(res
)) {
354 str
= PyUnicode_FromObject(res
);
365 /* Macro to get the tp_richcompare field of a type if defined */
366 #define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
367 ? (t)->tp_richcompare : NULL)
369 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
370 static int swapped_op
[] = {Py_GT
, Py_GE
, Py_EQ
, Py_NE
, Py_LT
, Py_LE
};
372 /* Try a genuine rich comparison, returning an object. Return:
374 NotImplemented if this particular rich comparison is not implemented or
376 some object not equal to NotImplemented if it is implemented
377 (this latter object may not be a Boolean).
380 try_rich_compare(PyObject
*v
, PyObject
*w
, int op
)
385 if ((f
= RICHCOMPARE(v
->ob_type
)) != NULL
) {
386 res
= (*f
)(v
, w
, op
);
387 if (res
!= Py_NotImplemented
)
391 if ((f
= RICHCOMPARE(w
->ob_type
)) != NULL
) {
392 return (*f
)(w
, v
, swapped_op
[op
]);
394 res
= Py_NotImplemented
;
399 /* Try a genuine rich comparison, returning an int. Return:
400 -1 for exception (including the case where try_rich_compare() returns an
401 object that's not a Boolean);
402 0 if the outcome is false;
403 1 if the outcome is true;
404 2 if this particular rich comparison is not implemented or undefined.
407 try_rich_compare_bool(PyObject
*v
, PyObject
*w
, int op
)
412 if (RICHCOMPARE(v
->ob_type
) == NULL
&& RICHCOMPARE(w
->ob_type
) == NULL
)
413 return 2; /* Shortcut, avoid INCREF+DECREF */
414 res
= try_rich_compare(v
, w
, op
);
417 if (res
== Py_NotImplemented
) {
421 ok
= PyObject_IsTrue(res
);
426 /* Try rich comparisons to determine a 3-way comparison. Return:
431 2 if this particular rich comparison is not implemented or undefined.
434 try_rich_to_3way_compare(PyObject
*v
, PyObject
*w
)
436 static struct { int op
; int outcome
; } tries
[3] = {
437 /* Try this operator, and if it is true, use this outcome: */
444 if (RICHCOMPARE(v
->ob_type
) == NULL
&& RICHCOMPARE(w
->ob_type
) == NULL
)
445 return 2; /* Shortcut */
447 for (i
= 0; i
< 3; i
++) {
448 switch (try_rich_compare_bool(v
, w
, tries
[i
].op
)) {
452 return tries
[i
].outcome
;
459 /* Try a 3-way comparison, returning an int. Return:
464 2 if this particular 3-way comparison is not implemented or undefined.
467 try_3way_compare(PyObject
*v
, PyObject
*w
)
472 /* Comparisons involving instances are given to instance_compare,
473 which has the same return conventions as this function. */
475 if (PyInstance_Check(v
))
476 return (*v
->ob_type
->tp_compare
)(v
, w
);
477 if (PyInstance_Check(w
))
478 return (*w
->ob_type
->tp_compare
)(v
, w
);
480 /* Try coercion; if it fails, give up */
481 c
= PyNumber_CoerceEx(&v
, &w
);
487 /* Try v's comparison, if defined */
488 if ((f
= v
->ob_type
->tp_compare
) != NULL
) {
492 if (c
< 0 && PyErr_Occurred())
494 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
497 /* Try w's comparison, if defined */
498 if ((f
= w
->ob_type
->tp_compare
) != NULL
) {
499 c
= (*f
)(w
, v
); /* swapped! */
502 if (c
< 0 && PyErr_Occurred())
504 return c
< 0 ? 1 : c
> 0 ? -1 : 0; /* negated! */
507 /* No comparison defined */
513 /* Final fallback 3-way comparison, returning an int. Return:
514 -2 if an error occurred;
520 default_3way_compare(PyObject
*v
, PyObject
*w
)
525 if (v
->ob_type
== w
->ob_type
) {
526 /* When comparing these pointers, they must be cast to
527 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
528 * uintptr_t). ANSI specifies that pointer compares other
529 * than == and != to non-related structures are undefined.
531 Py_uintptr_t vv
= (Py_uintptr_t
)v
;
532 Py_uintptr_t ww
= (Py_uintptr_t
)w
;
533 return (vv
< ww
) ? -1 : (vv
> ww
) ? 1 : 0;
536 /* Special case for Unicode */
537 if (PyUnicode_Check(v
) || PyUnicode_Check(w
)) {
538 c
= PyUnicode_Compare(v
, w
);
539 if (!PyErr_Occurred())
541 /* TypeErrors are ignored: if Unicode coercion fails due
542 to one of the arguments not having the right type, we
543 continue as defined by the coercion protocol (see
544 above). Luckily, decoding errors are reported as
545 ValueErrors and are not masked by this technique. */
546 if (!PyErr_ExceptionMatches(PyExc_TypeError
))
551 /* None is smaller than anything */
557 /* different type: compare type names */
558 if (v
->ob_type
->tp_as_number
)
561 vname
= v
->ob_type
->tp_name
;
562 if (w
->ob_type
->tp_as_number
)
565 wname
= w
->ob_type
->tp_name
;
566 c
= strcmp(vname
, wname
);
571 /* Same type name, or (more likely) incomparable numeric types */
572 return ((Py_uintptr_t
)(v
->ob_type
) < (
573 Py_uintptr_t
)(w
->ob_type
)) ? -1 : 1;
576 #define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
578 /* Do a 3-way comparison, by hook or by crook. Return:
583 If the object implements a tp_compare function, it returns
584 whatever this function returns (whether with an exception or not).
587 do_cmp(PyObject
*v
, PyObject
*w
)
592 if (v
->ob_type
== w
->ob_type
593 && (f
= v
->ob_type
->tp_compare
) != NULL
)
595 c
= try_rich_to_3way_compare(v
, w
);
598 c
= try_3way_compare(v
, w
);
601 return default_3way_compare(v
, w
);
604 /* compare_nesting is incremented before calling compare (for
605 some types) and decremented on exit. If the count exceeds the
606 nesting limit, enable code to detect circular data structures.
608 This is a tunable parameter that should only affect the performance
609 of comparisons, nothing else. Setting it high makes comparing deeply
610 nested non-cyclical data structures faster, but makes comparing cyclical
611 data structures slower.
613 #define NESTING_LIMIT 20
615 static int compare_nesting
= 0;
618 get_inprogress_dict(void)
620 static PyObject
*key
;
621 PyObject
*tstate_dict
, *inprogress
;
624 key
= PyString_InternFromString("cmp_state");
629 tstate_dict
= PyThreadState_GetDict();
630 if (tstate_dict
== NULL
) {
631 PyErr_BadInternalCall();
635 inprogress
= PyDict_GetItem(tstate_dict
, key
);
636 if (inprogress
== NULL
) {
637 inprogress
= PyDict_New();
638 if (inprogress
== NULL
)
640 if (PyDict_SetItem(tstate_dict
, key
, inprogress
) == -1) {
641 Py_DECREF(inprogress
);
644 Py_DECREF(inprogress
);
651 check_recursion(PyObject
*v
, PyObject
*w
, int op
)
653 PyObject
*inprogress
;
655 Py_uintptr_t iv
= (Py_uintptr_t
)v
;
656 Py_uintptr_t iw
= (Py_uintptr_t
)w
;
659 inprogress
= get_inprogress_dict();
660 if (inprogress
== NULL
)
663 token
= PyTuple_New(3);
668 PyTuple_SET_ITEM(token
, 0, x
= PyLong_FromVoidPtr((void *)v
));
669 PyTuple_SET_ITEM(token
, 1, y
= PyLong_FromVoidPtr((void *)w
));
673 PyTuple_SET_ITEM(token
, 0, x
= PyLong_FromVoidPtr((void *)w
));
674 PyTuple_SET_ITEM(token
, 1, y
= PyLong_FromVoidPtr((void *)v
));
676 PyTuple_SET_ITEM(token
, 2, z
= PyInt_FromLong((long)op
));
677 if (x
== NULL
|| y
== NULL
|| z
== NULL
) {
682 if (PyDict_GetItem(inprogress
, token
) != NULL
) {
684 return Py_None
; /* Without INCREF! */
687 if (PyDict_SetItem(inprogress
, token
, token
) < 0) {
696 delete_token(PyObject
*token
)
698 PyObject
*inprogress
;
700 if (token
== NULL
|| token
== Py_None
)
702 inprogress
= get_inprogress_dict();
703 if (inprogress
== NULL
)
706 PyDict_DelItem(inprogress
, token
);
711 PyObject_Compare(PyObject
*v
, PyObject
*w
)
716 #if defined(USE_STACKCHECK)
717 if (PyOS_CheckStack()) {
718 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
722 if (v
== NULL
|| w
== NULL
) {
723 PyErr_BadInternalCall();
730 if (compare_nesting
> NESTING_LIMIT
&&
732 || (vtp
->tp_as_sequence
733 && !PyString_Check(v
)
734 && !PyTuple_Check(v
)))) {
735 /* try to detect circular data structures */
736 PyObject
*token
= check_recursion(v
, w
, -1);
741 else if (token
== Py_None
) {
742 /* already comparing these objects. assume
743 they're equal until shown otherwise */
747 result
= do_cmp(v
, w
);
752 result
= do_cmp(v
, w
);
755 return result
< 0 ? -1 : result
;
759 convert_3way_to_object(int op
, int c
)
763 case Py_LT
: c
= c
< 0; break;
764 case Py_LE
: c
= c
<= 0; break;
765 case Py_EQ
: c
= c
== 0; break;
766 case Py_NE
: c
= c
!= 0; break;
767 case Py_GT
: c
= c
> 0; break;
768 case Py_GE
: c
= c
>= 0; break;
770 result
= c
? Py_True
: Py_False
;
777 try_3way_to_rich_compare(PyObject
*v
, PyObject
*w
, int op
)
781 c
= try_3way_compare(v
, w
);
783 c
= default_3way_compare(v
, w
);
786 return convert_3way_to_object(op
, c
);
790 do_richcmp(PyObject
*v
, PyObject
*w
, int op
)
795 /* If the types are equal, don't bother with coercions etc.
796 Instances are special-cased in try_3way_compare, since
797 a result of 2 does *not* mean one value being greater
799 if (v
->ob_type
== w
->ob_type
800 && (f
= v
->ob_type
->tp_compare
) != NULL
801 && !PyInstance_Check(v
)) {
804 if ((f1
= RICHCOMPARE(v
->ob_type
)) != NULL
) {
805 /* If the type has richcmp, try it first.
806 try_rich_compare would try it two-sided,
807 which is not needed since we've a single
809 res
= (*f1
)(v
, w
, op
);
810 if (res
!= Py_NotImplemented
)
815 if (c
< 0 && PyErr_Occurred())
817 return convert_3way_to_object(op
, c
);
820 res
= try_rich_compare(v
, w
, op
);
821 if (res
!= Py_NotImplemented
)
825 return try_3way_to_rich_compare(v
, w
, op
);
829 PyObject_RichCompare(PyObject
*v
, PyObject
*w
, int op
)
833 assert(Py_LT
<= op
&& op
<= Py_GE
);
836 if (compare_nesting
> NESTING_LIMIT
&&
837 (v
->ob_type
->tp_as_mapping
838 || (v
->ob_type
->tp_as_sequence
839 && !PyString_Check(v
)
840 && !PyTuple_Check(v
)))) {
841 /* try to detect circular data structures */
842 PyObject
*token
= check_recursion(v
, w
, op
);
847 else if (token
== Py_None
) {
848 /* already comparing these objects with this operator.
849 assume they're equal until shown otherwise */
852 else if (op
== Py_NE
)
855 PyErr_SetString(PyExc_ValueError
,
856 "can't order recursive values");
862 res
= do_richcmp(v
, w
, op
);
867 res
= do_richcmp(v
, w
, op
);
873 /* Return -1 if error; 1 if v op w; 0 if not (v op w). */
875 PyObject_RichCompareBool(PyObject
*v
, PyObject
*w
, int op
)
877 PyObject
*res
= PyObject_RichCompare(v
, w
, op
);
882 ok
= PyObject_IsTrue(res
);
887 /* Set of hash utility functions to help maintaining the invariant that
888 iff a==b then hash(a)==hash(b)
890 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
894 _Py_HashDouble(double v
)
896 double intpart
, fractpart
;
899 long x
; /* the final hash value */
900 /* This is designed so that Python numbers of different types
901 * that compare equal hash to the same value; otherwise comparisons
902 * of mapping keys will turn out weird.
905 #ifdef MPW /* MPW C modf expects pointer to extended as second argument */
908 fractpart
= modf(v
, &e
);
912 fractpart
= modf(v
, &intpart
);
914 if (fractpart
== 0.0) {
915 /* This must return the same hash as an equal int or long. */
916 if (intpart
> LONG_MAX
|| -intpart
> LONG_MAX
) {
917 /* Convert to long and use its hash. */
918 PyObject
*plong
; /* converted to Python long */
919 if (Py_IS_INFINITY(intpart
))
920 /* can't convert to long int -- arbitrary */
921 v
= v
< 0 ? -271828.0 : 314159.0;
922 plong
= PyLong_FromDouble(v
);
925 x
= PyObject_Hash(plong
);
929 /* Fits in a C long == a Python int, so is its own hash. */
935 /* The fractional part is non-zero, so we don't have to worry about
936 * making this match the hash of some other type.
937 * Use frexp to get at the bits in the double.
938 * Since the VAX D double format has 56 mantissa bits, which is the
939 * most of any double format in use, each of these parts may have as
940 * many as (but no more than) 56 significant bits.
941 * So, assuming sizeof(long) >= 4, each part can be broken into two
942 * longs; frexp and multiplication are used to do that.
943 * Also, since the Cray double format has 15 exponent bits, which is
944 * the most of any double format in use, shifting the exponent field
945 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
948 v
*= 2147483648.0; /* 2**31 */
949 hipart
= (long)v
; /* take the top 32 bits */
950 v
= (v
- (double)hipart
) * 2147483648.0; /* get the next 32 bits */
951 x
= hipart
+ (long)v
+ (expo
<< 15);
958 _Py_HashPointer(void *p
)
960 #if SIZEOF_LONG >= SIZEOF_VOID_P
963 /* convert to a Python long and hash that */
967 if ((longobj
= PyLong_FromVoidPtr(p
)) == NULL
) {
971 x
= PyObject_Hash(longobj
);
981 PyObject_Hash(PyObject
*v
)
983 PyTypeObject
*tp
= v
->ob_type
;
984 if (tp
->tp_hash
!= NULL
)
985 return (*tp
->tp_hash
)(v
);
986 if (tp
->tp_compare
== NULL
&& RICHCOMPARE(tp
) == NULL
) {
987 return _Py_HashPointer(v
); /* Use address as hash value */
989 /* If there's a cmp but no hash defined, the object can't be hashed */
990 PyErr_SetString(PyExc_TypeError
, "unhashable type");
995 PyObject_GetAttrString(PyObject
*v
, char *name
)
997 if (v
->ob_type
->tp_getattro
!= NULL
) {
999 w
= PyString_InternFromString(name
);
1002 res
= (*v
->ob_type
->tp_getattro
)(v
, w
);
1007 if (v
->ob_type
->tp_getattr
== NULL
) {
1008 PyErr_Format(PyExc_AttributeError
,
1009 "'%.50s' object has no attribute '%.400s'",
1010 v
->ob_type
->tp_name
,
1015 return (*v
->ob_type
->tp_getattr
)(v
, name
);
1020 PyObject_HasAttrString(PyObject
*v
, char *name
)
1022 PyObject
*res
= PyObject_GetAttrString(v
, name
);
1032 PyObject_SetAttrString(PyObject
*v
, char *name
, PyObject
*w
)
1034 if (v
->ob_type
->tp_setattro
!= NULL
) {
1037 s
= PyString_InternFromString(name
);
1040 res
= (*v
->ob_type
->tp_setattro
)(v
, s
, w
);
1045 if (v
->ob_type
->tp_setattr
== NULL
) {
1046 if (v
->ob_type
->tp_getattr
== NULL
)
1047 PyErr_SetString(PyExc_TypeError
,
1048 "attribute-less object (assign or del)");
1050 PyErr_SetString(PyExc_TypeError
,
1051 "object has read-only attributes");
1055 return (*v
->ob_type
->tp_setattr
)(v
, name
, w
);
1059 /* Internal API needed by PyObject_GetAttr(): */
1061 PyObject
*_PyUnicode_AsDefaultEncodedString(PyObject
*unicode
,
1062 const char *errors
);
1065 PyObject_GetAttr(PyObject
*v
, PyObject
*name
)
1067 /* The Unicode to string conversion is done here because the
1068 existing tp_getattro slots expect a string object as name
1069 and we wouldn't want to break those. */
1070 if (PyUnicode_Check(name
)) {
1071 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
1076 if (!PyString_Check(name
)) {
1077 PyErr_SetString(PyExc_TypeError
,
1078 "attribute name must be string");
1081 if (v
->ob_type
->tp_getattro
!= NULL
)
1082 return (*v
->ob_type
->tp_getattro
)(v
, name
);
1084 return PyObject_GetAttrString(v
, PyString_AS_STRING(name
));
1088 PyObject_HasAttr(PyObject
*v
, PyObject
*name
)
1090 PyObject
*res
= PyObject_GetAttr(v
, name
);
1100 PyObject_SetAttr(PyObject
*v
, PyObject
*name
, PyObject
*value
)
1104 /* The Unicode to string conversion is done here because the
1105 existing tp_setattro slots expect a string object as name
1106 and we wouldn't want to break those. */
1107 if (PyUnicode_Check(name
)) {
1108 name
= PyUnicode_AsEncodedString(name
, NULL
, NULL
);
1115 if (!PyString_Check(name
)){
1116 PyErr_SetString(PyExc_TypeError
,
1117 "attribute name must be string");
1121 PyString_InternInPlace(&name
);
1122 if (v
->ob_type
->tp_setattro
!= NULL
)
1123 err
= (*v
->ob_type
->tp_setattro
)(v
, name
, value
);
1125 err
= PyObject_SetAttrString(v
,
1126 PyString_AS_STRING(name
), value
);
1133 /* Test a value used as condition, e.g., in a for or if statement.
1134 Return -1 if an error occurred */
1137 PyObject_IsTrue(PyObject
*v
)
1142 else if (v
->ob_type
->tp_as_number
!= NULL
&&
1143 v
->ob_type
->tp_as_number
->nb_nonzero
!= NULL
)
1144 res
= (*v
->ob_type
->tp_as_number
->nb_nonzero
)(v
);
1145 else if (v
->ob_type
->tp_as_mapping
!= NULL
&&
1146 v
->ob_type
->tp_as_mapping
->mp_length
!= NULL
)
1147 res
= (*v
->ob_type
->tp_as_mapping
->mp_length
)(v
);
1148 else if (v
->ob_type
->tp_as_sequence
!= NULL
&&
1149 v
->ob_type
->tp_as_sequence
->sq_length
!= NULL
)
1150 res
= (*v
->ob_type
->tp_as_sequence
->sq_length
)(v
);
1158 /* equivalent of 'not v'
1159 Return -1 if an error occurred */
1162 PyObject_Not(PyObject
*v
)
1165 res
= PyObject_IsTrue(v
);
1171 /* Coerce two numeric types to the "larger" one.
1172 Increment the reference count on each argument.
1174 -1 if an error occurred;
1175 0 if the coercion succeeded (and then the reference counts are increased);
1176 1 if no coercion is possible (and no error is raised).
1179 PyNumber_CoerceEx(PyObject
**pv
, PyObject
**pw
)
1181 register PyObject
*v
= *pv
;
1182 register PyObject
*w
= *pw
;
1185 if (v
->ob_type
== w
->ob_type
&& !PyInstance_Check(v
)) {
1190 if (v
->ob_type
->tp_as_number
&& v
->ob_type
->tp_as_number
->nb_coerce
) {
1191 res
= (*v
->ob_type
->tp_as_number
->nb_coerce
)(pv
, pw
);
1195 if (w
->ob_type
->tp_as_number
&& w
->ob_type
->tp_as_number
->nb_coerce
) {
1196 res
= (*w
->ob_type
->tp_as_number
->nb_coerce
)(pw
, pv
);
1203 /* Coerce two numeric types to the "larger" one.
1204 Increment the reference count on each argument.
1205 Return -1 and raise an exception if no coercion is possible
1206 (and then no reference count is incremented).
1209 PyNumber_Coerce(PyObject
**pv
, PyObject
**pw
)
1211 int err
= PyNumber_CoerceEx(pv
, pw
);
1214 PyErr_SetString(PyExc_TypeError
, "number coercion failed");
1219 /* Test whether an object can be called */
1222 PyCallable_Check(PyObject
*x
)
1226 if (x
->ob_type
->tp_call
!= NULL
||
1227 PyFunction_Check(x
) ||
1228 PyMethod_Check(x
) ||
1229 PyCFunction_Check(x
) ||
1232 if (PyInstance_Check(x
)) {
1233 PyObject
*call
= PyObject_GetAttrString(x
, "__call__");
1238 /* Could test recursively but don't, for fear of endless
1239 recursion if some joker sets self.__call__ = self */
1248 NoObject is usable as a non-NULL undefined value, used by the macro None.
1249 There is (and should be!) no way to create other objects of this type,
1250 so there is exactly one (which is indestructible, by the way).
1255 none_repr(PyObject
*op
)
1257 return PyString_FromString("None");
1262 none_dealloc(PyObject
* ignore
)
1264 /* This should never get called, but we also don't want to SEGV if
1265 * we accidently decref None out of existance.
1271 static PyTypeObject PyNothing_Type
= {
1272 PyObject_HEAD_INIT(&PyType_Type
)
1277 (destructor
)none_dealloc
, /*tp_dealloc*/ /*never called*/
1282 (reprfunc
)none_repr
, /*tp_repr*/
1284 0, /*tp_as_sequence*/
1285 0, /*tp_as_mapping*/
1289 PyObject _Py_NoneStruct
= {
1290 PyObject_HEAD_INIT(&PyNothing_Type
)
1293 /* NotImplemented is an object that can be used to signal that an
1294 operation is not implemented for the given type combination. */
1297 NotImplemented_repr(PyObject
*op
)
1299 return PyString_FromString("NotImplemented");
1302 static PyTypeObject PyNotImplemented_Type
= {
1303 PyObject_HEAD_INIT(&PyType_Type
)
1308 (destructor
)none_dealloc
, /*tp_dealloc*/ /*never called*/
1313 (reprfunc
)NotImplemented_repr
, /*tp_repr*/
1315 0, /*tp_as_sequence*/
1316 0, /*tp_as_mapping*/
1320 PyObject _Py_NotImplementedStruct
= {
1321 PyObject_HEAD_INIT(&PyNotImplemented_Type
)
1325 #ifdef Py_TRACE_REFS
1327 static PyObject refchain
= {&refchain
, &refchain
};
1330 _Py_ResetReferences(void)
1332 refchain
._ob_prev
= refchain
._ob_next
= &refchain
;
1337 _Py_NewReference(PyObject
*op
)
1341 op
->_ob_next
= refchain
._ob_next
;
1342 op
->_ob_prev
= &refchain
;
1343 refchain
._ob_next
->_ob_prev
= op
;
1344 refchain
._ob_next
= op
;
1346 inc_count(op
->ob_type
);
1351 _Py_ForgetReference(register PyObject
*op
)
1353 #ifdef SLOW_UNREF_CHECK
1354 register PyObject
*p
;
1356 if (op
->ob_refcnt
< 0)
1357 Py_FatalError("UNREF negative refcnt");
1358 if (op
== &refchain
||
1359 op
->_ob_prev
->_ob_next
!= op
|| op
->_ob_next
->_ob_prev
!= op
)
1360 Py_FatalError("UNREF invalid object");
1361 #ifdef SLOW_UNREF_CHECK
1362 for (p
= refchain
._ob_next
; p
!= &refchain
; p
= p
->_ob_next
) {
1366 if (p
== &refchain
) /* Not found */
1367 Py_FatalError("UNREF unknown object");
1369 op
->_ob_next
->_ob_prev
= op
->_ob_prev
;
1370 op
->_ob_prev
->_ob_next
= op
->_ob_next
;
1371 op
->_ob_next
= op
->_ob_prev
= NULL
;
1373 op
->ob_type
->tp_free
++;
1378 _Py_Dealloc(PyObject
*op
)
1380 destructor dealloc
= op
->ob_type
->tp_dealloc
;
1381 _Py_ForgetReference(op
);
1386 _Py_PrintReferences(FILE *fp
)
1389 fprintf(fp
, "Remaining objects:\n");
1390 for (op
= refchain
._ob_next
; op
!= &refchain
; op
= op
->_ob_next
) {
1391 fprintf(fp
, "[%d] ", op
->ob_refcnt
);
1392 if (PyObject_Print(op
, fp
, 0) != 0)
1399 _Py_GetObjects(PyObject
*self
, PyObject
*args
)
1405 if (!PyArg_ParseTuple(args
, "i|O", &n
, &t
))
1407 op
= refchain
._ob_next
;
1408 res
= PyList_New(0);
1411 for (i
= 0; (n
== 0 || i
< n
) && op
!= &refchain
; i
++) {
1412 while (op
== self
|| op
== args
|| op
== res
|| op
== t
||
1413 t
!= NULL
&& op
->ob_type
!= (PyTypeObject
*) t
) {
1415 if (op
== &refchain
)
1418 if (PyList_Append(res
, op
) < 0) {
1430 /* Hack to force loading of cobject.o */
1431 PyTypeObject
*_Py_cobject_hack
= &PyCObject_Type
;
1434 /* Hack to force loading of abstract.o */
1435 int (*_Py_abstract_hack
)(PyObject
*) = &PyObject_Size
;
1438 /* Python's malloc wrappers (see pymem.h) */
1441 PyMem_Malloc(size_t nbytes
)
1443 #if _PyMem_EXTRA > 0
1445 nbytes
= _PyMem_EXTRA
;
1447 return PyMem_MALLOC(nbytes
);
1451 PyMem_Realloc(void *p
, size_t nbytes
)
1453 #if _PyMem_EXTRA > 0
1455 nbytes
= _PyMem_EXTRA
;
1457 return PyMem_REALLOC(p
, nbytes
);
1467 /* Python's object malloc wrappers (see objimpl.h) */
1470 PyObject_Malloc(size_t nbytes
)
1472 return PyObject_MALLOC(nbytes
);
1476 PyObject_Realloc(void *p
, size_t nbytes
)
1478 return PyObject_REALLOC(p
, nbytes
);
1482 PyObject_Free(void *p
)
1488 /* Hook to clear up weak references only once the _weakref module is
1489 imported. We use a dummy implementation to simplify the code at each
1490 call site instead of requiring a test for NULL.
1494 empty_clear_weak_refs(PyObject
*o
)
1499 void (*PyObject_ClearWeakRefs
)(PyObject
*) = empty_clear_weak_refs
;
1503 /* These methods are used to control infinite recursion in repr, str, print,
1504 etc. Container objects that may recursively contain themselves,
1505 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1506 Py_ReprLeave() to avoid infinite recursion.
1508 Py_ReprEnter() returns 0 the first time it is called for a particular
1509 object and 1 every time thereafter. It returns -1 if an exception
1510 occurred. Py_ReprLeave() has no return value.
1512 See dictobject.c and listobject.c for examples of use.
1515 #define KEY "Py_Repr"
1518 Py_ReprEnter(PyObject
*obj
)
1524 dict
= PyThreadState_GetDict();
1527 list
= PyDict_GetItemString(dict
, KEY
);
1529 list
= PyList_New(0);
1532 if (PyDict_SetItemString(dict
, KEY
, list
) < 0)
1536 i
= PyList_GET_SIZE(list
);
1538 if (PyList_GET_ITEM(list
, i
) == obj
)
1541 PyList_Append(list
, obj
);
1546 Py_ReprLeave(PyObject
*obj
)
1552 dict
= PyThreadState_GetDict();
1555 list
= PyDict_GetItemString(dict
, KEY
);
1556 if (list
== NULL
|| !PyList_Check(list
))
1558 i
= PyList_GET_SIZE(list
);
1559 /* Count backwards because we always expect obj to be list[-1] */
1561 if (PyList_GET_ITEM(list
, i
) == obj
) {
1562 PyList_SetSlice(list
, i
, i
+ 1, NULL
);
1571 non-recursively destroy nested objects
1574 everything is now done in a macro.
1577 modified to use functions, after Tim Peter's suggestion.
1580 modified to restore a possible error.
1583 added better safe than sorry check for threadstate
1586 complete rewrite. We now build a chain via ob_type
1587 and save the limited number of types in ob_refcnt.
1588 This is perfect since we don't need any memory.
1589 A patch for free-threading would need just a lock.
1592 #define Py_TRASHCAN_TUPLE 1
1593 #define Py_TRASHCAN_LIST 2
1594 #define Py_TRASHCAN_DICT 3
1595 #define Py_TRASHCAN_FRAME 4
1596 #define Py_TRASHCAN_TRACEBACK 5
1597 /* extend here if other objects want protection */
1599 int _PyTrash_delete_nesting
= 0;
1601 PyObject
* _PyTrash_delete_later
= NULL
;
1604 _PyTrash_deposit_object(PyObject
*op
)
1608 if (PyTuple_Check(op
))
1609 typecode
= Py_TRASHCAN_TUPLE
;
1610 else if (PyList_Check(op
))
1611 typecode
= Py_TRASHCAN_LIST
;
1612 else if (PyDict_Check(op
))
1613 typecode
= Py_TRASHCAN_DICT
;
1614 else if (PyFrame_Check(op
))
1615 typecode
= Py_TRASHCAN_FRAME
;
1616 else if (PyTraceBack_Check(op
))
1617 typecode
= Py_TRASHCAN_TRACEBACK
;
1618 else /* We have a bug here -- those are the only types in GC */ {
1619 Py_FatalError("Type not supported in GC -- internal bug");
1620 return; /* pacify compiler -- execution never here */
1622 op
->ob_refcnt
= typecode
;
1624 op
->ob_type
= (PyTypeObject
*)_PyTrash_delete_later
;
1625 _PyTrash_delete_later
= op
;
1629 _PyTrash_destroy_chain(void)
1631 while (_PyTrash_delete_later
) {
1632 PyObject
*shredder
= _PyTrash_delete_later
;
1633 _PyTrash_delete_later
= (PyObject
*) shredder
->ob_type
;
1635 switch (shredder
->ob_refcnt
) {
1636 case Py_TRASHCAN_TUPLE
:
1637 shredder
->ob_type
= &PyTuple_Type
;
1639 case Py_TRASHCAN_LIST
:
1640 shredder
->ob_type
= &PyList_Type
;
1642 case Py_TRASHCAN_DICT
:
1643 shredder
->ob_type
= &PyDict_Type
;
1645 case Py_TRASHCAN_FRAME
:
1646 shredder
->ob_type
= &PyFrame_Type
;
1648 case Py_TRASHCAN_TRACEBACK
:
1649 shredder
->ob_type
= &PyTraceBack_Type
;
1652 _Py_NewReference(shredder
);
1654 ++_PyTrash_delete_nesting
;
1655 Py_DECREF(shredder
);
1656 --_PyTrash_delete_nesting
;
1660 #ifdef WITH_PYMALLOC
1661 #include "obmalloc.c"