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 /* If the types are equal, don't bother with coercions etc. */
481 if (v
->ob_type
== w
->ob_type
) {
482 if ((f
= v
->ob_type
->tp_compare
) == NULL
)
485 if (PyErr_Occurred())
487 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
490 /* Try coercion; if it fails, give up */
491 c
= PyNumber_CoerceEx(&v
, &w
);
497 /* Try v's comparison, if defined */
498 if ((f
= v
->ob_type
->tp_compare
) != NULL
) {
502 if (PyErr_Occurred())
504 return c
< 0 ? -1 : c
> 0 ? 1 : 0;
507 /* Try w's comparison, if defined */
508 if ((f
= w
->ob_type
->tp_compare
) != NULL
) {
509 c
= (*f
)(w
, v
); /* swapped! */
512 if (PyErr_Occurred())
514 return c
< 0 ? 1 : c
> 0 ? -1 : 0; /* negated! */
517 /* No comparison defined */
523 /* Final fallback 3-way comparison, returning an int. Return:
524 -2 if an error occurred;
530 default_3way_compare(PyObject
*v
, PyObject
*w
)
535 if (v
->ob_type
== w
->ob_type
) {
536 /* When comparing these pointers, they must be cast to
537 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
538 * uintptr_t). ANSI specifies that pointer compares other
539 * than == and != to non-related structures are undefined.
541 Py_uintptr_t vv
= (Py_uintptr_t
)v
;
542 Py_uintptr_t ww
= (Py_uintptr_t
)w
;
543 return (vv
< ww
) ? -1 : (vv
> ww
) ? 1 : 0;
546 /* Special case for Unicode */
547 if (PyUnicode_Check(v
) || PyUnicode_Check(w
)) {
548 c
= PyUnicode_Compare(v
, w
);
549 if (!PyErr_Occurred())
551 /* TypeErrors are ignored: if Unicode coercion fails due
552 to one of the arguments not having the right type, we
553 continue as defined by the coercion protocol (see
554 above). Luckily, decoding errors are reported as
555 ValueErrors and are not masked by this technique. */
556 if (!PyErr_ExceptionMatches(PyExc_TypeError
))
561 /* None is smaller than anything */
567 /* different type: compare type names */
568 if (v
->ob_type
->tp_as_number
)
571 vname
= v
->ob_type
->tp_name
;
572 if (w
->ob_type
->tp_as_number
)
575 wname
= w
->ob_type
->tp_name
;
576 c
= strcmp(vname
, wname
);
581 /* Same type name, or (more likely) incomparable numeric types */
582 return ((Py_uintptr_t
)(v
->ob_type
) < (
583 Py_uintptr_t
)(w
->ob_type
)) ? -1 : 1;
586 #define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
588 /* Do a 3-way comparison, by hook or by crook. Return:
595 do_cmp(PyObject
*v
, PyObject
*w
)
599 c
= try_rich_to_3way_compare(v
, w
);
602 c
= try_3way_compare(v
, w
);
605 return default_3way_compare(v
, w
);
608 /* compare_nesting is incremented before calling compare (for
609 some types) and decremented on exit. If the count exceeds the
610 nesting limit, enable code to detect circular data structures.
612 This is a tunable parameter that should only affect the performance
613 of comparisons, nothing else. Setting it high makes comparing deeply
614 nested non-cyclical data structures faster, but makes comparing cyclical
615 data structures slower.
617 #define NESTING_LIMIT 20
619 static int compare_nesting
= 0;
622 get_inprogress_dict(void)
624 static PyObject
*key
;
625 PyObject
*tstate_dict
, *inprogress
;
628 key
= PyString_InternFromString("cmp_state");
633 tstate_dict
= PyThreadState_GetDict();
634 if (tstate_dict
== NULL
) {
635 PyErr_BadInternalCall();
639 inprogress
= PyDict_GetItem(tstate_dict
, key
);
640 if (inprogress
== NULL
) {
641 inprogress
= PyDict_New();
642 if (inprogress
== NULL
)
644 if (PyDict_SetItem(tstate_dict
, key
, inprogress
) == -1) {
645 Py_DECREF(inprogress
);
648 Py_DECREF(inprogress
);
655 check_recursion(PyObject
*v
, PyObject
*w
, int op
)
657 PyObject
*inprogress
;
659 Py_uintptr_t iv
= (Py_uintptr_t
)v
;
660 Py_uintptr_t iw
= (Py_uintptr_t
)w
;
663 inprogress
= get_inprogress_dict();
664 if (inprogress
== NULL
)
667 token
= PyTuple_New(3);
672 PyTuple_SET_ITEM(token
, 0, x
= PyLong_FromVoidPtr((void *)v
));
673 PyTuple_SET_ITEM(token
, 1, y
= PyLong_FromVoidPtr((void *)w
));
677 PyTuple_SET_ITEM(token
, 0, x
= PyLong_FromVoidPtr((void *)w
));
678 PyTuple_SET_ITEM(token
, 1, y
= PyLong_FromVoidPtr((void *)v
));
680 PyTuple_SET_ITEM(token
, 2, z
= PyInt_FromLong((long)op
));
681 if (x
== NULL
|| y
== NULL
|| z
== NULL
) {
686 if (PyDict_GetItem(inprogress
, token
) != NULL
) {
688 return Py_None
; /* Without INCREF! */
691 if (PyDict_SetItem(inprogress
, token
, token
) < 0) {
700 delete_token(PyObject
*token
)
702 PyObject
*inprogress
;
704 if (token
== NULL
|| token
== Py_None
)
706 inprogress
= get_inprogress_dict();
707 if (inprogress
== NULL
)
710 PyDict_DelItem(inprogress
, token
);
715 PyObject_Compare(PyObject
*v
, PyObject
*w
)
720 #if defined(USE_STACKCHECK)
721 if (PyOS_CheckStack()) {
722 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
726 if (v
== NULL
|| w
== NULL
) {
727 PyErr_BadInternalCall();
734 if (compare_nesting
> NESTING_LIMIT
&&
736 || (vtp
->tp_as_sequence
737 && !PyString_Check(v
)
738 && !PyTuple_Check(v
)))) {
739 /* try to detect circular data structures */
740 PyObject
*token
= check_recursion(v
, w
, -1);
745 else if (token
== Py_None
) {
746 /* already comparing these objects. assume
747 they're equal until shown otherwise */
751 result
= do_cmp(v
, w
);
756 result
= do_cmp(v
, w
);
759 return result
< 0 ? -1 : result
;
763 try_3way_to_rich_compare(PyObject
*v
, PyObject
*w
, int op
)
768 c
= try_3way_compare(v
, w
);
770 c
= default_3way_compare(v
, w
);
774 case Py_LT
: c
= c
< 0; break;
775 case Py_LE
: c
= c
<= 0; break;
776 case Py_EQ
: c
= c
== 0; break;
777 case Py_NE
: c
= c
!= 0; break;
778 case Py_GT
: c
= c
> 0; break;
779 case Py_GE
: c
= c
>= 0; break;
781 result
= c
? Py_True
: Py_False
;
787 do_richcmp(PyObject
*v
, PyObject
*w
, int op
)
791 res
= try_rich_compare(v
, w
, op
);
792 if (res
!= Py_NotImplemented
)
796 return try_3way_to_rich_compare(v
, w
, op
);
800 PyObject_RichCompare(PyObject
*v
, PyObject
*w
, int op
)
804 assert(Py_LT
<= op
&& op
<= Py_GE
);
807 if (compare_nesting
> NESTING_LIMIT
&&
808 (v
->ob_type
->tp_as_mapping
809 || (v
->ob_type
->tp_as_sequence
810 && !PyString_Check(v
)
811 && !PyTuple_Check(v
)))) {
812 /* try to detect circular data structures */
813 PyObject
*token
= check_recursion(v
, w
, op
);
818 else if (token
== Py_None
) {
819 /* already comparing these objects with this operator.
820 assume they're equal until shown otherwise */
823 else if (op
== Py_NE
)
826 PyErr_SetString(PyExc_ValueError
,
827 "can't order recursive values");
833 res
= do_richcmp(v
, w
, op
);
838 res
= do_richcmp(v
, w
, op
);
845 PyObject_RichCompareBool(PyObject
*v
, PyObject
*w
, int op
)
847 PyObject
*res
= PyObject_RichCompare(v
, w
, op
);
852 ok
= PyObject_IsTrue(res
);
857 /* Set of hash utility functions to help maintaining the invariant that
858 iff a==b then hash(a)==hash(b)
860 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
864 _Py_HashDouble(double v
)
866 double intpart
, fractpart
;
869 long x
; /* the final hash value */
870 /* This is designed so that Python numbers of different types
871 * that compare equal hash to the same value; otherwise comparisons
872 * of mapping keys will turn out weird.
875 #ifdef MPW /* MPW C modf expects pointer to extended as second argument */
878 fractpart
= modf(v
, &e
);
882 fractpart
= modf(v
, &intpart
);
884 if (fractpart
== 0.0) {
885 /* This must return the same hash as an equal int or long. */
886 if (intpart
> LONG_MAX
|| -intpart
> LONG_MAX
) {
887 /* Convert to long and use its hash. */
888 PyObject
*plong
; /* converted to Python long */
889 if (Py_IS_INFINITY(intpart
))
890 /* can't convert to long int -- arbitrary */
891 v
= v
< 0 ? -271828.0 : 314159.0;
892 plong
= PyLong_FromDouble(v
);
895 x
= PyObject_Hash(plong
);
899 /* Fits in a C long == a Python int, so is its own hash. */
905 /* The fractional part is non-zero, so we don't have to worry about
906 * making this match the hash of some other type.
907 * Use frexp to get at the bits in the double.
908 * Since the VAX D double format has 56 mantissa bits, which is the
909 * most of any double format in use, each of these parts may have as
910 * many as (but no more than) 56 significant bits.
911 * So, assuming sizeof(long) >= 4, each part can be broken into two
912 * longs; frexp and multiplication are used to do that.
913 * Also, since the Cray double format has 15 exponent bits, which is
914 * the most of any double format in use, shifting the exponent field
915 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
918 v
*= 2147483648.0; /* 2**31 */
919 hipart
= (long)v
; /* take the top 32 bits */
920 v
= (v
- (double)hipart
) * 2147483648.0; /* get the next 32 bits */
921 x
= hipart
+ (long)v
+ (expo
<< 15);
928 _Py_HashPointer(void *p
)
930 #if SIZEOF_LONG >= SIZEOF_VOID_P
933 /* convert to a Python long and hash that */
937 if ((longobj
= PyLong_FromVoidPtr(p
)) == NULL
) {
941 x
= PyObject_Hash(longobj
);
951 PyObject_Hash(PyObject
*v
)
953 PyTypeObject
*tp
= v
->ob_type
;
954 if (tp
->tp_hash
!= NULL
)
955 return (*tp
->tp_hash
)(v
);
956 if (tp
->tp_compare
== NULL
&& RICHCOMPARE(tp
) == NULL
) {
957 return _Py_HashPointer(v
); /* Use address as hash value */
959 /* If there's a cmp but no hash defined, the object can't be hashed */
960 PyErr_SetString(PyExc_TypeError
, "unhashable type");
965 PyObject_GetAttrString(PyObject
*v
, char *name
)
967 if (v
->ob_type
->tp_getattro
!= NULL
) {
969 w
= PyString_InternFromString(name
);
972 res
= (*v
->ob_type
->tp_getattro
)(v
, w
);
977 if (v
->ob_type
->tp_getattr
== NULL
) {
978 PyErr_Format(PyExc_AttributeError
,
979 "'%.50s' object has no attribute '%.400s'",
985 return (*v
->ob_type
->tp_getattr
)(v
, name
);
990 PyObject_HasAttrString(PyObject
*v
, char *name
)
992 PyObject
*res
= PyObject_GetAttrString(v
, name
);
1002 PyObject_SetAttrString(PyObject
*v
, char *name
, PyObject
*w
)
1004 if (v
->ob_type
->tp_setattro
!= NULL
) {
1007 s
= PyString_InternFromString(name
);
1010 res
= (*v
->ob_type
->tp_setattro
)(v
, s
, w
);
1015 if (v
->ob_type
->tp_setattr
== NULL
) {
1016 if (v
->ob_type
->tp_getattr
== NULL
)
1017 PyErr_SetString(PyExc_TypeError
,
1018 "attribute-less object (assign or del)");
1020 PyErr_SetString(PyExc_TypeError
,
1021 "object has read-only attributes");
1025 return (*v
->ob_type
->tp_setattr
)(v
, name
, w
);
1029 /* Internal API needed by PyObject_GetAttr(): */
1031 PyObject
*_PyUnicode_AsDefaultEncodedString(PyObject
*unicode
,
1032 const char *errors
);
1035 PyObject_GetAttr(PyObject
*v
, PyObject
*name
)
1037 /* The Unicode to string conversion is done here because the
1038 existing tp_getattro slots expect a string object as name
1039 and we wouldn't want to break those. */
1040 if (PyUnicode_Check(name
)) {
1041 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
1046 if (!PyString_Check(name
)) {
1047 PyErr_SetString(PyExc_TypeError
,
1048 "attribute name must be string");
1051 if (v
->ob_type
->tp_getattro
!= NULL
)
1052 return (*v
->ob_type
->tp_getattro
)(v
, name
);
1054 return PyObject_GetAttrString(v
, PyString_AS_STRING(name
));
1058 PyObject_HasAttr(PyObject
*v
, PyObject
*name
)
1060 PyObject
*res
= PyObject_GetAttr(v
, name
);
1070 PyObject_SetAttr(PyObject
*v
, PyObject
*name
, PyObject
*value
)
1074 /* The Unicode to string conversion is done here because the
1075 existing tp_setattro slots expect a string object as name
1076 and we wouldn't want to break those. */
1077 if (PyUnicode_Check(name
)) {
1078 name
= PyUnicode_AsEncodedString(name
, NULL
, NULL
);
1085 if (!PyString_Check(name
)){
1086 PyErr_SetString(PyExc_TypeError
,
1087 "attribute name must be string");
1091 PyString_InternInPlace(&name
);
1092 if (v
->ob_type
->tp_setattro
!= NULL
)
1093 err
= (*v
->ob_type
->tp_setattro
)(v
, name
, value
);
1095 err
= PyObject_SetAttrString(v
,
1096 PyString_AS_STRING(name
), value
);
1103 /* Test a value used as condition, e.g., in a for or if statement.
1104 Return -1 if an error occurred */
1107 PyObject_IsTrue(PyObject
*v
)
1112 else if (v
->ob_type
->tp_as_number
!= NULL
&&
1113 v
->ob_type
->tp_as_number
->nb_nonzero
!= NULL
)
1114 res
= (*v
->ob_type
->tp_as_number
->nb_nonzero
)(v
);
1115 else if (v
->ob_type
->tp_as_mapping
!= NULL
&&
1116 v
->ob_type
->tp_as_mapping
->mp_length
!= NULL
)
1117 res
= (*v
->ob_type
->tp_as_mapping
->mp_length
)(v
);
1118 else if (v
->ob_type
->tp_as_sequence
!= NULL
&&
1119 v
->ob_type
->tp_as_sequence
->sq_length
!= NULL
)
1120 res
= (*v
->ob_type
->tp_as_sequence
->sq_length
)(v
);
1128 /* equivalent of 'not v'
1129 Return -1 if an error occurred */
1132 PyObject_Not(PyObject
*v
)
1135 res
= PyObject_IsTrue(v
);
1141 /* Coerce two numeric types to the "larger" one.
1142 Increment the reference count on each argument.
1144 -1 if an error occurred;
1145 0 if the coercion succeeded (and then the reference counts are increased);
1146 1 if no coercion is possible (and no error is raised).
1149 PyNumber_CoerceEx(PyObject
**pv
, PyObject
**pw
)
1151 register PyObject
*v
= *pv
;
1152 register PyObject
*w
= *pw
;
1155 if (v
->ob_type
== w
->ob_type
&& !PyInstance_Check(v
)) {
1160 if (v
->ob_type
->tp_as_number
&& v
->ob_type
->tp_as_number
->nb_coerce
) {
1161 res
= (*v
->ob_type
->tp_as_number
->nb_coerce
)(pv
, pw
);
1165 if (w
->ob_type
->tp_as_number
&& w
->ob_type
->tp_as_number
->nb_coerce
) {
1166 res
= (*w
->ob_type
->tp_as_number
->nb_coerce
)(pw
, pv
);
1173 /* Coerce two numeric types to the "larger" one.
1174 Increment the reference count on each argument.
1175 Return -1 and raise an exception if no coercion is possible
1176 (and then no reference count is incremented).
1179 PyNumber_Coerce(PyObject
**pv
, PyObject
**pw
)
1181 int err
= PyNumber_CoerceEx(pv
, pw
);
1184 PyErr_SetString(PyExc_TypeError
, "number coercion failed");
1189 /* Test whether an object can be called */
1192 PyCallable_Check(PyObject
*x
)
1196 if (x
->ob_type
->tp_call
!= NULL
||
1197 PyFunction_Check(x
) ||
1198 PyMethod_Check(x
) ||
1199 PyCFunction_Check(x
) ||
1202 if (PyInstance_Check(x
)) {
1203 PyObject
*call
= PyObject_GetAttrString(x
, "__call__");
1208 /* Could test recursively but don't, for fear of endless
1209 recursion if some joker sets self.__call__ = self */
1218 NoObject is usable as a non-NULL undefined value, used by the macro None.
1219 There is (and should be!) no way to create other objects of this type,
1220 so there is exactly one (which is indestructible, by the way).
1225 none_repr(PyObject
*op
)
1227 return PyString_FromString("None");
1232 none_dealloc(PyObject
* ignore
)
1234 /* This should never get called, but we also don't want to SEGV if
1235 * we accidently decref None out of existance.
1241 static PyTypeObject PyNothing_Type
= {
1242 PyObject_HEAD_INIT(&PyType_Type
)
1247 (destructor
)none_dealloc
, /*tp_dealloc*/ /*never called*/
1252 (reprfunc
)none_repr
, /*tp_repr*/
1254 0, /*tp_as_sequence*/
1255 0, /*tp_as_mapping*/
1259 PyObject _Py_NoneStruct
= {
1260 PyObject_HEAD_INIT(&PyNothing_Type
)
1263 /* NotImplemented is an object that can be used to signal that an
1264 operation is not implemented for the given type combination. */
1267 NotImplemented_repr(PyObject
*op
)
1269 return PyString_FromString("NotImplemented");
1272 static PyTypeObject PyNotImplemented_Type
= {
1273 PyObject_HEAD_INIT(&PyType_Type
)
1278 (destructor
)none_dealloc
, /*tp_dealloc*/ /*never called*/
1283 (reprfunc
)NotImplemented_repr
, /*tp_repr*/
1285 0, /*tp_as_sequence*/
1286 0, /*tp_as_mapping*/
1290 PyObject _Py_NotImplementedStruct
= {
1291 PyObject_HEAD_INIT(&PyNotImplemented_Type
)
1295 #ifdef Py_TRACE_REFS
1297 static PyObject refchain
= {&refchain
, &refchain
};
1300 _Py_ResetReferences(void)
1302 refchain
._ob_prev
= refchain
._ob_next
= &refchain
;
1307 _Py_NewReference(PyObject
*op
)
1311 op
->_ob_next
= refchain
._ob_next
;
1312 op
->_ob_prev
= &refchain
;
1313 refchain
._ob_next
->_ob_prev
= op
;
1314 refchain
._ob_next
= op
;
1316 inc_count(op
->ob_type
);
1321 _Py_ForgetReference(register PyObject
*op
)
1323 #ifdef SLOW_UNREF_CHECK
1324 register PyObject
*p
;
1326 if (op
->ob_refcnt
< 0)
1327 Py_FatalError("UNREF negative refcnt");
1328 if (op
== &refchain
||
1329 op
->_ob_prev
->_ob_next
!= op
|| op
->_ob_next
->_ob_prev
!= op
)
1330 Py_FatalError("UNREF invalid object");
1331 #ifdef SLOW_UNREF_CHECK
1332 for (p
= refchain
._ob_next
; p
!= &refchain
; p
= p
->_ob_next
) {
1336 if (p
== &refchain
) /* Not found */
1337 Py_FatalError("UNREF unknown object");
1339 op
->_ob_next
->_ob_prev
= op
->_ob_prev
;
1340 op
->_ob_prev
->_ob_next
= op
->_ob_next
;
1341 op
->_ob_next
= op
->_ob_prev
= NULL
;
1343 op
->ob_type
->tp_free
++;
1348 _Py_Dealloc(PyObject
*op
)
1350 destructor dealloc
= op
->ob_type
->tp_dealloc
;
1351 _Py_ForgetReference(op
);
1356 _Py_PrintReferences(FILE *fp
)
1359 fprintf(fp
, "Remaining objects:\n");
1360 for (op
= refchain
._ob_next
; op
!= &refchain
; op
= op
->_ob_next
) {
1361 fprintf(fp
, "[%d] ", op
->ob_refcnt
);
1362 if (PyObject_Print(op
, fp
, 0) != 0)
1369 _Py_GetObjects(PyObject
*self
, PyObject
*args
)
1375 if (!PyArg_ParseTuple(args
, "i|O", &n
, &t
))
1377 op
= refchain
._ob_next
;
1378 res
= PyList_New(0);
1381 for (i
= 0; (n
== 0 || i
< n
) && op
!= &refchain
; i
++) {
1382 while (op
== self
|| op
== args
|| op
== res
|| op
== t
||
1383 t
!= NULL
&& op
->ob_type
!= (PyTypeObject
*) t
) {
1385 if (op
== &refchain
)
1388 if (PyList_Append(res
, op
) < 0) {
1400 /* Hack to force loading of cobject.o */
1401 PyTypeObject
*_Py_cobject_hack
= &PyCObject_Type
;
1404 /* Hack to force loading of abstract.o */
1405 int (*_Py_abstract_hack
)(PyObject
*) = &PyObject_Size
;
1408 /* Python's malloc wrappers (see pymem.h) */
1411 PyMem_Malloc(size_t nbytes
)
1413 #if _PyMem_EXTRA > 0
1415 nbytes
= _PyMem_EXTRA
;
1417 return PyMem_MALLOC(nbytes
);
1421 PyMem_Realloc(void *p
, size_t nbytes
)
1423 #if _PyMem_EXTRA > 0
1425 nbytes
= _PyMem_EXTRA
;
1427 return PyMem_REALLOC(p
, nbytes
);
1437 /* Python's object malloc wrappers (see objimpl.h) */
1440 PyObject_Malloc(size_t nbytes
)
1442 return PyObject_MALLOC(nbytes
);
1446 PyObject_Realloc(void *p
, size_t nbytes
)
1448 return PyObject_REALLOC(p
, nbytes
);
1452 PyObject_Free(void *p
)
1458 /* Hook to clear up weak references only once the _weakref module is
1459 imported. We use a dummy implementation to simplify the code at each
1460 call site instead of requiring a test for NULL.
1464 empty_clear_weak_refs(PyObject
*o
)
1469 void (*PyObject_ClearWeakRefs
)(PyObject
*) = empty_clear_weak_refs
;
1473 /* These methods are used to control infinite recursion in repr, str, print,
1474 etc. Container objects that may recursively contain themselves,
1475 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1476 Py_ReprLeave() to avoid infinite recursion.
1478 Py_ReprEnter() returns 0 the first time it is called for a particular
1479 object and 1 every time thereafter. It returns -1 if an exception
1480 occurred. Py_ReprLeave() has no return value.
1482 See dictobject.c and listobject.c for examples of use.
1485 #define KEY "Py_Repr"
1488 Py_ReprEnter(PyObject
*obj
)
1494 dict
= PyThreadState_GetDict();
1497 list
= PyDict_GetItemString(dict
, KEY
);
1499 list
= PyList_New(0);
1502 if (PyDict_SetItemString(dict
, KEY
, list
) < 0)
1506 i
= PyList_GET_SIZE(list
);
1508 if (PyList_GET_ITEM(list
, i
) == obj
)
1511 PyList_Append(list
, obj
);
1516 Py_ReprLeave(PyObject
*obj
)
1522 dict
= PyThreadState_GetDict();
1525 list
= PyDict_GetItemString(dict
, KEY
);
1526 if (list
== NULL
|| !PyList_Check(list
))
1528 i
= PyList_GET_SIZE(list
);
1529 /* Count backwards because we always expect obj to be list[-1] */
1531 if (PyList_GET_ITEM(list
, i
) == obj
) {
1532 PyList_SetSlice(list
, i
, i
+ 1, NULL
);
1541 non-recursively destroy nested objects
1544 everything is now done in a macro.
1547 modified to use functions, after Tim Peter's suggestion.
1550 modified to restore a possible error.
1553 added better safe than sorry check for threadstate
1556 complete rewrite. We now build a chain via ob_type
1557 and save the limited number of types in ob_refcnt.
1558 This is perfect since we don't need any memory.
1559 A patch for free-threading would need just a lock.
1562 #define Py_TRASHCAN_TUPLE 1
1563 #define Py_TRASHCAN_LIST 2
1564 #define Py_TRASHCAN_DICT 3
1565 #define Py_TRASHCAN_FRAME 4
1566 #define Py_TRASHCAN_TRACEBACK 5
1567 /* extend here if other objects want protection */
1569 int _PyTrash_delete_nesting
= 0;
1571 PyObject
* _PyTrash_delete_later
= NULL
;
1574 _PyTrash_deposit_object(PyObject
*op
)
1578 if (PyTuple_Check(op
))
1579 typecode
= Py_TRASHCAN_TUPLE
;
1580 else if (PyList_Check(op
))
1581 typecode
= Py_TRASHCAN_LIST
;
1582 else if (PyDict_Check(op
))
1583 typecode
= Py_TRASHCAN_DICT
;
1584 else if (PyFrame_Check(op
))
1585 typecode
= Py_TRASHCAN_FRAME
;
1586 else if (PyTraceBack_Check(op
))
1587 typecode
= Py_TRASHCAN_TRACEBACK
;
1588 else /* We have a bug here -- those are the only types in GC */ {
1589 Py_FatalError("Type not supported in GC -- internal bug");
1590 return; /* pacify compiler -- execution never here */
1592 op
->ob_refcnt
= typecode
;
1594 op
->ob_type
= (PyTypeObject
*)_PyTrash_delete_later
;
1595 _PyTrash_delete_later
= op
;
1599 _PyTrash_destroy_chain(void)
1601 while (_PyTrash_delete_later
) {
1602 PyObject
*shredder
= _PyTrash_delete_later
;
1603 _PyTrash_delete_later
= (PyObject
*) shredder
->ob_type
;
1605 switch (shredder
->ob_refcnt
) {
1606 case Py_TRASHCAN_TUPLE
:
1607 shredder
->ob_type
= &PyTuple_Type
;
1609 case Py_TRASHCAN_LIST
:
1610 shredder
->ob_type
= &PyList_Type
;
1612 case Py_TRASHCAN_DICT
:
1613 shredder
->ob_type
= &PyDict_Type
;
1615 case Py_TRASHCAN_FRAME
:
1616 shredder
->ob_type
= &PyFrame_Type
;
1618 case Py_TRASHCAN_TRACEBACK
:
1619 shredder
->ob_type
= &PyTraceBack_Type
;
1622 _Py_NewReference(shredder
);
1624 ++_PyTrash_delete_nesting
;
1625 Py_DECREF(shredder
);
1626 --_PyTrash_delete_nesting
;
1630 #ifdef WITH_PYMALLOC
1631 #include "obmalloc.c"