blob: 065abdcd01e420b98763e93daaab80dd6e761f07 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Generic object operations; and implementation of None (NoObject) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005#include "sliceobject.h" /* For PyEllipsis_Type */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007#ifdef __cplusplus
8extern "C" {
9#endif
10
Tim Peters34592512002-07-11 06:23:50 +000011#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000012Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013
14Py_ssize_t
15_Py_GetRefTotal(void)
16{
17 PyObject *o;
18 Py_ssize_t total = _Py_RefTotal;
19 /* ignore the references to the dummy object of the dicts and sets
20 because they are not reliable and not useful (now that the
21 hash table code is well-tested) */
22 o = _PyDict_Dummy();
23 if (o != NULL)
24 total -= o->ob_refcnt;
25 o = _PySet_Dummy();
26 if (o != NULL)
27 total -= o->ob_refcnt;
28 return total;
29}
30#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031
Mark Hammonda2905272002-07-29 13:42:14 +000032int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000033
Guido van Rossum3f5da241990-12-20 15:06:42 +000034/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
35 These are used by the individual routines for object creation.
36 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037
Tim Peters78be7992003-03-23 02:51:01 +000038#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000039/* Head of circular doubly-linked list of all objects. These are linked
40 * together via the _ob_prev and _ob_next members of a PyObject, which
41 * exist only in a Py_TRACE_REFS build.
42 */
Tim Peters78be7992003-03-23 02:51:01 +000043static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000044
Tim Peters7571a0f2003-03-23 17:52:28 +000045/* Insert op at the front of the list of all objects. If force is true,
46 * op is added even if _ob_prev and _ob_next are non-NULL already. If
47 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
48 * force should be true if and only if op points to freshly allocated,
49 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000050 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000051 * Note that objects are normally added to the list via _Py_NewReference,
52 * which is called by PyObject_Init. Not all objects are initialized that
53 * way, though; exceptions include statically allocated type objects, and
54 * statically allocated singletons (like Py_True and Py_None).
55 */
Tim Peters36eb4df2003-03-23 03:33:13 +000056void
Tim Peters7571a0f2003-03-23 17:52:28 +000057_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000058{
Tim Peters7571a0f2003-03-23 17:52:28 +000059#ifdef Py_DEBUG
60 if (!force) {
61 /* If it's initialized memory, op must be in or out of
62 * the list unambiguously.
63 */
64 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
65 }
Tim Peters78be7992003-03-23 02:51:01 +000066#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000067 if (force || op->_ob_prev == NULL) {
68 op->_ob_next = refchain._ob_next;
69 op->_ob_prev = &refchain;
70 refchain._ob_next->_ob_prev = op;
71 refchain._ob_next = op;
72 }
73}
74#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000075
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078/* All types are added to type_list, at least when
79 they get one object created. That makes them
80 immortal, which unfortunately contributes to
81 garbage itself. If unlist_types_without_objects
82 is set, they will be removed from the type_list
83 once the last object is deallocated. */
84int unlist_types_without_objects;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000085extern int tuple_zero_allocs, fast_tuple_allocs;
86extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000087extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000088void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000090{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000091 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000092
93 for (tp = type_list; tp; tp = tp->tp_next)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000094 fprintf(f, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000095 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000096 tp->tp_maxalloc);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000097 fprintf(f, "fast tuple allocs: %d, empty: %d\n",
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000098 fast_tuple_allocs, tuple_zero_allocs);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000099 fprintf(f, "fast int allocs: pos: %d, neg: %d\n",
Sjoerd Mullender52c1f511993-10-25 08:40:52 +0000100 quick_int_allocs, quick_neg_int_allocs);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000101 fprintf(f, "null strings: %d, 1-strings: %d\n",
Sjoerd Mullender52c1f511993-10-25 08:40:52 +0000102 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000103}
104
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000105PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000106get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000107{
108 PyTypeObject *tp;
109 PyObject *result;
110 PyObject *v;
111
112 result = PyList_New(0);
113 if (result == NULL)
114 return NULL;
115 for (tp = type_list; tp; tp = tp->tp_next) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000116 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000117 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000118 if (v == NULL) {
119 Py_DECREF(result);
120 return NULL;
121 }
122 if (PyList_Append(result, v) < 0) {
123 Py_DECREF(v);
124 Py_DECREF(result);
125 return NULL;
126 }
127 Py_DECREF(v);
128 }
129 return result;
130}
131
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000132void
Fred Drake100814d2000-07-09 15:48:49 +0000133inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000134{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000135 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000136 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000137 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138 Py_FatalError("XXX inc_count sanity check");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000139 if (type_list)
140 type_list->tp_prev = tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000141 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000142 /* Note that as of Python 2.2, heap-allocated type objects
143 * can go away, but this code requires that they stay alive
144 * until program exit. That's why we're careful with
145 * refcounts here. type_list gets a new reference to tp,
146 * while ownership of the reference type_list used to hold
147 * (if any) was transferred to tp->tp_next in the line above.
148 * tp is thus effectively immortal after this.
149 */
150 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000151 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000152#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000153 /* Also insert in the doubly-linked list of all objects,
154 * if not already there.
155 */
156 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000157#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000158 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000159 tp->tp_allocs++;
160 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
161 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000162}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163
164void dec_count(PyTypeObject *tp)
165{
166 tp->tp_frees++;
167 if (unlist_types_without_objects &&
168 tp->tp_allocs == tp->tp_frees) {
169 /* unlink the type from type_list */
170 if (tp->tp_prev)
171 tp->tp_prev->tp_next = tp->tp_next;
172 else
173 type_list = tp->tp_next;
174 if (tp->tp_next)
175 tp->tp_next->tp_prev = tp->tp_prev;
176 tp->tp_next = tp->tp_prev = NULL;
177 Py_DECREF(tp);
178 }
179}
180
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000181#endif
182
Tim Peters7c321a82002-07-09 02:57:01 +0000183#ifdef Py_REF_DEBUG
184/* Log a fatal error; doesn't return. */
185void
186_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
187{
188 char buf[300];
189
190 PyOS_snprintf(buf, sizeof(buf),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191 "%s:%i object at %p has negative ref count "
192 "%" PY_FORMAT_SIZE_T "d",
193 fname, lineno, op, op->ob_refcnt);
Tim Peters7c321a82002-07-09 02:57:01 +0000194 Py_FatalError(buf);
195}
196
197#endif /* Py_REF_DEBUG */
198
Thomas Heller1328b522004-04-22 17:23:49 +0000199void
200Py_IncRef(PyObject *o)
201{
202 Py_XINCREF(o);
203}
204
205void
206Py_DecRef(PyObject *o)
207{
208 Py_XDECREF(o);
209}
210
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000212PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000214 if (op == NULL)
215 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000216 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000217 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000218 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219 return op;
220}
221
Guido van Rossumb18618d2000-05-03 23:44:39 +0000222PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000223PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000224{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000225 if (op == NULL)
226 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000227 /* Any changes should be reflected in PyObject_INIT_VAR */
228 op->ob_size = size;
229 op->ob_type = tp;
230 _Py_NewReference((PyObject *)op);
231 return op;
232}
233
234PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000235_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000236{
237 PyObject *op;
238 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
239 if (op == NULL)
240 return PyErr_NoMemory();
241 return PyObject_INIT(op, tp);
242}
243
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000244PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000245_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000247 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000248 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000249 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000251 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000252 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000253}
254
Neal Norwitz1a997502003-01-13 20:13:12 +0000255/* Implementation of PyObject_Print with recursion checking */
256static int
257internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000258{
Guido van Rossum278ef591991-07-27 21:40:24 +0000259 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000260 if (nesting > 10) {
261 PyErr_SetString(PyExc_RuntimeError, "print recursion");
262 return -1;
263 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000264 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000265 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000266#ifdef USE_STACKCHECK
267 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000268 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000269 return -1;
270 }
271#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000272 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000273 if (op == NULL) {
274 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275 }
Guido van Rossum90933611991-06-07 16:10:43 +0000276 else {
277 if (op->ob_refcnt <= 0)
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000278 /* XXX(twouters) cast refcount to long until %zd is
279 universally available */
280 fprintf(fp, "<refcnt %ld at %p>",
281 (long)op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000282 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000283 PyObject *s;
284 if (flags & Py_PRINT_RAW)
285 s = PyObject_Str(op);
286 else
287 s = PyObject_Repr(op);
288 if (s == NULL)
289 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000290 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000291 ret = internal_print(s, fp, Py_PRINT_RAW,
292 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000293 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000294 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000295 }
Guido van Rossum90933611991-06-07 16:10:43 +0000296 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000297 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000298 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000299 if (ret == 0) {
300 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000301 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000302 clearerr(fp);
303 ret = -1;
304 }
305 }
306 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307}
308
Neal Norwitz1a997502003-01-13 20:13:12 +0000309int
310PyObject_Print(PyObject *op, FILE *fp, int flags)
311{
312 return internal_print(op, fp, flags, 0);
313}
314
Guido van Rossum38938152006-08-21 23:36:26 +0000315/* For debugging convenience. Set a breakpoint here and call it from your DLL */
316void
Thomas Woutersb2137042007-02-01 18:02:27 +0000317_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000318{
319}
320
Neal Norwitz1a997502003-01-13 20:13:12 +0000321
Barry Warsaw9bf16442001-01-23 16:24:35 +0000322/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000323void
324_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000325{
Barry Warsaweefb1072001-02-22 22:39:18 +0000326 if (op == NULL)
327 fprintf(stderr, "NULL\n");
328 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000329 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000330 (void)PyObject_Print(op, stderr, 0);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000331 /* XXX(twouters) cast refcount to long until %zd is
332 universally available */
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000333 fprintf(stderr, "\n"
334 "type : %s\n"
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000335 "refcount: %ld\n"
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000336 "address : %p\n",
337 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000338 (long)op->ob_refcnt,
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000339 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000340 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000341}
Barry Warsaw903138f2001-01-23 16:33:18 +0000342
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000344PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000346 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000347 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000348#ifdef USE_STACKCHECK
349 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000350 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000351 return NULL;
352 }
353#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000354 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000356 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000357 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000358 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000359 else {
360 PyObject *res;
361 res = (*v->ob_type->tp_repr)(v);
362 if (res == NULL)
363 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000364#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000365 if (PyUnicode_Check(res)) {
366 PyObject* str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000367 str = PyUnicode_AsEncodedString(res, NULL, NULL);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000368 Py_DECREF(res);
369 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000370 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000371 else
372 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000373 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000374#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000375 if (!PyString_Check(res)) {
376 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000377 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000378 res->ob_type->tp_name);
379 Py_DECREF(res);
380 return NULL;
381 }
382 return res;
383 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000384}
385
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000387_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000388{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000389 PyObject *res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000390 int type_ok;
Guido van Rossumc6004111993-11-05 10:22:19 +0000391 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000392 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000393 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000394 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000395 return v;
396 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000397#ifdef Py_USING_UNICODE
398 if (PyUnicode_CheckExact(v)) {
399 Py_INCREF(v);
400 return v;
401 }
402#endif
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000403 if (v->ob_type->tp_str == NULL)
404 return PyObject_Repr(v);
405
406 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000407 if (res == NULL)
408 return NULL;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000409 type_ok = PyString_Check(res);
410#ifdef Py_USING_UNICODE
411 type_ok = type_ok || PyUnicode_Check(res);
412#endif
413 if (!type_ok) {
414 PyErr_Format(PyExc_TypeError,
415 "__str__ returned non-string (type %.200s)",
416 res->ob_type->tp_name);
417 Py_DECREF(res);
418 return NULL;
419 }
420 return res;
421}
422
423PyObject *
424PyObject_Str(PyObject *v)
425{
426 PyObject *res = _PyObject_Str(v);
427 if (res == NULL)
428 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000429#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000430 if (PyUnicode_Check(res)) {
431 PyObject* str;
432 str = PyUnicode_AsEncodedString(res, NULL, NULL);
433 Py_DECREF(res);
434 if (str)
435 res = str;
436 else
437 return NULL;
438 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000439#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +0000440 assert(PyString_Check(res));
Guido van Rossum4c08d552000-03-10 22:55:18 +0000441 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000442}
443
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000444#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000445PyObject *
446PyObject_Unicode(PyObject *v)
447{
448 PyObject *res;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000449 PyObject *func;
Neal Norwitz75801462006-03-14 06:02:16 +0000450 PyObject *str;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000451 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000452
Georg Brandl3daf7582006-03-13 22:22:11 +0000453 if (v == NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000454 res = PyString_FromString("<NULL>");
Neal Norwitz75801462006-03-14 06:02:16 +0000455 if (res == NULL)
456 return NULL;
457 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
458 Py_DECREF(res);
459 return str;
Georg Brandl3daf7582006-03-13 22:22:11 +0000460 } else if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000461 Py_INCREF(v);
462 return v;
463 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000464 /* XXX As soon as we have a tp_unicode slot, we should
465 check this before trying the __unicode__
466 method. */
467 if (unicodestr == NULL) {
468 unicodestr= PyString_InternFromString("__unicode__");
469 if (unicodestr == NULL)
470 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000471 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000472 func = PyObject_GetAttr(v, unicodestr);
473 if (func != NULL) {
474 res = PyEval_CallObject(func, (PyObject *)NULL);
475 Py_DECREF(func);
476 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000477 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000478 PyErr_Clear();
479 if (PyUnicode_Check(v)) {
480 /* For a Unicode subtype that's didn't overwrite __unicode__,
481 return a true Unicode object with the same data. */
482 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
483 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000484 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000485 if (PyString_CheckExact(v)) {
486 Py_INCREF(v);
487 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000488 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000489 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000490 if (v->ob_type->tp_str != NULL)
491 res = (*v->ob_type->tp_str)(v);
492 else
493 res = PyObject_Repr(v);
494 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000495 }
496 if (res == NULL)
497 return NULL;
498 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000499 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000500 Py_DECREF(res);
Neal Norwitz75801462006-03-14 06:02:16 +0000501 res = str;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000502 }
503 return res;
504}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000505#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000506
507
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000508/* The new comparison philosophy is: we completely separate three-way
509 comparison from rich comparison. That is, PyObject_Compare() and
510 PyObject_Cmp() *just* use the tp_compare slot. And PyObject_RichCompare()
511 and PyObject_RichCompareBool() *just* use the tp_richcompare slot.
512
513 See (*) below for practical amendments.
514
515 IOW, only cmp() uses tp_compare; the comparison operators (==, !=, <=, <,
516 >=, >) only use tp_richcompare. Note that list.sort() only uses <.
517
518 (And yes, eventually we'll rip out cmp() and tp_compare.)
519
520 The calling conventions are different: tp_compare only gets called with two
521 objects of the appropriate type; tp_richcompare gets called with a first
522 argument of the appropriate type and a second object of an arbitrary type.
523 We never do any kind of coercion.
524
525 The return conventions are also different.
526
527 The tp_compare slot should return a C int, as follows:
528
529 -1 if a < b or if an exception occurred
530 0 if a == b
531 +1 if a > b
532
533 No other return values are allowed. PyObject_Compare() has the same
534 calling convention.
535
536 The tp_richcompare slot should return an object, as follows:
537
538 NULL if an exception occurred
539 NotImplemented if the requested comparison is not implemented
540 any other false value if the requested comparison is false
541 any other true value if the requested comparison is true
542
543 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
544 NotImplemented.
545
546 (*) Practical amendments:
547
548 - If rich comparison returns NotImplemented, == and != are decided by
549 comparing the object pointer (i.e. falling back to the base object
550 implementation).
551
552 - If three-way comparison is not implemented, it falls back on rich
553 comparison (but not the other way around!).
554
Guido van Rossuma4073002002-05-31 20:03:54 +0000555*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000556
557/* Forward */
558static PyObject *do_richcompare(PyObject *v, PyObject *w, int op);
559
560/* Perform a three-way comparison, raising TypeError if three-way comparison
561 is not supported. */
Guido van Rossuma4073002002-05-31 20:03:54 +0000562static int
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000563do_compare(PyObject *v, PyObject *w)
Guido van Rossuma4073002002-05-31 20:03:54 +0000564{
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000565 cmpfunc f;
566 int ok;
567
568 if (v->ob_type == w->ob_type &&
569 (f = v->ob_type->tp_compare) != NULL) {
570 return (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000571 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000572
573 /* Now try three-way compare before giving up. This is intentionally
574 elaborate; if you have a it will raise TypeError if it detects two
575 objects that aren't ordered with respect to each other. */
576 ok = PyObject_RichCompareBool(v, w, Py_LT);
577 if (ok < 0)
578 return -1; /* Error */
579 if (ok)
580 return -1; /* Less than */
581 ok = PyObject_RichCompareBool(v, w, Py_GT);
582 if (ok < 0)
583 return -1; /* Error */
584 if (ok)
585 return 1; /* Greater than */
586 ok = PyObject_RichCompareBool(v, w, Py_EQ);
587 if (ok < 0)
588 return -1; /* Error */
589 if (ok)
590 return 0; /* Equal */
591
592 /* Give up */
593 PyErr_Format(PyExc_TypeError,
Neal Norwitz3bd844e2006-08-29 04:39:12 +0000594 "unorderable types: '%.100s' != '%.100s'",
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000595 v->ob_type->tp_name,
596 w->ob_type->tp_name);
597 return -1;
Guido van Rossuma4073002002-05-31 20:03:54 +0000598}
599
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000600/* Perform a three-way comparison. This wraps do_compare() with a check for
601 NULL arguments and a recursion check. */
602int
603PyObject_Compare(PyObject *v, PyObject *w)
604{
605 int res;
Guido van Rossuma4073002002-05-31 20:03:54 +0000606
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000607 if (v == NULL || w == NULL) {
608 if (!PyErr_Occurred())
609 PyErr_BadInternalCall();
610 return -1;
611 }
612 if (Py_EnterRecursiveCall(" in cmp"))
613 return -1;
614 res = do_compare(v, w);
615 Py_LeaveRecursiveCall();
616 return res < 0 ? -1 : res;
617}
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000618
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000619/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000620int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000621
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000622static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000623
624/* Perform a rich comparison, raising TypeError when the requested comparison
625 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000626static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000627do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000628{
629 richcmpfunc f;
630 PyObject *res;
631
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000632 if (v->ob_type != w->ob_type &&
633 PyType_IsSubtype(w->ob_type, v->ob_type) &&
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000634 (f = w->ob_type->tp_richcompare) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000635 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000636 if (res != Py_NotImplemented)
637 return res;
638 Py_DECREF(res);
639 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000640 if ((f = v->ob_type->tp_richcompare) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000641 res = (*f)(v, w, op);
642 if (res != Py_NotImplemented)
643 return res;
644 Py_DECREF(res);
645 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000646 if ((f = w->ob_type->tp_richcompare) != NULL) {
647 res = (*f)(w, v, _Py_SwappedOp[op]);
648 if (res != Py_NotImplemented)
649 return res;
650 Py_DECREF(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000651 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000652 /* If neither object implements it, provide a sensible default
653 for == and !=, but raise an exception for ordering. */
654 switch (op) {
655 case Py_EQ:
656 res = (v == w) ? Py_True : Py_False;
657 break;
658 case Py_NE:
659 res = (v != w) ? Py_True : Py_False;
660 break;
661 default:
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000662 /* XXX Special-case None so it doesn't show as NoneType() */
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000663 PyErr_Format(PyExc_TypeError,
664 "unorderable types: %.100s() %s %.100s()",
665 v->ob_type->tp_name,
666 opstrings[op],
667 w->ob_type->tp_name);
668 return NULL;
669 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000670 Py_INCREF(res);
671 return res;
672}
673
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000674/* Perform a rich comparison with object result. This wraps do_richcompare()
675 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000676
Guido van Rossume797ec12001-01-17 15:24:28 +0000677PyObject *
678PyObject_RichCompare(PyObject *v, PyObject *w, int op)
679{
680 PyObject *res;
681
682 assert(Py_LT <= op && op <= Py_GE);
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000683 if (v == NULL || w == NULL) {
684 if (!PyErr_Occurred())
685 PyErr_BadInternalCall();
686 return NULL;
687 }
Armin Rigo2b3eb402003-10-28 12:05:48 +0000688 if (Py_EnterRecursiveCall(" in cmp"))
689 return NULL;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000690 res = do_richcompare(v, w, op);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000691 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000692 return res;
693}
694
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000695/* Perform a rich comparison with integer result. This wraps
696 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000697int
698PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
699{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000700 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000701 int ok;
702
Raymond Hettinger93d44812004-03-21 17:01:44 +0000703 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000704 if (res == NULL)
705 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000706 if (PyBool_Check(res))
707 ok = (res == Py_True);
708 else
709 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000710 Py_DECREF(res);
711 return ok;
712}
Fred Drake13634cf2000-06-29 19:17:04 +0000713
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000714/* Turn the result of a three-way comparison into the result expected by a
715 rich comparison. */
716PyObject *
717Py_CmpToRich(int op, int cmp)
718{
719 PyObject *res;
720 int ok;
721
722 if (PyErr_Occurred())
723 return NULL;
724 switch (op) {
725 case Py_LT:
726 ok = cmp < 0;
727 break;
728 case Py_LE:
729 ok = cmp <= 0;
730 break;
731 case Py_EQ:
732 ok = cmp == 0;
733 break;
734 case Py_NE:
735 ok = cmp != 0;
736 break;
737 case Py_GT:
738 ok = cmp > 0;
739 break;
740 case Py_GE:
741 ok = cmp >= 0;
742 break;
743 default:
744 PyErr_BadArgument();
745 return NULL;
746 }
747 res = ok ? Py_True : Py_False;
748 Py_INCREF(res);
749 return res;
750}
751
Fred Drake13634cf2000-06-29 19:17:04 +0000752/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000753 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000754
755 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
756*/
757
758long
Fred Drake100814d2000-07-09 15:48:49 +0000759_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000760{
Tim Peters39dce292000-08-15 03:34:48 +0000761 double intpart, fractpart;
762 int expo;
763 long hipart;
764 long x; /* the final hash value */
765 /* This is designed so that Python numbers of different types
766 * that compare equal hash to the same value; otherwise comparisons
767 * of mapping keys will turn out weird.
768 */
769
Tim Peters39dce292000-08-15 03:34:48 +0000770 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000771 if (fractpart == 0.0) {
772 /* This must return the same hash as an equal int or long. */
773 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
774 /* Convert to long and use its hash. */
775 PyObject *plong; /* converted to Python long */
776 if (Py_IS_INFINITY(intpart))
777 /* can't convert to long int -- arbitrary */
778 v = v < 0 ? -271828.0 : 314159.0;
779 plong = PyLong_FromDouble(v);
780 if (plong == NULL)
781 return -1;
782 x = PyObject_Hash(plong);
783 Py_DECREF(plong);
784 return x;
785 }
786 /* Fits in a C long == a Python int, so is its own hash. */
787 x = (long)intpart;
788 if (x == -1)
789 x = -2;
790 return x;
791 }
792 /* The fractional part is non-zero, so we don't have to worry about
793 * making this match the hash of some other type.
794 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000795 * Since the VAX D double format has 56 mantissa bits, which is the
796 * most of any double format in use, each of these parts may have as
797 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000798 * So, assuming sizeof(long) >= 4, each part can be broken into two
799 * longs; frexp and multiplication are used to do that.
800 * Also, since the Cray double format has 15 exponent bits, which is
801 * the most of any double format in use, shifting the exponent field
802 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000803 */
Tim Peters39dce292000-08-15 03:34:48 +0000804 v = frexp(v, &expo);
805 v *= 2147483648.0; /* 2**31 */
806 hipart = (long)v; /* take the top 32 bits */
807 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
808 x = hipart + (long)v + (expo << 15);
809 if (x == -1)
810 x = -2;
811 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000812}
813
814long
Fred Drake100814d2000-07-09 15:48:49 +0000815_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000816{
817#if SIZEOF_LONG >= SIZEOF_VOID_P
818 return (long)p;
819#else
820 /* convert to a Python long and hash that */
821 PyObject* longobj;
822 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000823
Fred Drake13634cf2000-06-29 19:17:04 +0000824 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
825 x = -1;
826 goto finally;
827 }
828 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000829
Fred Drake13634cf2000-06-29 19:17:04 +0000830finally:
831 Py_XDECREF(longobj);
832 return x;
833#endif
834}
835
836
Guido van Rossum9bfef441993-03-29 10:43:31 +0000837long
Fred Drake100814d2000-07-09 15:48:49 +0000838PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000839{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000840 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000841 if (tp->tp_hash != NULL)
842 return (*tp->tp_hash)(v);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000843 /* Otherwise, the object can't be hashed */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000844 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
845 v->ob_type->tp_name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000846 return -1;
847}
848
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000849PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000850PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000851{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000853
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854 if (v->ob_type->tp_getattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +0000855 return (*v->ob_type->tp_getattr)(v, (char*)name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000856 w = PyString_InternFromString(name);
857 if (w == NULL)
858 return NULL;
859 res = PyObject_GetAttr(v, w);
860 Py_XDECREF(w);
861 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000862}
863
864int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000865PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000866{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000867 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000868 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000869 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000870 return 1;
871 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000872 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000873 return 0;
874}
875
876int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000877PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000878{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000879 PyObject *s;
880 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000881
Tim Peters6d6c1a32001-08-02 04:15:00 +0000882 if (v->ob_type->tp_setattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +0000883 return (*v->ob_type->tp_setattr)(v, (char*)name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884 s = PyString_InternFromString(name);
885 if (s == NULL)
886 return -1;
887 res = PyObject_SetAttr(v, s, w);
888 Py_XDECREF(s);
889 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000890}
891
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000892PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000893PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000894{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000895 PyTypeObject *tp = v->ob_type;
896
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000897 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000898#ifdef Py_USING_UNICODE
899 /* The Unicode to string conversion is done here because the
900 existing tp_getattro slots expect a string object as name
901 and we wouldn't want to break those. */
902 if (PyUnicode_Check(name)) {
903 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
904 if (name == NULL)
905 return NULL;
906 }
907 else
908#endif
909 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000910 PyErr_Format(PyExc_TypeError,
911 "attribute name must be string, not '%.200s'",
912 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000913 return NULL;
914 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000915 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000916 if (tp->tp_getattro != NULL)
917 return (*tp->tp_getattro)(v, name);
918 if (tp->tp_getattr != NULL)
919 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
920 PyErr_Format(PyExc_AttributeError,
921 "'%.50s' object has no attribute '%.400s'",
922 tp->tp_name, PyString_AS_STRING(name));
923 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000924}
925
926int
Fred Drake100814d2000-07-09 15:48:49 +0000927PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000928{
929 PyObject *res = PyObject_GetAttr(v, name);
930 if (res != NULL) {
931 Py_DECREF(res);
932 return 1;
933 }
934 PyErr_Clear();
935 return 0;
936}
937
938int
Fred Drake100814d2000-07-09 15:48:49 +0000939PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000940{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000941 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000942 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000943
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000944 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000945#ifdef Py_USING_UNICODE
946 /* The Unicode to string conversion is done here because the
947 existing tp_setattro slots expect a string object as name
948 and we wouldn't want to break those. */
949 if (PyUnicode_Check(name)) {
950 name = PyUnicode_AsEncodedString(name, NULL, NULL);
951 if (name == NULL)
952 return -1;
953 }
Tim Peters803526b2002-07-07 05:13:56 +0000954 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000955#endif
956 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000957 PyErr_Format(PyExc_TypeError,
958 "attribute name must be string, not '%.200s'",
959 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000960 return -1;
961 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000962 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000963 else
964 Py_INCREF(name);
965
966 PyString_InternInPlace(&name);
967 if (tp->tp_setattro != NULL) {
968 err = (*tp->tp_setattro)(v, name, value);
969 Py_DECREF(name);
970 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000971 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000972 if (tp->tp_setattr != NULL) {
973 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
974 Py_DECREF(name);
975 return err;
976 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000977 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000978 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
979 PyErr_Format(PyExc_TypeError,
980 "'%.100s' object has no attributes "
981 "(%s .%.100s)",
982 tp->tp_name,
983 value==NULL ? "del" : "assign to",
984 PyString_AS_STRING(name));
985 else
986 PyErr_Format(PyExc_TypeError,
987 "'%.100s' object has only read-only attributes "
988 "(%s .%.100s)",
989 tp->tp_name,
990 value==NULL ? "del" : "assign to",
991 PyString_AS_STRING(name));
992 return -1;
993}
994
995/* Helper to get a pointer to an object's __dict__ slot, if any */
996
997PyObject **
998_PyObject_GetDictPtr(PyObject *obj)
999{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001000 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001 PyTypeObject *tp = obj->ob_type;
1002
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003 dictoffset = tp->tp_dictoffset;
1004 if (dictoffset == 0)
1005 return NULL;
1006 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001007 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001008 size_t size;
1009
1010 tsize = ((PyVarObject *)obj)->ob_size;
1011 if (tsize < 0)
1012 tsize = -tsize;
1013 size = _PyObject_VAR_SIZE(tp, tsize);
1014
Tim Peters6d483d32001-10-06 21:27:34 +00001015 dictoffset += (long)size;
1016 assert(dictoffset > 0);
1017 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001018 }
1019 return (PyObject **) ((char *)obj + dictoffset);
1020}
1021
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001023PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001024{
1025 Py_INCREF(obj);
1026 return obj;
1027}
1028
Michael W. Hudson1593f502004-09-14 17:09:47 +00001029/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1030
Raymond Hettinger01538262003-03-17 08:24:35 +00001031PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1033{
1034 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001035 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001036 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001038 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039 PyObject **dictptr;
1040
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001041 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001042#ifdef Py_USING_UNICODE
1043 /* The Unicode to string conversion is done here because the
1044 existing tp_setattro slots expect a string object as name
1045 and we wouldn't want to break those. */
1046 if (PyUnicode_Check(name)) {
1047 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1048 if (name == NULL)
1049 return NULL;
1050 }
Tim Peters803526b2002-07-07 05:13:56 +00001051 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001052#endif
1053 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001054 PyErr_Format(PyExc_TypeError,
1055 "attribute name must be string, not '%.200s'",
1056 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001057 return NULL;
1058 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001059 }
1060 else
1061 Py_INCREF(name);
1062
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001064 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001065 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 }
1067
Guido van Rossum056fbf42002-08-19 19:22:50 +00001068 /* Inline _PyType_Lookup */
1069 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001070 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001071 PyObject *mro, *base, *dict;
1072
1073 /* Look in tp_dict of types in MRO */
1074 mro = tp->tp_mro;
1075 assert(mro != NULL);
1076 assert(PyTuple_Check(mro));
1077 n = PyTuple_GET_SIZE(mro);
1078 for (i = 0; i < n; i++) {
1079 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001080 assert(PyType_Check(base));
1081 dict = ((PyTypeObject *)base)->tp_dict;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001082 assert(dict && PyDict_Check(dict));
1083 descr = PyDict_GetItem(dict, name);
1084 if (descr != NULL)
1085 break;
1086 }
1087 }
1088
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001089 Py_XINCREF(descr);
1090
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001092 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001094 if (f != NULL && PyDescr_IsData(descr)) {
1095 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001096 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001097 goto done;
1098 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 }
1100
Guido van Rossumc66ff442002-08-19 16:50:48 +00001101 /* Inline _PyObject_GetDictPtr */
1102 dictoffset = tp->tp_dictoffset;
1103 if (dictoffset != 0) {
1104 PyObject *dict;
1105 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001107 size_t size;
1108
1109 tsize = ((PyVarObject *)obj)->ob_size;
1110 if (tsize < 0)
1111 tsize = -tsize;
1112 size = _PyObject_VAR_SIZE(tp, tsize);
1113
1114 dictoffset += (long)size;
1115 assert(dictoffset > 0);
1116 assert(dictoffset % SIZEOF_VOID_P == 0);
1117 }
1118 dictptr = (PyObject **) ((char *)obj + dictoffset);
1119 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001121 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 if (res != NULL) {
1123 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001124 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001125 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126 }
1127 }
1128 }
1129
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001130 if (f != NULL) {
1131 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001132 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001133 goto done;
1134 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135
1136 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001137 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001138 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001139 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140 }
1141
1142 PyErr_Format(PyExc_AttributeError,
1143 "'%.50s' object has no attribute '%.400s'",
1144 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001145 done:
1146 Py_DECREF(name);
1147 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148}
1149
1150int
1151PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1152{
1153 PyTypeObject *tp = obj->ob_type;
1154 PyObject *descr;
1155 descrsetfunc f;
1156 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001157 int res = -1;
1158
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001159 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001160#ifdef Py_USING_UNICODE
1161 /* The Unicode to string conversion is done here because the
1162 existing tp_setattro slots expect a string object as name
1163 and we wouldn't want to break those. */
1164 if (PyUnicode_Check(name)) {
1165 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1166 if (name == NULL)
1167 return -1;
1168 }
Tim Peters803526b2002-07-07 05:13:56 +00001169 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001170#endif
1171 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001172 PyErr_Format(PyExc_TypeError,
1173 "attribute name must be string, not '%.200s'",
1174 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001175 return -1;
1176 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001177 }
1178 else
1179 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180
1181 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001182 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001183 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001184 }
1185
1186 descr = _PyType_Lookup(tp, name);
1187 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001188 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001190 if (f != NULL && PyDescr_IsData(descr)) {
1191 res = f(descr, obj, value);
1192 goto done;
1193 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001194 }
1195
1196 dictptr = _PyObject_GetDictPtr(obj);
1197 if (dictptr != NULL) {
1198 PyObject *dict = *dictptr;
1199 if (dict == NULL && value != NULL) {
1200 dict = PyDict_New();
1201 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001202 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 *dictptr = dict;
1204 }
1205 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206 if (value == NULL)
1207 res = PyDict_DelItem(dict, name);
1208 else
1209 res = PyDict_SetItem(dict, name, value);
1210 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1211 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001212 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 }
1214 }
1215
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001216 if (f != NULL) {
1217 res = f(descr, obj, value);
1218 goto done;
1219 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220
1221 if (descr == NULL) {
1222 PyErr_Format(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001223 "'%.100s' object has no attribute '%.200s'",
Tim Peters6d6c1a32001-08-02 04:15:00 +00001224 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001225 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226 }
1227
1228 PyErr_Format(PyExc_AttributeError,
1229 "'%.50s' object attribute '%.400s' is read-only",
1230 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001231 done:
1232 Py_DECREF(name);
1233 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001234}
1235
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001236/* Test a value used as condition, e.g., in a for or if statement.
1237 Return -1 if an error occurred */
1238
1239int
Fred Drake100814d2000-07-09 15:48:49 +00001240PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001241{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001242 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001243 if (v == Py_True)
1244 return 1;
1245 if (v == Py_False)
1246 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001247 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001248 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001249 else if (v->ob_type->tp_as_number != NULL &&
Jack Diederich4dafcc42006-11-28 19:15:13 +00001250 v->ob_type->tp_as_number->nb_bool != NULL)
1251 res = (*v->ob_type->tp_as_number->nb_bool)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001252 else if (v->ob_type->tp_as_mapping != NULL &&
1253 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001254 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001255 else if (v->ob_type->tp_as_sequence != NULL &&
1256 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001257 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1258 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001259 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001260 /* if it is negative, it should be either -1 or -2 */
1261 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001262}
1263
Tim Peters803526b2002-07-07 05:13:56 +00001264/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001265 Return -1 if an error occurred */
1266
1267int
Fred Drake100814d2000-07-09 15:48:49 +00001268PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001269{
1270 int res;
1271 res = PyObject_IsTrue(v);
1272 if (res < 0)
1273 return res;
1274 return res == 0;
1275}
1276
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001277/* Test whether an object can be called */
1278
1279int
Fred Drake100814d2000-07-09 15:48:49 +00001280PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001281{
1282 if (x == NULL)
1283 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001284 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001285}
1286
Tim Peters7eea37e2001-09-04 22:08:56 +00001287/* Helper for PyObject_Dir.
1288 Merge the __dict__ of aclass into dict, and recursively also all
1289 the __dict__s of aclass's base classes. The order of merging isn't
1290 defined, as it's expected that only the final set of dict keys is
1291 interesting.
1292 Return 0 on success, -1 on error.
1293*/
1294
1295static int
1296merge_class_dict(PyObject* dict, PyObject* aclass)
1297{
1298 PyObject *classdict;
1299 PyObject *bases;
1300
1301 assert(PyDict_Check(dict));
1302 assert(aclass);
1303
1304 /* Merge in the type's dict (if any). */
1305 classdict = PyObject_GetAttrString(aclass, "__dict__");
1306 if (classdict == NULL)
1307 PyErr_Clear();
1308 else {
1309 int status = PyDict_Update(dict, classdict);
1310 Py_DECREF(classdict);
1311 if (status < 0)
1312 return -1;
1313 }
1314
1315 /* Recursively merge in the base types' (if any) dicts. */
1316 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001317 if (bases == NULL)
1318 PyErr_Clear();
1319 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001320 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001321 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001322 n = PySequence_Size(bases); /* This better be right */
1323 if (n < 0)
1324 PyErr_Clear();
1325 else {
1326 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001327 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001328 PyObject *base = PySequence_GetItem(bases, i);
1329 if (base == NULL) {
1330 Py_DECREF(bases);
1331 return -1;
1332 }
Tim Peters18e70832003-02-05 19:35:19 +00001333 status = merge_class_dict(dict, base);
1334 Py_DECREF(base);
1335 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001336 Py_DECREF(bases);
1337 return -1;
1338 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001339 }
1340 }
1341 Py_DECREF(bases);
1342 }
1343 return 0;
1344}
1345
Tim Peters305b5852001-09-17 02:38:46 +00001346/* Helper for PyObject_Dir.
1347 If obj has an attr named attrname that's a list, merge its string
1348 elements into keys of dict.
1349 Return 0 on success, -1 on error. Errors due to not finding the attr,
1350 or the attr not being a list, are suppressed.
1351*/
1352
1353static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001354merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001355{
1356 PyObject *list;
1357 int result = 0;
1358
1359 assert(PyDict_Check(dict));
1360 assert(obj);
1361 assert(attrname);
1362
1363 list = PyObject_GetAttrString(obj, attrname);
1364 if (list == NULL)
1365 PyErr_Clear();
1366
1367 else if (PyList_Check(list)) {
1368 int i;
1369 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1370 PyObject *item = PyList_GET_ITEM(list, i);
1371 if (PyString_Check(item)) {
1372 result = PyDict_SetItem(dict, item, Py_None);
1373 if (result < 0)
1374 break;
1375 }
1376 }
1377 }
1378
1379 Py_XDECREF(list);
1380 return result;
1381}
1382
Tim Peters7eea37e2001-09-04 22:08:56 +00001383/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1384 docstring, which should be kept in synch with this implementation. */
1385
1386PyObject *
1387PyObject_Dir(PyObject *arg)
1388{
1389 /* Set exactly one of these non-NULL before the end. */
1390 PyObject *result = NULL; /* result list */
1391 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1392
1393 /* If NULL arg, return the locals. */
1394 if (arg == NULL) {
1395 PyObject *locals = PyEval_GetLocals();
1396 if (locals == NULL)
1397 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001398 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001399 if (result == NULL)
1400 goto error;
1401 }
1402
1403 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001404 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001405 masterdict = PyObject_GetAttrString(arg, "__dict__");
1406 if (masterdict == NULL)
1407 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001408 if (!PyDict_Check(masterdict)) {
1409 PyErr_SetString(PyExc_TypeError,
1410 "module.__dict__ is not a dictionary");
1411 goto error;
1412 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001413 }
1414
1415 /* Elif some form of type or class, grab its dict and its bases.
1416 We deliberately don't suck up its __class__, as methods belonging
1417 to the metaclass would probably be more confusing than helpful. */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001418 else if (PyType_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001419 masterdict = PyDict_New();
1420 if (masterdict == NULL)
1421 goto error;
1422 if (merge_class_dict(masterdict, arg) < 0)
1423 goto error;
1424 }
1425
1426 /* Else look at its dict, and the attrs reachable from its class. */
1427 else {
1428 PyObject *itsclass;
1429 /* Create a dict to start with. CAUTION: Not everything
1430 responding to __dict__ returns a dict! */
1431 masterdict = PyObject_GetAttrString(arg, "__dict__");
1432 if (masterdict == NULL) {
1433 PyErr_Clear();
1434 masterdict = PyDict_New();
1435 }
1436 else if (!PyDict_Check(masterdict)) {
1437 Py_DECREF(masterdict);
1438 masterdict = PyDict_New();
1439 }
1440 else {
1441 /* The object may have returned a reference to its
1442 dict, so copy it to avoid mutating it. */
1443 PyObject *temp = PyDict_Copy(masterdict);
1444 Py_DECREF(masterdict);
1445 masterdict = temp;
1446 }
1447 if (masterdict == NULL)
1448 goto error;
1449
Tim Peters305b5852001-09-17 02:38:46 +00001450 /* Merge in __members__ and __methods__ (if any).
1451 XXX Would like this to go away someday; for now, it's
1452 XXX needed to get at im_self etc of method objects. */
1453 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1454 goto error;
1455 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1456 goto error;
1457
Tim Peters7eea37e2001-09-04 22:08:56 +00001458 /* Merge in attrs reachable from its class.
1459 CAUTION: Not all objects have a __class__ attr. */
1460 itsclass = PyObject_GetAttrString(arg, "__class__");
1461 if (itsclass == NULL)
1462 PyErr_Clear();
1463 else {
1464 int status = merge_class_dict(masterdict, itsclass);
1465 Py_DECREF(itsclass);
1466 if (status < 0)
1467 goto error;
1468 }
1469 }
1470
1471 assert((result == NULL) ^ (masterdict == NULL));
1472 if (masterdict != NULL) {
1473 /* The result comes from its keys. */
1474 assert(result == NULL);
1475 result = PyDict_Keys(masterdict);
1476 if (result == NULL)
1477 goto error;
1478 }
1479
1480 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001481 if (!PyList_Check(result)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001482 PyErr_Format(PyExc_TypeError,
1483 "Expected keys() to be a list, not '%.200s'",
1484 result->ob_type->tp_name);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001485 goto error;
1486 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001487 if (PyList_Sort(result) != 0)
1488 goto error;
1489 else
1490 goto normal_return;
1491
1492 error:
1493 Py_XDECREF(result);
1494 result = NULL;
1495 /* fall through */
1496 normal_return:
1497 Py_XDECREF(masterdict);
1498 return result;
1499}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001500
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001501/*
1502NoObject is usable as a non-NULL undefined value, used by the macro None.
1503There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001504so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001505(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001506*/
1507
Guido van Rossum0c182a11992-03-27 17:26:13 +00001508/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001509static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001510none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001511{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001512 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001513}
1514
Barry Warsaw9bf16442001-01-23 16:24:35 +00001515/* ARGUSED */
1516static void
Tim Peters803526b2002-07-07 05:13:56 +00001517none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001518{
1519 /* This should never get called, but we also don't want to SEGV if
1520 * we accidently decref None out of existance.
1521 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001522 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001523}
1524
1525
Guido van Rossumba21a492001-08-16 08:17:26 +00001526static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001527 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001528 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001529 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001530 0,
1531 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001532 none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001533 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001534 0, /*tp_getattr*/
1535 0, /*tp_setattr*/
1536 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001537 none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001538 0, /*tp_as_number*/
1539 0, /*tp_as_sequence*/
1540 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001541 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001542};
1543
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001544PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001545 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001546};
1547
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001548/* NotImplemented is an object that can be used to signal that an
1549 operation is not implemented for the given type combination. */
1550
1551static PyObject *
1552NotImplemented_repr(PyObject *op)
1553{
1554 return PyString_FromString("NotImplemented");
1555}
1556
1557static PyTypeObject PyNotImplemented_Type = {
1558 PyObject_HEAD_INIT(&PyType_Type)
1559 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001560 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001561 0,
1562 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001563 none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001564 0, /*tp_print*/
1565 0, /*tp_getattr*/
1566 0, /*tp_setattr*/
1567 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001568 NotImplemented_repr, /*tp_repr*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001569 0, /*tp_as_number*/
1570 0, /*tp_as_sequence*/
1571 0, /*tp_as_mapping*/
1572 0, /*tp_hash */
1573};
1574
1575PyObject _Py_NotImplementedStruct = {
1576 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1577};
1578
Guido van Rossumba21a492001-08-16 08:17:26 +00001579void
1580_Py_ReadyTypes(void)
1581{
1582 if (PyType_Ready(&PyType_Type) < 0)
1583 Py_FatalError("Can't initialize 'type'");
1584
Fred Drake0a4dd392004-07-02 18:57:45 +00001585 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1586 Py_FatalError("Can't initialize 'weakref'");
1587
Guido van Rossum77f6a652002-04-03 22:41:51 +00001588 if (PyType_Ready(&PyBool_Type) < 0)
1589 Py_FatalError("Can't initialize 'bool'");
1590
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001591 if (PyType_Ready(&PyBytes_Type) < 0)
1592 Py_FatalError("Can't initialize 'bytes'");
1593
Guido van Rossumcacfc072002-05-24 19:01:59 +00001594 if (PyType_Ready(&PyString_Type) < 0)
1595 Py_FatalError("Can't initialize 'str'");
1596
Guido van Rossumba21a492001-08-16 08:17:26 +00001597 if (PyType_Ready(&PyList_Type) < 0)
1598 Py_FatalError("Can't initialize 'list'");
1599
1600 if (PyType_Ready(&PyNone_Type) < 0)
1601 Py_FatalError("Can't initialize type(None)");
1602
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001603 if (PyType_Ready(Py_Ellipsis->ob_type) < 0)
1604 Py_FatalError("Can't initialize type(Ellipsis)");
1605
Guido van Rossumba21a492001-08-16 08:17:26 +00001606 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1607 Py_FatalError("Can't initialize type(NotImplemented)");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001608
1609 if (PyType_Ready(&PyCode_Type) < 0)
1610 Py_FatalError("Can't initialize 'code'");
Guido van Rossumba21a492001-08-16 08:17:26 +00001611}
1612
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001613
Guido van Rossum84a90321996-05-22 16:34:47 +00001614#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001615
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001616void
Fred Drake100814d2000-07-09 15:48:49 +00001617_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001618{
Tim Peters34592512002-07-11 06:23:50 +00001619 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001620 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001621 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001622 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001623}
1624
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001625void
Fred Drake100814d2000-07-09 15:48:49 +00001626_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001627{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001628#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001629 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001630#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001631 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001632 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001633 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001634 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001635 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001636#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001637 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1638 if (p == op)
1639 break;
1640 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001641 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001642 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001643#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001644 op->_ob_next->_ob_prev = op->_ob_prev;
1645 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001646 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001647 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001648}
1649
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001650void
Fred Drake100814d2000-07-09 15:48:49 +00001651_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001652{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001653 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001654 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001655 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001656}
1657
Tim Peters269b2a62003-04-17 19:52:29 +00001658/* Print all live objects. Because PyObject_Print is called, the
1659 * interpreter must be in a healthy state.
1660 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001661void
Fred Drake100814d2000-07-09 15:48:49 +00001662_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001663{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001664 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001665 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001666 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001667 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001668 if (PyObject_Print(op, fp, 0) != 0)
1669 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001670 putc('\n', fp);
1671 }
1672}
1673
Tim Peters269b2a62003-04-17 19:52:29 +00001674/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1675 * doesn't make any calls to the Python C API, so is always safe to call.
1676 */
1677void
1678_Py_PrintReferenceAddresses(FILE *fp)
1679{
1680 PyObject *op;
1681 fprintf(fp, "Remaining object addresses:\n");
1682 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001683 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1684 op->ob_refcnt, op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001685}
1686
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001687PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001688_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001689{
1690 int i, n;
1691 PyObject *t = NULL;
1692 PyObject *res, *op;
1693
1694 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1695 return NULL;
1696 op = refchain._ob_next;
1697 res = PyList_New(0);
1698 if (res == NULL)
1699 return NULL;
1700 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1701 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001702 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001703 op = op->_ob_next;
1704 if (op == &refchain)
1705 return res;
1706 }
1707 if (PyList_Append(res, op) < 0) {
1708 Py_DECREF(res);
1709 return NULL;
1710 }
1711 op = op->_ob_next;
1712 }
1713 return res;
1714}
1715
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001716#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001717
1718
1719/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001720PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001721
1722
1723/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001724Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001725
1726
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001727/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001728
Thomas Wouters334fb892000-07-25 12:56:38 +00001729void *
Fred Drake100814d2000-07-09 15:48:49 +00001730PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001731{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001732 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001733}
1734
Thomas Wouters334fb892000-07-25 12:56:38 +00001735void *
1736PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001737{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001738 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001739}
1740
1741void
Thomas Wouters334fb892000-07-25 12:56:38 +00001742PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001743{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001744 PyMem_FREE(p);
1745}
1746
1747
Guido van Rossum86610361998-04-10 22:32:46 +00001748/* These methods are used to control infinite recursion in repr, str, print,
1749 etc. Container objects that may recursively contain themselves,
1750 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1751 Py_ReprLeave() to avoid infinite recursion.
1752
1753 Py_ReprEnter() returns 0 the first time it is called for a particular
1754 object and 1 every time thereafter. It returns -1 if an exception
1755 occurred. Py_ReprLeave() has no return value.
1756
1757 See dictobject.c and listobject.c for examples of use.
1758*/
1759
1760#define KEY "Py_Repr"
1761
1762int
Fred Drake100814d2000-07-09 15:48:49 +00001763Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001764{
1765 PyObject *dict;
1766 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001767 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001768
1769 dict = PyThreadState_GetDict();
1770 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001771 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001772 list = PyDict_GetItemString(dict, KEY);
1773 if (list == NULL) {
1774 list = PyList_New(0);
1775 if (list == NULL)
1776 return -1;
1777 if (PyDict_SetItemString(dict, KEY, list) < 0)
1778 return -1;
1779 Py_DECREF(list);
1780 }
1781 i = PyList_GET_SIZE(list);
1782 while (--i >= 0) {
1783 if (PyList_GET_ITEM(list, i) == obj)
1784 return 1;
1785 }
1786 PyList_Append(list, obj);
1787 return 0;
1788}
1789
1790void
Fred Drake100814d2000-07-09 15:48:49 +00001791Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001792{
1793 PyObject *dict;
1794 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001795 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001796
1797 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001798 if (dict == NULL)
1799 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001800 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001801 if (list == NULL || !PyList_Check(list))
1802 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001803 i = PyList_GET_SIZE(list);
1804 /* Count backwards because we always expect obj to be list[-1] */
1805 while (--i >= 0) {
1806 if (PyList_GET_ITEM(list, i) == obj) {
1807 PyList_SetSlice(list, i, i + 1, NULL);
1808 break;
1809 }
1810 }
1811}
Guido van Rossumd724b232000-03-13 16:01:29 +00001812
Tim Peters803526b2002-07-07 05:13:56 +00001813/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001814
Tim Peters803526b2002-07-07 05:13:56 +00001815/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001816int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001817
Tim Peters803526b2002-07-07 05:13:56 +00001818/* List of objects that still need to be cleaned up, singly linked via their
1819 * gc headers' gc_prev pointers.
1820 */
1821PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001822
Tim Peters803526b2002-07-07 05:13:56 +00001823/* Add op to the _PyTrash_delete_later list. Called when the current
1824 * call-stack depth gets large. op must be a currently untracked gc'ed
1825 * object, with refcount 0. Py_DECREF must already have been called on it.
1826 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001827void
Fred Drake100814d2000-07-09 15:48:49 +00001828_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001829{
Tim Peters803526b2002-07-07 05:13:56 +00001830 assert(PyObject_IS_GC(op));
1831 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1832 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00001833 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001834 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001835}
1836
Tim Peters803526b2002-07-07 05:13:56 +00001837/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1838 * the call-stack unwinds again.
1839 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001840void
Fred Drake100814d2000-07-09 15:48:49 +00001841_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001842{
1843 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00001844 PyObject *op = _PyTrash_delete_later;
1845 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001846
Neil Schemenauerf589c052002-03-29 03:05:54 +00001847 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00001848 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001849
Tim Peters803526b2002-07-07 05:13:56 +00001850 /* Call the deallocator directly. This used to try to
1851 * fool Py_DECREF into calling it indirectly, but
1852 * Py_DECREF was already called on this object, and in
1853 * assorted non-release builds calling Py_DECREF again ends
1854 * up distorting allocation statistics.
1855 */
1856 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00001857 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00001858 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00001859 --_PyTrash_delete_nesting;
1860 }
1861}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001862
1863#ifdef __cplusplus
1864}
1865#endif
1866