blob: 9d96e86c589827cd75f49a5c889b1ea0c049f663 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Benjamin Peterson722954a2011-06-11 16:33:35 -05002/* Generic object operations; and implementation of None */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +00005#include "frameobject.h"
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017 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;
Antoine Pitrou9d952542013-08-24 21:07:07 +020025 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 if (o != NULL)
27 total -= o->ob_refcnt;
28 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000029}
30#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031
Guido van Rossum3f5da241990-12-20 15:06:42 +000032/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
33 These are used by the individual routines for object creation.
34 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000035
Tim Peters78be7992003-03-23 02:51:01 +000036#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000037/* Head of circular doubly-linked list of all objects. These are linked
38 * together via the _ob_prev and _ob_next members of a PyObject, which
39 * exist only in a Py_TRACE_REFS build.
40 */
Tim Peters78be7992003-03-23 02:51:01 +000041static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000042
Tim Peters7571a0f2003-03-23 17:52:28 +000043/* Insert op at the front of the list of all objects. If force is true,
44 * op is added even if _ob_prev and _ob_next are non-NULL already. If
45 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
46 * force should be true if and only if op points to freshly allocated,
47 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000048 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000049 * Note that objects are normally added to the list via _Py_NewReference,
50 * which is called by PyObject_Init. Not all objects are initialized that
51 * way, though; exceptions include statically allocated type objects, and
52 * statically allocated singletons (like Py_True and Py_None).
53 */
Tim Peters36eb4df2003-03-23 03:33:13 +000054void
Tim Peters7571a0f2003-03-23 17:52:28 +000055_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000056{
Tim Peters7571a0f2003-03-23 17:52:28 +000057#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (!force) {
59 /* If it's initialized memory, op must be in or out of
60 * the list unambiguously.
61 */
62 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
63 }
Tim Peters78be7992003-03-23 02:51:01 +000064#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (force || op->_ob_prev == NULL) {
66 op->_ob_next = refchain._ob_next;
67 op->_ob_prev = &refchain;
68 refchain._ob_next->_ob_prev = op;
69 refchain._ob_next = op;
70 }
Tim Peters7571a0f2003-03-23 17:52:28 +000071}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000073
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000076/* All types are added to type_list, at least when
77 they get one object created. That makes them
78 immortal, which unfortunately contributes to
79 garbage itself. If unlist_types_without_objects
80 is set, they will be removed from the type_list
81 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +000082static int unlist_types_without_objects;
83extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
84extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
85extern Py_ssize_t null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000086void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000087dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 for (tp = type_list; tp; tp = tp->tp_next)
92 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
93 "freed: %" PY_FORMAT_SIZE_T "d, "
94 "max in use: %" PY_FORMAT_SIZE_T "d\n",
95 tp->tp_name, tp->tp_allocs, tp->tp_frees,
96 tp->tp_maxalloc);
97 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
98 "empty: %" PY_FORMAT_SIZE_T "d\n",
99 fast_tuple_allocs, tuple_zero_allocs);
100 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
101 "neg: %" PY_FORMAT_SIZE_T "d\n",
102 quick_int_allocs, quick_neg_int_allocs);
103 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
104 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
105 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000106}
107
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000108PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000109get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PyTypeObject *tp;
112 PyObject *result;
113 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 result = PyList_New(0);
116 if (result == NULL)
117 return NULL;
118 for (tp = type_list; tp; tp = tp->tp_next) {
119 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
120 tp->tp_frees, tp->tp_maxalloc);
121 if (v == NULL) {
122 Py_DECREF(result);
123 return NULL;
124 }
125 if (PyList_Append(result, v) < 0) {
126 Py_DECREF(v);
127 Py_DECREF(result);
128 return NULL;
129 }
130 Py_DECREF(v);
131 }
132 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000133}
134
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000135void
Fred Drake100814d2000-07-09 15:48:49 +0000136inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
139 /* first time; insert in linked list */
140 if (tp->tp_next != NULL) /* sanity check */
141 Py_FatalError("XXX inc_count sanity check");
142 if (type_list)
143 type_list->tp_prev = tp;
144 tp->tp_next = type_list;
145 /* Note that as of Python 2.2, heap-allocated type objects
146 * can go away, but this code requires that they stay alive
147 * until program exit. That's why we're careful with
148 * refcounts here. type_list gets a new reference to tp,
149 * while ownership of the reference type_list used to hold
150 * (if any) was transferred to tp->tp_next in the line above.
151 * tp is thus effectively immortal after this.
152 */
153 Py_INCREF(tp);
154 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000155#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 /* Also insert in the doubly-linked list of all objects,
157 * if not already there.
158 */
159 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000160#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 }
162 tp->tp_allocs++;
163 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
164 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000165}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000166
167void dec_count(PyTypeObject *tp)
168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 tp->tp_frees++;
170 if (unlist_types_without_objects &&
171 tp->tp_allocs == tp->tp_frees) {
172 /* unlink the type from type_list */
173 if (tp->tp_prev)
174 tp->tp_prev->tp_next = tp->tp_next;
175 else
176 type_list = tp->tp_next;
177 if (tp->tp_next)
178 tp->tp_next->tp_prev = tp->tp_prev;
179 tp->tp_next = tp->tp_prev = NULL;
180 Py_DECREF(tp);
181 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000182}
183
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000184#endif
185
Tim Peters7c321a82002-07-09 02:57:01 +0000186#ifdef Py_REF_DEBUG
187/* Log a fatal error; doesn't return. */
188void
189_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 char buf[300];
Tim Peters7c321a82002-07-09 02:57:01 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 PyOS_snprintf(buf, sizeof(buf),
194 "%s:%i object at %p has negative ref count "
195 "%" PY_FORMAT_SIZE_T "d",
196 fname, lineno, op, op->ob_refcnt);
197 Py_FatalError(buf);
Tim Peters7c321a82002-07-09 02:57:01 +0000198}
199
200#endif /* Py_REF_DEBUG */
201
Thomas Heller1328b522004-04-22 17:23:49 +0000202void
203Py_IncRef(PyObject *o)
204{
205 Py_XINCREF(o);
206}
207
208void
209Py_DecRef(PyObject *o)
210{
211 Py_XDECREF(o);
212}
213
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000215PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (op == NULL)
218 return PyErr_NoMemory();
219 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
220 Py_TYPE(op) = tp;
221 _Py_NewReference(op);
222 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223}
224
Guido van Rossumb18618d2000-05-03 23:44:39 +0000225PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000226PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (op == NULL)
229 return (PyVarObject *) PyErr_NoMemory();
230 /* Any changes should be reflected in PyObject_INIT_VAR */
231 op->ob_size = size;
232 Py_TYPE(op) = tp;
233 _Py_NewReference((PyObject *)op);
234 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000235}
236
237PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000238_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyObject *op;
241 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
242 if (op == NULL)
243 return PyErr_NoMemory();
244 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000245}
246
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000247PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000248_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 PyVarObject *op;
251 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
252 op = (PyVarObject *) PyObject_MALLOC(size);
253 if (op == NULL)
254 return (PyVarObject *)PyErr_NoMemory();
255 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000256}
257
Antoine Pitrou796564c2013-07-30 19:59:21 +0200258void
259PyObject_CallFinalizer(PyObject *self)
260{
261 PyTypeObject *tp = Py_TYPE(self);
262
263 /* The former could happen on heaptypes created from the C API, e.g.
264 PyType_FromSpec(). */
265 if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
266 tp->tp_finalize == NULL)
267 return;
268 /* tp_finalize should only be called once. */
269 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
270 return;
271
272 tp->tp_finalize(self);
273 if (PyType_IS_GC(tp))
274 _PyGC_SET_FINALIZED(self, 1);
275}
276
277int
278PyObject_CallFinalizerFromDealloc(PyObject *self)
279{
280 Py_ssize_t refcnt;
281
282 /* Temporarily resurrect the object. */
283 if (self->ob_refcnt != 0) {
284 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
285 "object with a non-zero refcount");
286 }
287 self->ob_refcnt = 1;
288
289 PyObject_CallFinalizer(self);
290
291 /* Undo the temporary resurrection; can't use DECREF here, it would
292 * cause a recursive call.
293 */
294 assert(self->ob_refcnt > 0);
295 if (--self->ob_refcnt == 0)
296 return 0; /* this is the normal path out */
297
298 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
299 * never happened.
300 */
301 refcnt = self->ob_refcnt;
302 _Py_NewReference(self);
303 self->ob_refcnt = refcnt;
304
305 if (PyType_IS_GC(Py_TYPE(self))) {
306 assert(_PyGC_REFS(self) != _PyGC_REFS_UNTRACKED);
307 }
308 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
309 * we need to undo that. */
310 _Py_DEC_REFTOTAL;
311 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
312 * chain, so no more to do there.
313 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
314 * _Py_NewReference bumped tp_allocs: both of those need to be
315 * undone.
316 */
317#ifdef COUNT_ALLOCS
318 --Py_TYPE(self)->tp_frees;
319 --Py_TYPE(self)->tp_allocs;
320#endif
321 return -1;
322}
323
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000324int
325PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (PyErr_CheckSignals())
329 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000330#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 if (PyOS_CheckStack()) {
332 PyErr_SetString(PyExc_MemoryError, "stack overflow");
333 return -1;
334 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000335#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 clearerr(fp); /* Clear any previous error condition */
337 if (op == NULL) {
338 Py_BEGIN_ALLOW_THREADS
339 fprintf(fp, "<nil>");
340 Py_END_ALLOW_THREADS
341 }
342 else {
343 if (op->ob_refcnt <= 0)
344 /* XXX(twouters) cast refcount to long until %zd is
345 universally available */
346 Py_BEGIN_ALLOW_THREADS
347 fprintf(fp, "<refcnt %ld at %p>",
348 (long)op->ob_refcnt, op);
349 Py_END_ALLOW_THREADS
350 else {
351 PyObject *s;
352 if (flags & Py_PRINT_RAW)
353 s = PyObject_Str(op);
354 else
355 s = PyObject_Repr(op);
356 if (s == NULL)
357 ret = -1;
358 else if (PyBytes_Check(s)) {
359 fwrite(PyBytes_AS_STRING(s), 1,
360 PyBytes_GET_SIZE(s), fp);
361 }
362 else if (PyUnicode_Check(s)) {
363 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200364 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (t == NULL)
366 ret = 0;
367 else {
368 fwrite(PyBytes_AS_STRING(t), 1,
369 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000370 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 }
372 }
373 else {
374 PyErr_Format(PyExc_TypeError,
375 "str() or repr() returned '%.100s'",
376 s->ob_type->tp_name);
377 ret = -1;
378 }
379 Py_XDECREF(s);
380 }
381 }
382 if (ret == 0) {
383 if (ferror(fp)) {
384 PyErr_SetFromErrno(PyExc_IOError);
385 clearerr(fp);
386 ret = -1;
387 }
388 }
389 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390}
391
Guido van Rossum38938152006-08-21 23:36:26 +0000392/* For debugging convenience. Set a breakpoint here and call it from your DLL */
393void
Thomas Woutersb2137042007-02-01 18:02:27 +0000394_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000395{
396}
397
Neal Norwitz1a997502003-01-13 20:13:12 +0000398
Barry Warsaw9bf16442001-01-23 16:24:35 +0000399/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000400void
401_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 if (op == NULL)
404 fprintf(stderr, "NULL\n");
405 else {
Georg Brandldfd73442009-04-05 11:47:34 +0000406#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 PyGILState_STATE gil;
Georg Brandldfd73442009-04-05 11:47:34 +0000408#endif
Victor Stinnere5132102013-08-26 13:49:06 +0200409 PyObject *error_type, *error_value, *error_traceback;
410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 fprintf(stderr, "object : ");
Georg Brandldfd73442009-04-05 11:47:34 +0000412#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 gil = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000414#endif
Victor Stinnere5132102013-08-26 13:49:06 +0200415
416 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 (void)PyObject_Print(op, stderr, 0);
Victor Stinnere5132102013-08-26 13:49:06 +0200418 PyErr_Restore(error_type, error_value, error_traceback);
419
Georg Brandldfd73442009-04-05 11:47:34 +0000420#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyGILState_Release(gil);
Georg Brandldfd73442009-04-05 11:47:34 +0000422#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* XXX(twouters) cast refcount to long until %zd is
424 universally available */
425 fprintf(stderr, "\n"
426 "type : %s\n"
427 "refcount: %ld\n"
428 "address : %p\n",
429 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
430 (long)op->ob_refcnt,
431 op);
432 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000433}
Barry Warsaw903138f2001-01-23 16:33:18 +0000434
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000435PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000436PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 PyObject *res;
439 if (PyErr_CheckSignals())
440 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000441#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (PyOS_CheckStack()) {
443 PyErr_SetString(PyExc_MemoryError, "stack overflow");
444 return NULL;
445 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000446#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (v == NULL)
448 return PyUnicode_FromString("<NULL>");
449 if (Py_TYPE(v)->tp_repr == NULL)
450 return PyUnicode_FromFormat("<%s object at %p>",
451 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200452
453#ifdef Py_DEBUG
454 /* PyObject_Repr() must not be called with an exception set,
455 because it may clear it (directly or indirectly) and so the
456 caller looses its exception */
457 assert(!PyErr_Occurred());
458#endif
459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 res = (*v->ob_type->tp_repr)(v);
Victor Stinner0a54cf12011-12-01 03:22:44 +0100461 if (res == NULL)
462 return NULL;
463 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 PyErr_Format(PyExc_TypeError,
465 "__repr__ returned non-string (type %.200s)",
466 res->ob_type->tp_name);
467 Py_DECREF(res);
468 return NULL;
469 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100470#ifndef Py_DEBUG
471 if (PyUnicode_READY(res) < 0)
472 return NULL;
473#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475}
476
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000477PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000478PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 PyObject *res;
481 if (PyErr_CheckSignals())
482 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000483#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (PyOS_CheckStack()) {
485 PyErr_SetString(PyExc_MemoryError, "stack overflow");
486 return NULL;
487 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000488#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (v == NULL)
490 return PyUnicode_FromString("<NULL>");
491 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100492#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100493 if (PyUnicode_READY(v) < 0)
494 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100495#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 Py_INCREF(v);
497 return v;
498 }
499 if (Py_TYPE(v)->tp_str == NULL)
500 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000501
Victor Stinner33824f62013-08-26 14:05:19 +0200502#ifdef Py_DEBUG
503 /* PyObject_Str() must not be called with an exception set,
504 because it may clear it (directly or indirectly) and so the
505 caller looses its exception */
506 assert(!PyErr_Occurred());
507#endif
508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* It is possible for a type to have a tp_str representation that loops
510 infinitely. */
511 if (Py_EnterRecursiveCall(" while getting the str of an object"))
512 return NULL;
513 res = (*Py_TYPE(v)->tp_str)(v);
514 Py_LeaveRecursiveCall();
515 if (res == NULL)
516 return NULL;
517 if (!PyUnicode_Check(res)) {
518 PyErr_Format(PyExc_TypeError,
519 "__str__ returned non-string (type %.200s)",
520 Py_TYPE(res)->tp_name);
521 Py_DECREF(res);
522 return NULL;
523 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100524#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100525 if (PyUnicode_READY(res) < 0)
526 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100527#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100528 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000530}
531
Georg Brandl559e5d72008-06-11 18:37:52 +0000532PyObject *
533PyObject_ASCII(PyObject *v)
534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 repr = PyObject_Repr(v);
538 if (repr == NULL)
539 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000540
Victor Stinneraf037572013-04-14 18:44:10 +0200541 if (PyUnicode_IS_ASCII(repr))
542 return repr;
543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200545 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 Py_DECREF(repr);
547 if (ascii == NULL)
548 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 res = PyUnicode_DecodeASCII(
551 PyBytes_AS_STRING(ascii),
552 PyBytes_GET_SIZE(ascii),
553 NULL);
554
555 Py_DECREF(ascii);
556 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000557}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000558
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000559PyObject *
560PyObject_Bytes(PyObject *v)
561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 PyObject *result, *func;
Benjamin Petersonce798522012-01-22 11:24:29 -0500563 _Py_IDENTIFIER(__bytes__);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (v == NULL)
566 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 if (PyBytes_CheckExact(v)) {
569 Py_INCREF(v);
570 return v;
571 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000572
Benjamin Petersonce798522012-01-22 11:24:29 -0500573 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (func != NULL) {
575 result = PyObject_CallFunctionObjArgs(func, NULL);
576 Py_DECREF(func);
577 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000578 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000580 PyErr_Format(PyExc_TypeError,
581 "__bytes__ returned non-bytes (type %.200s)",
582 Py_TYPE(result)->tp_name);
583 Py_DECREF(result);
584 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 }
586 return result;
587 }
588 else if (PyErr_Occurred())
589 return NULL;
590 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000591}
592
Mark Dickinsonc008a172009-02-01 13:59:22 +0000593/* For Python 3.0.1 and later, the old three-way comparison has been
594 completely removed in favour of rich comparisons. PyObject_Compare() and
595 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000596 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000597 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000598
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000599 See (*) below for practical amendments.
600
Mark Dickinsonc008a172009-02-01 13:59:22 +0000601 tp_richcompare gets called with a first argument of the appropriate type
602 and a second object of an arbitrary type. We never do any kind of
603 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000604
Mark Dickinsonc008a172009-02-01 13:59:22 +0000605 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000606
607 NULL if an exception occurred
608 NotImplemented if the requested comparison is not implemented
609 any other false value if the requested comparison is false
610 any other true value if the requested comparison is true
611
612 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
613 NotImplemented.
614
615 (*) Practical amendments:
616
617 - If rich comparison returns NotImplemented, == and != are decided by
618 comparing the object pointer (i.e. falling back to the base object
619 implementation).
620
Guido van Rossuma4073002002-05-31 20:03:54 +0000621*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000622
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000623/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000624int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000625
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000626static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000627
628/* Perform a rich comparison, raising TypeError when the requested comparison
629 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000630static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000631do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 richcmpfunc f;
634 PyObject *res;
635 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (v->ob_type != w->ob_type &&
638 PyType_IsSubtype(w->ob_type, v->ob_type) &&
639 (f = w->ob_type->tp_richcompare) != NULL) {
640 checked_reverse_op = 1;
641 res = (*f)(w, v, _Py_SwappedOp[op]);
642 if (res != Py_NotImplemented)
643 return res;
644 Py_DECREF(res);
645 }
646 if ((f = v->ob_type->tp_richcompare) != NULL) {
647 res = (*f)(v, w, op);
648 if (res != Py_NotImplemented)
649 return res;
650 Py_DECREF(res);
651 }
652 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
653 res = (*f)(w, v, _Py_SwappedOp[op]);
654 if (res != Py_NotImplemented)
655 return res;
656 Py_DECREF(res);
657 }
658 /* If neither object implements it, provide a sensible default
659 for == and !=, but raise an exception for ordering. */
660 switch (op) {
661 case Py_EQ:
662 res = (v == w) ? Py_True : Py_False;
663 break;
664 case Py_NE:
665 res = (v != w) ? Py_True : Py_False;
666 break;
667 default:
668 /* XXX Special-case None so it doesn't show as NoneType() */
669 PyErr_Format(PyExc_TypeError,
670 "unorderable types: %.100s() %s %.100s()",
671 v->ob_type->tp_name,
672 opstrings[op],
673 w->ob_type->tp_name);
674 return NULL;
675 }
676 Py_INCREF(res);
677 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000678}
679
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000680/* Perform a rich comparison with object result. This wraps do_richcompare()
681 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000682
Guido van Rossume797ec12001-01-17 15:24:28 +0000683PyObject *
684PyObject_RichCompare(PyObject *v, PyObject *w, int op)
685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 assert(Py_LT <= op && op <= Py_GE);
689 if (v == NULL || w == NULL) {
690 if (!PyErr_Occurred())
691 PyErr_BadInternalCall();
692 return NULL;
693 }
694 if (Py_EnterRecursiveCall(" in comparison"))
695 return NULL;
696 res = do_richcompare(v, w, op);
697 Py_LeaveRecursiveCall();
698 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000699}
700
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000701/* Perform a rich comparison with integer result. This wraps
702 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000703int
704PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 PyObject *res;
707 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 /* Quick result when objects are the same.
710 Guarantees that identity implies equality. */
711 if (v == w) {
712 if (op == Py_EQ)
713 return 1;
714 else if (op == Py_NE)
715 return 0;
716 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 res = PyObject_RichCompare(v, w, op);
719 if (res == NULL)
720 return -1;
721 if (PyBool_Check(res))
722 ok = (res == Py_True);
723 else
724 ok = PyObject_IsTrue(res);
725 Py_DECREF(res);
726 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000727}
Fred Drake13634cf2000-06-29 19:17:04 +0000728
729/* Set of hash utility functions to help maintaining the invariant that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000731
732 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
733*/
734
Mark Dickinsondc787d22010-05-23 13:33:13 +0000735/* For numeric types, the hash of a number x is based on the reduction
736 of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that
737 hash(x) == hash(y) whenever x and y are numerically equal, even if
738 x and y have different types.
739
740 A quick summary of the hashing strategy:
741
742 (1) First define the 'reduction of x modulo P' for any rational
743 number x; this is a standard extension of the usual notion of
744 reduction modulo P for integers. If x == p/q (written in lowest
745 terms), the reduction is interpreted as the reduction of p times
746 the inverse of the reduction of q, all modulo P; if q is exactly
747 divisible by P then define the reduction to be infinity. So we've
748 got a well-defined map
749
750 reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }.
751
752 (2) Now for a rational number x, define hash(x) by:
753
754 reduce(x) if x >= 0
755 -reduce(-x) if x < 0
756
757 If the result of the reduction is infinity (this is impossible for
758 integers, floats and Decimals) then use the predefined hash value
759 _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead.
760 _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the
761 hashes of float and Decimal infinities and nans.
762
763 A selling point for the above strategy is that it makes it possible
764 to compute hashes of decimal and binary floating-point numbers
765 efficiently, even if the exponent of the binary or decimal number
766 is large. The key point is that
767
768 reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS)
769
770 provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a
771 binary or decimal float is never infinity, since the denominator is a power
772 of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have,
773 for nonnegative x,
774
775 reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS
776
777 reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS
778
779 and reduce(10**e) can be computed efficiently by the usual modular
780 exponentiation algorithm. For reduce(2**e) it's even better: since
781 P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication
782 by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits.
783
784 */
785
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000786Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000787_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000788{
Mark Dickinsondc787d22010-05-23 13:33:13 +0000789 int e, sign;
790 double m;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000791 Py_uhash_t x, y;
Tim Peters39dce292000-08-15 03:34:48 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (!Py_IS_FINITE(v)) {
794 if (Py_IS_INFINITY(v))
Mark Dickinsondc787d22010-05-23 13:33:13 +0000795 return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 else
Mark Dickinsondc787d22010-05-23 13:33:13 +0000797 return _PyHASH_NAN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000799
800 m = frexp(v, &e);
801
802 sign = 1;
803 if (m < 0) {
804 sign = -1;
805 m = -m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000807
808 /* process 28 bits at a time; this should work well both for binary
809 and hexadecimal floating point. */
810 x = 0;
811 while (m) {
812 x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28);
813 m *= 268435456.0; /* 2**28 */
814 e -= 28;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000815 y = (Py_uhash_t)m; /* pull out integer part */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000816 m -= y;
817 x += y;
818 if (x >= _PyHASH_MODULUS)
819 x -= _PyHASH_MODULUS;
820 }
821
822 /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */
823 e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);
824 x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e);
825
826 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000827 if (x == (Py_uhash_t)-1)
828 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000829 return (Py_hash_t)x;
Fred Drake13634cf2000-06-29 19:17:04 +0000830}
831
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000832Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000833_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000834{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000835 Py_hash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 size_t y = (size_t)p;
837 /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
838 excessive hash collisions for dicts and sets */
839 y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000840 x = (Py_hash_t)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (x == -1)
842 x = -2;
843 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000844}
845
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000846Py_hash_t
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100847_Py_HashBytes(unsigned char *p, Py_ssize_t len)
848{
849 Py_uhash_t x;
850 Py_ssize_t i;
851
Georg Brandl2fb477c2012-02-21 00:33:36 +0100852 /*
853 We make the hash of the empty string be 0, rather than using
854 (prefix ^ suffix), since this slightly obfuscates the hash secret
855 */
Benjamin Peterson64ed5762012-04-09 15:04:39 -0400856#ifdef Py_DEBUG
Benjamin Petersond9a35912012-02-21 11:12:14 -0500857 assert(_Py_HashSecret_Initialized);
Benjamin Peterson64ed5762012-04-09 15:04:39 -0400858#endif
Georg Brandl2fb477c2012-02-21 00:33:36 +0100859 if (len == 0) {
860 return 0;
861 }
862 x = (Py_uhash_t) _Py_HashSecret.prefix;
863 x ^= (Py_uhash_t) *p << 7;
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100864 for (i = 0; i < len; i++)
Gregory P. Smithf5b62a92012-01-14 15:45:13 -0800865 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *p++;
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100866 x ^= (Py_uhash_t) len;
Georg Brandl2fb477c2012-02-21 00:33:36 +0100867 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100868 if (x == -1)
869 x = -2;
870 return x;
871}
872
873Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000874PyObject_HashNotImplemented(PyObject *v)
875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
877 Py_TYPE(v)->tp_name);
878 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000879}
Fred Drake13634cf2000-06-29 19:17:04 +0000880
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100881_Py_HashSecret_t _Py_HashSecret;
882
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000883Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000884PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyTypeObject *tp = Py_TYPE(v);
887 if (tp->tp_hash != NULL)
888 return (*tp->tp_hash)(v);
889 /* To keep to the general practice that inheriting
890 * solely from object in C code should work without
891 * an explicit call to PyType_Ready, we implicitly call
892 * PyType_Ready here and then check the tp_hash slot again
893 */
894 if (tp->tp_dict == NULL) {
895 if (PyType_Ready(tp) < 0)
896 return -1;
897 if (tp->tp_hash != NULL)
898 return (*tp->tp_hash)(v);
899 }
900 /* Otherwise, the object can't be hashed */
901 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000902}
903
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000904PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000905PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 if (Py_TYPE(v)->tp_getattr != NULL)
910 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
911 w = PyUnicode_InternFromString(name);
912 if (w == NULL)
913 return NULL;
914 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100915 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000917}
918
919int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000920PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyObject *res = PyObject_GetAttrString(v, name);
923 if (res != NULL) {
924 Py_DECREF(res);
925 return 1;
926 }
927 PyErr_Clear();
928 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000929}
930
931int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000932PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *s;
935 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 if (Py_TYPE(v)->tp_setattr != NULL)
938 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
939 s = PyUnicode_InternFromString(name);
940 if (s == NULL)
941 return -1;
942 res = PyObject_SetAttr(v, s, w);
943 Py_XDECREF(s);
944 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000945}
946
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500947int
948_PyObject_IsAbstract(PyObject *obj)
949{
950 int res;
951 PyObject* isabstract;
952 _Py_IDENTIFIER(__isabstractmethod__);
953
954 if (obj == NULL)
955 return 0;
956
957 isabstract = _PyObject_GetAttrId(obj, &PyId___isabstractmethod__);
958 if (isabstract == NULL) {
959 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
960 PyErr_Clear();
961 return 0;
962 }
963 return -1;
964 }
965 res = PyObject_IsTrue(isabstract);
966 Py_DECREF(isabstract);
967 return res;
968}
969
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000970PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200971_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
972{
973 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100974 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200975 if (!oname)
976 return NULL;
977 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200978 return result;
979}
980
981int
982_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
983{
984 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100985 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200986 if (!oname)
987 return -1;
988 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200989 return result;
990}
991
992int
993_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
994{
995 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100996 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200997 if (!oname)
998 return -1;
999 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001000 return result;
1001}
1002
1003PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001004PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (!PyUnicode_Check(name)) {
1009 PyErr_Format(PyExc_TypeError,
1010 "attribute name must be string, not '%.200s'",
1011 name->ob_type->tp_name);
1012 return NULL;
1013 }
1014 if (tp->tp_getattro != NULL)
1015 return (*tp->tp_getattro)(v, name);
1016 if (tp->tp_getattr != NULL) {
1017 char *name_str = _PyUnicode_AsString(name);
1018 if (name_str == NULL)
1019 return NULL;
1020 return (*tp->tp_getattr)(v, name_str);
1021 }
1022 PyErr_Format(PyExc_AttributeError,
1023 "'%.50s' object has no attribute '%U'",
1024 tp->tp_name, name);
1025 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001026}
1027
1028int
Fred Drake100814d2000-07-09 15:48:49 +00001029PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 PyObject *res = PyObject_GetAttr(v, name);
1032 if (res != NULL) {
1033 Py_DECREF(res);
1034 return 1;
1035 }
1036 PyErr_Clear();
1037 return 0;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001038}
1039
1040int
Fred Drake100814d2000-07-09 15:48:49 +00001041PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyTypeObject *tp = Py_TYPE(v);
1044 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 if (!PyUnicode_Check(name)) {
1047 PyErr_Format(PyExc_TypeError,
1048 "attribute name must be string, not '%.200s'",
1049 name->ob_type->tp_name);
1050 return -1;
1051 }
1052 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 PyUnicode_InternInPlace(&name);
1055 if (tp->tp_setattro != NULL) {
1056 err = (*tp->tp_setattro)(v, name, value);
1057 Py_DECREF(name);
1058 return err;
1059 }
1060 if (tp->tp_setattr != NULL) {
1061 char *name_str = _PyUnicode_AsString(name);
1062 if (name_str == NULL)
1063 return -1;
1064 err = (*tp->tp_setattr)(v, name_str, value);
1065 Py_DECREF(name);
1066 return err;
1067 }
1068 Py_DECREF(name);
1069 assert(name->ob_refcnt >= 1);
1070 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1071 PyErr_Format(PyExc_TypeError,
1072 "'%.100s' object has no attributes "
1073 "(%s .%U)",
1074 tp->tp_name,
1075 value==NULL ? "del" : "assign to",
1076 name);
1077 else
1078 PyErr_Format(PyExc_TypeError,
1079 "'%.100s' object has only read-only attributes "
1080 "(%s .%U)",
1081 tp->tp_name,
1082 value==NULL ? "del" : "assign to",
1083 name);
1084 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085}
1086
1087/* Helper to get a pointer to an object's __dict__ slot, if any */
1088
1089PyObject **
1090_PyObject_GetDictPtr(PyObject *obj)
1091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 Py_ssize_t dictoffset;
1093 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 dictoffset = tp->tp_dictoffset;
1096 if (dictoffset == 0)
1097 return NULL;
1098 if (dictoffset < 0) {
1099 Py_ssize_t tsize;
1100 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 tsize = ((PyVarObject *)obj)->ob_size;
1103 if (tsize < 0)
1104 tsize = -tsize;
1105 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 dictoffset += (long)size;
1108 assert(dictoffset > 0);
1109 assert(dictoffset % SIZEOF_VOID_P == 0);
1110 }
1111 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112}
1113
Tim Peters6d6c1a32001-08-02 04:15:00 +00001114PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001115PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 Py_INCREF(obj);
1118 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001119}
1120
Antoine Pitroua7013882012-04-05 00:04:20 +02001121/* Convenience function to get a builtin from its name */
1122PyObject *
1123_PyObject_GetBuiltin(const char *name)
1124{
Victor Stinner53e9ec42013-11-07 00:43:05 +01001125 PyObject *mod_name, *mod, *attr;
1126
1127 mod_name = _PyUnicode_FromId(&_PyId_builtins); /* borrowed */
1128 if (mod_name == NULL)
1129 return NULL;
1130 mod = PyImport_Import(mod_name);
Antoine Pitroua7013882012-04-05 00:04:20 +02001131 if (mod == NULL)
1132 return NULL;
1133 attr = PyObject_GetAttrString(mod, name);
1134 Py_DECREF(mod);
1135 return attr;
1136}
1137
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001138/* Helper used when the __next__ method is removed from a type:
1139 tp_iternext is never NULL and can be safely called without checking
1140 on every iteration.
1141 */
1142
1143PyObject *
1144_PyObject_NextNotImplemented(PyObject *self)
1145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 PyErr_Format(PyExc_TypeError,
1147 "'%.200s' object is not iterable",
1148 Py_TYPE(self)->tp_name);
1149 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001150}
1151
Michael W. Hudson1593f502004-09-14 17:09:47 +00001152/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1153
Raymond Hettinger01538262003-03-17 08:24:35 +00001154PyObject *
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001155_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 PyTypeObject *tp = Py_TYPE(obj);
1158 PyObject *descr = NULL;
1159 PyObject *res = NULL;
1160 descrgetfunc f;
1161 Py_ssize_t dictoffset;
1162 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (!PyUnicode_Check(name)){
1165 PyErr_Format(PyExc_TypeError,
1166 "attribute name must be string, not '%.200s'",
1167 name->ob_type->tp_name);
1168 return NULL;
1169 }
1170 else
1171 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (tp->tp_dict == NULL) {
1174 if (PyType_Ready(tp) < 0)
1175 goto done;
1176 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 descr = _PyType_Lookup(tp, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 Py_XINCREF(descr);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 f = NULL;
1182 if (descr != NULL) {
1183 f = descr->ob_type->tp_descr_get;
1184 if (f != NULL && PyDescr_IsData(descr)) {
1185 res = f(descr, obj, (PyObject *)obj->ob_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 goto done;
1187 }
1188 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001190 if (dict == NULL) {
1191 /* Inline _PyObject_GetDictPtr */
1192 dictoffset = tp->tp_dictoffset;
1193 if (dictoffset != 0) {
1194 if (dictoffset < 0) {
1195 Py_ssize_t tsize;
1196 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001197
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001198 tsize = ((PyVarObject *)obj)->ob_size;
1199 if (tsize < 0)
1200 tsize = -tsize;
1201 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001202
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001203 dictoffset += (long)size;
1204 assert(dictoffset > 0);
1205 assert(dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001207 dictptr = (PyObject **) ((char *)obj + dictoffset);
1208 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 }
1210 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001211 if (dict != NULL) {
1212 Py_INCREF(dict);
1213 res = PyDict_GetItem(dict, name);
1214 if (res != NULL) {
1215 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001216 Py_DECREF(dict);
1217 goto done;
1218 }
1219 Py_DECREF(dict);
1220 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (f != NULL) {
1223 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 goto done;
1225 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (descr != NULL) {
1228 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001229 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 goto done;
1231 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 PyErr_Format(PyExc_AttributeError,
1234 "'%.50s' object has no attribute '%U'",
1235 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001236 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001237 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 Py_DECREF(name);
1239 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240}
1241
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001242PyObject *
1243PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1244{
1245 return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1246}
1247
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001249_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1250 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 PyTypeObject *tp = Py_TYPE(obj);
1253 PyObject *descr;
1254 descrsetfunc f;
1255 PyObject **dictptr;
1256 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (!PyUnicode_Check(name)){
1259 PyErr_Format(PyExc_TypeError,
1260 "attribute name must be string, not '%.200s'",
1261 name->ob_type->tp_name);
1262 return -1;
1263 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001264
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001265 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1266 return -1;
1267
1268 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001271 Py_XINCREF(descr);
1272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 f = NULL;
1274 if (descr != NULL) {
1275 f = descr->ob_type->tp_descr_set;
1276 if (f != NULL && PyDescr_IsData(descr)) {
1277 res = f(descr, obj, value);
1278 goto done;
1279 }
1280 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001282 if (dict == NULL) {
1283 dictptr = _PyObject_GetDictPtr(obj);
1284 if (dictptr != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001285 res = _PyObjectDict_SetItem(Py_TYPE(obj), dictptr, name, value);
1286 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1287 PyErr_SetObject(PyExc_AttributeError, name);
1288 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001290 }
1291 if (dict != NULL) {
1292 Py_INCREF(dict);
1293 if (value == NULL)
1294 res = PyDict_DelItem(dict, name);
1295 else
1296 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001297 Py_DECREF(dict);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001298 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1299 PyErr_SetObject(PyExc_AttributeError, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001300 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (f != NULL) {
1304 res = f(descr, obj, value);
1305 goto done;
1306 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (descr == NULL) {
1309 PyErr_Format(PyExc_AttributeError,
1310 "'%.100s' object has no attribute '%U'",
1311 tp->tp_name, name);
1312 goto done;
1313 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 PyErr_Format(PyExc_AttributeError,
1316 "'%.50s' object attribute '%U' is read-only",
1317 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001318 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001319 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 Py_DECREF(name);
1321 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001322}
1323
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001324int
1325PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1326{
1327 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1328}
1329
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001330int
1331PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1332{
1333 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
1334 if (dictptr == NULL) {
1335 PyErr_SetString(PyExc_AttributeError,
1336 "This object has no __dict__");
1337 return -1;
1338 }
1339 if (value == NULL) {
1340 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1341 return -1;
1342 }
1343 if (!PyDict_Check(value)) {
1344 PyErr_Format(PyExc_TypeError,
1345 "__dict__ must be set to a dictionary, "
1346 "not a '%.200s'", Py_TYPE(value)->tp_name);
1347 return -1;
1348 }
1349 dict = *dictptr;
1350 Py_XINCREF(value);
1351 *dictptr = value;
1352 Py_XDECREF(dict);
1353 return 0;
1354}
1355
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001356
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001357/* Test a value used as condition, e.g., in a for or if statement.
1358 Return -1 if an error occurred */
1359
1360int
Fred Drake100814d2000-07-09 15:48:49 +00001361PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 Py_ssize_t res;
1364 if (v == Py_True)
1365 return 1;
1366 if (v == Py_False)
1367 return 0;
1368 if (v == Py_None)
1369 return 0;
1370 else if (v->ob_type->tp_as_number != NULL &&
1371 v->ob_type->tp_as_number->nb_bool != NULL)
1372 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1373 else if (v->ob_type->tp_as_mapping != NULL &&
1374 v->ob_type->tp_as_mapping->mp_length != NULL)
1375 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1376 else if (v->ob_type->tp_as_sequence != NULL &&
1377 v->ob_type->tp_as_sequence->sq_length != NULL)
1378 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1379 else
1380 return 1;
1381 /* if it is negative, it should be either -1 or -2 */
1382 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001383}
1384
Tim Peters803526b2002-07-07 05:13:56 +00001385/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001386 Return -1 if an error occurred */
1387
1388int
Fred Drake100814d2000-07-09 15:48:49 +00001389PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 int res;
1392 res = PyObject_IsTrue(v);
1393 if (res < 0)
1394 return res;
1395 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001396}
1397
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001398/* Test whether an object can be called */
1399
1400int
Fred Drake100814d2000-07-09 15:48:49 +00001401PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 if (x == NULL)
1404 return 0;
1405 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001406}
1407
Tim Peters7eea37e2001-09-04 22:08:56 +00001408
Georg Brandle32b4222007-03-10 22:13:27 +00001409/* Helper for PyObject_Dir without arguments: returns the local scope. */
1410static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001411_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001414 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001415
Victor Stinner41bb43a2013-10-29 01:19:37 +01001416 locals = PyEval_GetLocals();
1417 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 names = PyMapping_Keys(locals);
1421 if (!names)
1422 return NULL;
1423 if (!PyList_Check(names)) {
1424 PyErr_Format(PyExc_TypeError,
1425 "dir(): expected keys() of locals to be a list, "
1426 "not '%.200s'", Py_TYPE(names)->tp_name);
1427 Py_DECREF(names);
1428 return NULL;
1429 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001430 if (PyList_Sort(names)) {
1431 Py_DECREF(names);
1432 return NULL;
1433 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 /* the locals don't need to be DECREF'd */
1435 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001436}
1437
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001438/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001439static PyObject *
1440_dir_object(PyObject *obj)
1441{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001442 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001443 _Py_IDENTIFIER(__dir__);
1444 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 assert(obj);
1447 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001448 if (!PyErr_Occurred())
1449 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1450 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001452 /* use __dir__ */
1453 result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
1454 Py_DECREF(dirfunc);
1455 if (result == NULL)
1456 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001457 /* return sorted(result) */
1458 sorted = PySequence_List(result);
1459 Py_DECREF(result);
1460 if (sorted == NULL)
1461 return NULL;
1462 if (PyList_Sort(sorted)) {
1463 Py_DECREF(sorted);
1464 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001466 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001467}
1468
1469/* Implementation of dir() -- if obj is NULL, returns the names in the current
1470 (local) scope. Otherwise, performs introspection of the object: returns a
1471 sorted list of attribute names (supposedly) accessible from the object
1472*/
1473PyObject *
1474PyObject_Dir(PyObject *obj)
1475{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001476 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001477}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001478
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001479/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001480None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001481There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001482so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001483*/
1484
Guido van Rossum0c182a11992-03-27 17:26:13 +00001485/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001486static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001487none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001490}
1491
Barry Warsaw9bf16442001-01-23 16:24:35 +00001492/* ARGUSED */
1493static void
Tim Peters803526b2002-07-07 05:13:56 +00001494none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 /* This should never get called, but we also don't want to SEGV if
1497 * we accidentally decref None out of existence.
1498 */
1499 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001500}
1501
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001502static PyObject *
1503none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1504{
1505 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1506 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1507 return NULL;
1508 }
1509 Py_RETURN_NONE;
1510}
1511
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001512static int
1513none_bool(PyObject *v)
1514{
1515 return 0;
1516}
1517
1518static PyNumberMethods none_as_number = {
1519 0, /* nb_add */
1520 0, /* nb_subtract */
1521 0, /* nb_multiply */
1522 0, /* nb_remainder */
1523 0, /* nb_divmod */
1524 0, /* nb_power */
1525 0, /* nb_negative */
1526 0, /* nb_positive */
1527 0, /* nb_absolute */
1528 (inquiry)none_bool, /* nb_bool */
1529 0, /* nb_invert */
1530 0, /* nb_lshift */
1531 0, /* nb_rshift */
1532 0, /* nb_and */
1533 0, /* nb_xor */
1534 0, /* nb_or */
1535 0, /* nb_int */
1536 0, /* nb_reserved */
1537 0, /* nb_float */
1538 0, /* nb_inplace_add */
1539 0, /* nb_inplace_subtract */
1540 0, /* nb_inplace_multiply */
1541 0, /* nb_inplace_remainder */
1542 0, /* nb_inplace_power */
1543 0, /* nb_inplace_lshift */
1544 0, /* nb_inplace_rshift */
1545 0, /* nb_inplace_and */
1546 0, /* nb_inplace_xor */
1547 0, /* nb_inplace_or */
1548 0, /* nb_floor_divide */
1549 0, /* nb_true_divide */
1550 0, /* nb_inplace_floor_divide */
1551 0, /* nb_inplace_true_divide */
1552 0, /* nb_index */
1553};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001554
Guido van Rossumba21a492001-08-16 08:17:26 +00001555static PyTypeObject PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1557 "NoneType",
1558 0,
1559 0,
1560 none_dealloc, /*tp_dealloc*/ /*never called*/
1561 0, /*tp_print*/
1562 0, /*tp_getattr*/
1563 0, /*tp_setattr*/
1564 0, /*tp_reserved*/
1565 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001566 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 0, /*tp_as_sequence*/
1568 0, /*tp_as_mapping*/
1569 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001570 0, /*tp_call */
1571 0, /*tp_str */
1572 0, /*tp_getattro */
1573 0, /*tp_setattro */
1574 0, /*tp_as_buffer */
1575 Py_TPFLAGS_DEFAULT, /*tp_flags */
1576 0, /*tp_doc */
1577 0, /*tp_traverse */
1578 0, /*tp_clear */
1579 0, /*tp_richcompare */
1580 0, /*tp_weaklistoffset */
1581 0, /*tp_iter */
1582 0, /*tp_iternext */
1583 0, /*tp_methods */
1584 0, /*tp_members */
1585 0, /*tp_getset */
1586 0, /*tp_base */
1587 0, /*tp_dict */
1588 0, /*tp_descr_get */
1589 0, /*tp_descr_set */
1590 0, /*tp_dictoffset */
1591 0, /*tp_init */
1592 0, /*tp_alloc */
1593 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001594};
1595
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001596PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001597 _PyObject_EXTRA_INIT
1598 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001599};
1600
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001601/* NotImplemented is an object that can be used to signal that an
1602 operation is not implemented for the given type combination. */
1603
1604static PyObject *
1605NotImplemented_repr(PyObject *op)
1606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001608}
1609
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001610static PyObject *
1611notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1612{
1613 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1614 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1615 return NULL;
1616 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001617 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001618}
1619
Armin Ronacher226b1db2012-10-06 14:28:58 +02001620static void
1621notimplemented_dealloc(PyObject* ignore)
1622{
1623 /* This should never get called, but we also don't want to SEGV if
1624 * we accidentally decref NotImplemented out of existence.
1625 */
1626 Py_FatalError("deallocating NotImplemented");
1627}
1628
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001629static PyTypeObject PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1631 "NotImplementedType",
1632 0,
1633 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001634 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 0, /*tp_print*/
1636 0, /*tp_getattr*/
1637 0, /*tp_setattr*/
1638 0, /*tp_reserved*/
1639 NotImplemented_repr, /*tp_repr*/
1640 0, /*tp_as_number*/
1641 0, /*tp_as_sequence*/
1642 0, /*tp_as_mapping*/
1643 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001644 0, /*tp_call */
1645 0, /*tp_str */
1646 0, /*tp_getattro */
1647 0, /*tp_setattro */
1648 0, /*tp_as_buffer */
1649 Py_TPFLAGS_DEFAULT, /*tp_flags */
1650 0, /*tp_doc */
1651 0, /*tp_traverse */
1652 0, /*tp_clear */
1653 0, /*tp_richcompare */
1654 0, /*tp_weaklistoffset */
1655 0, /*tp_iter */
1656 0, /*tp_iternext */
1657 0, /*tp_methods */
1658 0, /*tp_members */
1659 0, /*tp_getset */
1660 0, /*tp_base */
1661 0, /*tp_dict */
1662 0, /*tp_descr_get */
1663 0, /*tp_descr_set */
1664 0, /*tp_dictoffset */
1665 0, /*tp_init */
1666 0, /*tp_alloc */
1667 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001668};
1669
1670PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 _PyObject_EXTRA_INIT
1672 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001673};
1674
Guido van Rossumba21a492001-08-16 08:17:26 +00001675void
1676_Py_ReadyTypes(void)
1677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (PyType_Ready(&PyType_Type) < 0)
1679 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1682 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1685 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1688 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (PyType_Ready(&PyBool_Type) < 0)
1691 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (PyType_Ready(&PyByteArray_Type) < 0)
1694 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (PyType_Ready(&PyBytes_Type) < 0)
1697 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 if (PyType_Ready(&PyList_Type) < 0)
1700 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (PyType_Ready(&PyNone_Type) < 0)
1703 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1706 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (PyType_Ready(&PyTraceBack_Type) < 0)
1709 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (PyType_Ready(&PySuper_Type) < 0)
1712 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (PyType_Ready(&PyBaseObject_Type) < 0)
1715 Py_FatalError("Can't initialize object type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 if (PyType_Ready(&PyRange_Type) < 0)
1718 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (PyType_Ready(&PyDict_Type) < 0)
1721 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (PyType_Ready(&PySet_Type) < 0)
1724 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 if (PyType_Ready(&PyUnicode_Type) < 0)
1727 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (PyType_Ready(&PySlice_Type) < 0)
1730 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1733 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (PyType_Ready(&PyComplex_Type) < 0)
1736 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 if (PyType_Ready(&PyFloat_Type) < 0)
1739 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (PyType_Ready(&PyLong_Type) < 0)
1742 Py_FatalError("Can't initialize int type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1745 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 if (PyType_Ready(&PyProperty_Type) < 0)
1748 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001749
Stefan Krah9a2d99e2012-02-25 12:24:21 +01001750 if (PyType_Ready(&_PyManagedBuffer_Type) < 0)
1751 Py_FatalError("Can't initialize managed buffer type");
1752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 if (PyType_Ready(&PyMemoryView_Type) < 0)
1754 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (PyType_Ready(&PyTuple_Type) < 0)
1757 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (PyType_Ready(&PyEnum_Type) < 0)
1760 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (PyType_Ready(&PyReversed_Type) < 0)
1763 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1766 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (PyType_Ready(&PyCode_Type) < 0)
1769 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (PyType_Ready(&PyFrame_Type) < 0)
1772 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (PyType_Ready(&PyCFunction_Type) < 0)
1775 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (PyType_Ready(&PyMethod_Type) < 0)
1778 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (PyType_Ready(&PyFunction_Type) < 0)
1781 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 if (PyType_Ready(&PyDictProxy_Type) < 0)
1784 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (PyType_Ready(&PyGen_Type) < 0)
1787 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1790 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1793 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001794
Benjamin Petersoneff61f62011-09-01 16:32:31 -04001795 if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1796 Py_FatalError("Can't initialize method wrapper type");
1797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 if (PyType_Ready(&PyEllipsis_Type) < 0)
1799 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1802 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001803
Barry Warsaw409da152012-06-03 16:18:47 -04001804 if (PyType_Ready(&_PyNamespace_Type) < 0)
1805 Py_FatalError("Can't initialize namespace type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -04001806
Benjamin Petersonc4311282012-10-30 23:21:10 -04001807 if (PyType_Ready(&PyCapsule_Type) < 0)
1808 Py_FatalError("Can't initialize capsule type");
1809
1810 if (PyType_Ready(&PyLongRangeIter_Type) < 0)
1811 Py_FatalError("Can't initialize long range iterator type");
1812
1813 if (PyType_Ready(&PyCell_Type) < 0)
1814 Py_FatalError("Can't initialize cell type");
1815
1816 if (PyType_Ready(&PyInstanceMethod_Type) < 0)
1817 Py_FatalError("Can't initialize instance method type");
1818
1819 if (PyType_Ready(&PyClassMethodDescr_Type) < 0)
1820 Py_FatalError("Can't initialize class method descr type");
1821
1822 if (PyType_Ready(&PyMethodDescr_Type) < 0)
1823 Py_FatalError("Can't initialize method descr type");
1824
1825 if (PyType_Ready(&PyCallIter_Type) < 0)
1826 Py_FatalError("Can't initialize call iter type");
1827
1828 if (PyType_Ready(&PySeqIter_Type) < 0)
1829 Py_FatalError("Can't initialize sequence iterator type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001830}
1831
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001832
Guido van Rossum84a90321996-05-22 16:34:47 +00001833#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001834
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001835void
Fred Drake100814d2000-07-09 15:48:49 +00001836_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 _Py_INC_REFTOTAL;
1839 op->ob_refcnt = 1;
1840 _Py_AddToAllObjects(op, 1);
1841 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001842}
1843
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001844void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001845_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001847#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001848 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001849#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (op->ob_refcnt < 0)
1851 Py_FatalError("UNREF negative refcnt");
1852 if (op == &refchain ||
1853 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1854 fprintf(stderr, "* ob\n");
1855 _PyObject_Dump(op);
1856 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1857 _PyObject_Dump(op->_ob_prev->_ob_next);
1858 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1859 _PyObject_Dump(op->_ob_next->_ob_prev);
1860 Py_FatalError("UNREF invalid object");
1861 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001862#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1864 if (p == op)
1865 break;
1866 }
1867 if (p == &refchain) /* Not found */
1868 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001869#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 op->_ob_next->_ob_prev = op->_ob_prev;
1871 op->_ob_prev->_ob_next = op->_ob_next;
1872 op->_ob_next = op->_ob_prev = NULL;
1873 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001874}
1875
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001876void
Fred Drake100814d2000-07-09 15:48:49 +00001877_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1880 _Py_ForgetReference(op);
1881 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001882}
1883
Tim Peters269b2a62003-04-17 19:52:29 +00001884/* Print all live objects. Because PyObject_Print is called, the
1885 * interpreter must be in a healthy state.
1886 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001887void
Fred Drake100814d2000-07-09 15:48:49 +00001888_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 PyObject *op;
1891 fprintf(fp, "Remaining objects:\n");
1892 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1893 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1894 if (PyObject_Print(op, fp, 0) != 0)
1895 PyErr_Clear();
1896 putc('\n', fp);
1897 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001898}
1899
Tim Peters269b2a62003-04-17 19:52:29 +00001900/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1901 * doesn't make any calls to the Python C API, so is always safe to call.
1902 */
1903void
1904_Py_PrintReferenceAddresses(FILE *fp)
1905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 PyObject *op;
1907 fprintf(fp, "Remaining object addresses:\n");
1908 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1909 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1910 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001911}
1912
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001913PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001914_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 int i, n;
1917 PyObject *t = NULL;
1918 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1921 return NULL;
1922 op = refchain._ob_next;
1923 res = PyList_New(0);
1924 if (res == NULL)
1925 return NULL;
1926 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1927 while (op == self || op == args || op == res || op == t ||
1928 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1929 op = op->_ob_next;
1930 if (op == &refchain)
1931 return res;
1932 }
1933 if (PyList_Append(res, op) < 0) {
1934 Py_DECREF(res);
1935 return NULL;
1936 }
1937 op = op->_ob_next;
1938 }
1939 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001940}
1941
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001942#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001943
Benjamin Petersonb173f782009-05-05 22:31:58 +00001944/* Hack to force loading of pycapsule.o */
1945PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
1946
1947
Guido van Rossum84a90321996-05-22 16:34:47 +00001948/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001949Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001950
1951
David Malcolm49526f42012-06-22 14:55:41 -04001952void
1953_PyObject_DebugTypeStats(FILE *out)
1954{
1955 _PyCFunction_DebugMallocStats(out);
1956 _PyDict_DebugMallocStats(out);
1957 _PyFloat_DebugMallocStats(out);
1958 _PyFrame_DebugMallocStats(out);
1959 _PyList_DebugMallocStats(out);
1960 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001961 _PyTuple_DebugMallocStats(out);
1962}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001963
Guido van Rossum86610361998-04-10 22:32:46 +00001964/* These methods are used to control infinite recursion in repr, str, print,
1965 etc. Container objects that may recursively contain themselves,
1966 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1967 Py_ReprLeave() to avoid infinite recursion.
1968
1969 Py_ReprEnter() returns 0 the first time it is called for a particular
1970 object and 1 every time thereafter. It returns -1 if an exception
1971 occurred. Py_ReprLeave() has no return value.
1972
1973 See dictobject.c and listobject.c for examples of use.
1974*/
1975
Victor Stinner7a07e452013-11-06 18:57:29 +01001976_Py_IDENTIFIER(Py_Repr);
Guido van Rossum86610361998-04-10 22:32:46 +00001977
1978int
Fred Drake100814d2000-07-09 15:48:49 +00001979Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyObject *dict;
1982 PyObject *list;
1983 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 dict = PyThreadState_GetDict();
1986 if (dict == NULL)
1987 return 0;
Victor Stinner7a07e452013-11-06 18:57:29 +01001988 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 if (list == NULL) {
1990 list = PyList_New(0);
1991 if (list == NULL)
1992 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01001993 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 return -1;
1995 Py_DECREF(list);
1996 }
1997 i = PyList_GET_SIZE(list);
1998 while (--i >= 0) {
1999 if (PyList_GET_ITEM(list, i) == obj)
2000 return 1;
2001 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002002 if (PyList_Append(list, obj) < 0)
2003 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002005}
2006
2007void
Fred Drake100814d2000-07-09 15:48:49 +00002008Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 PyObject *dict;
2011 PyObject *list;
2012 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002013 PyObject *error_type, *error_value, *error_traceback;
2014
2015 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 dict = PyThreadState_GetDict();
2018 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002019 goto finally;
2020
Victor Stinner7a07e452013-11-06 18:57:29 +01002021 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002023 goto finally;
2024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 i = PyList_GET_SIZE(list);
2026 /* Count backwards because we always expect obj to be list[-1] */
2027 while (--i >= 0) {
2028 if (PyList_GET_ITEM(list, i) == obj) {
2029 PyList_SetSlice(list, i, i + 1, NULL);
2030 break;
2031 }
2032 }
Victor Stinner1b634932013-07-16 22:24:44 +02002033
2034finally:
2035 /* ignore exceptions because there is no way to report them. */
2036 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002037}
Guido van Rossumd724b232000-03-13 16:01:29 +00002038
Tim Peters803526b2002-07-07 05:13:56 +00002039/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002040
Tim Peters803526b2002-07-07 05:13:56 +00002041/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002042int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002043
Tim Peters803526b2002-07-07 05:13:56 +00002044/* List of objects that still need to be cleaned up, singly linked via their
2045 * gc headers' gc_prev pointers.
2046 */
2047PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002048
Tim Peters803526b2002-07-07 05:13:56 +00002049/* Add op to the _PyTrash_delete_later list. Called when the current
2050 * call-stack depth gets large. op must be a currently untracked gc'ed
2051 * object, with refcount 0. Py_DECREF must already have been called on it.
2052 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002053void
Fred Drake100814d2000-07-09 15:48:49 +00002054_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 assert(PyObject_IS_GC(op));
Antoine Pitrou796564c2013-07-30 19:59:21 +02002057 assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 assert(op->ob_refcnt == 0);
2059 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2060 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002061}
2062
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002063/* The equivalent API, using per-thread state recursion info */
2064void
2065_PyTrash_thread_deposit_object(PyObject *op)
2066{
2067 PyThreadState *tstate = PyThreadState_GET();
2068 assert(PyObject_IS_GC(op));
Antoine Pitrou796564c2013-07-30 19:59:21 +02002069 assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002070 assert(op->ob_refcnt == 0);
2071 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *) tstate->trash_delete_later;
2072 tstate->trash_delete_later = op;
2073}
2074
Tim Peters803526b2002-07-07 05:13:56 +00002075/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2076 * the call-stack unwinds again.
2077 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002078void
Fred Drake100814d2000-07-09 15:48:49 +00002079_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 while (_PyTrash_delete_later) {
2082 PyObject *op = _PyTrash_delete_later;
2083 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 _PyTrash_delete_later =
2086 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 /* Call the deallocator directly. This used to try to
2089 * fool Py_DECREF into calling it indirectly, but
2090 * Py_DECREF was already called on this object, and in
2091 * assorted non-release builds calling Py_DECREF again ends
2092 * up distorting allocation statistics.
2093 */
2094 assert(op->ob_refcnt == 0);
2095 ++_PyTrash_delete_nesting;
2096 (*dealloc)(op);
2097 --_PyTrash_delete_nesting;
2098 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002099}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002100
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002101/* The equivalent API, using per-thread state recursion info */
2102void
2103_PyTrash_thread_destroy_chain(void)
2104{
2105 PyThreadState *tstate = PyThreadState_GET();
2106 while (tstate->trash_delete_later) {
2107 PyObject *op = tstate->trash_delete_later;
2108 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2109
2110 tstate->trash_delete_later =
2111 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
2112
2113 /* Call the deallocator directly. This used to try to
2114 * fool Py_DECREF into calling it indirectly, but
2115 * Py_DECREF was already called on this object, and in
2116 * assorted non-release builds calling Py_DECREF again ends
2117 * up distorting allocation statistics.
2118 */
2119 assert(op->ob_refcnt == 0);
2120 ++tstate->trash_delete_nesting;
2121 (*dealloc)(op);
2122 --tstate->trash_delete_nesting;
2123 }
2124}
2125
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002126#ifndef Py_TRACE_REFS
2127/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
2128 Define this here, so we can undefine the macro. */
2129#undef _Py_Dealloc
2130PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
2131void
2132_Py_Dealloc(PyObject *op)
2133{
2134 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
2135 (*Py_TYPE(op)->tp_dealloc)(op);
2136}
2137#endif
2138
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002139#ifdef __cplusplus
2140}
2141#endif