blob: acc34af3499279b9f12567e7c9e0a15f9e329c91 [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
Victor Stinnerbd303c12013-11-07 23:07:29 +010011_Py_IDENTIFIER(Py_Repr);
12_Py_IDENTIFIER(__bytes__);
13_Py_IDENTIFIER(__dir__);
14_Py_IDENTIFIER(__isabstractmethod__);
15_Py_IDENTIFIER(builtins);
16
Tim Peters34592512002-07-11 06:23:50 +000017#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000018Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019
20Py_ssize_t
21_Py_GetRefTotal(void)
22{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000023 PyObject *o;
24 Py_ssize_t total = _Py_RefTotal;
25 /* ignore the references to the dummy object of the dicts and sets
26 because they are not reliable and not useful (now that the
27 hash table code is well-tested) */
28 o = _PyDict_Dummy();
29 if (o != NULL)
30 total -= o->ob_refcnt;
Antoine Pitrou9d952542013-08-24 21:07:07 +020031 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 if (o != NULL)
33 total -= o->ob_refcnt;
34 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000035}
36#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037
Guido van Rossum3f5da241990-12-20 15:06:42 +000038/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
39 These are used by the individual routines for object creation.
40 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000041
Tim Peters78be7992003-03-23 02:51:01 +000042#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000043/* Head of circular doubly-linked list of all objects. These are linked
44 * together via the _ob_prev and _ob_next members of a PyObject, which
45 * exist only in a Py_TRACE_REFS build.
46 */
Tim Peters78be7992003-03-23 02:51:01 +000047static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000048
Tim Peters7571a0f2003-03-23 17:52:28 +000049/* Insert op at the front of the list of all objects. If force is true,
50 * op is added even if _ob_prev and _ob_next are non-NULL already. If
51 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
52 * force should be true if and only if op points to freshly allocated,
53 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000054 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000055 * Note that objects are normally added to the list via _Py_NewReference,
56 * which is called by PyObject_Init. Not all objects are initialized that
57 * way, though; exceptions include statically allocated type objects, and
58 * statically allocated singletons (like Py_True and Py_None).
59 */
Tim Peters36eb4df2003-03-23 03:33:13 +000060void
Tim Peters7571a0f2003-03-23 17:52:28 +000061_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000062{
Tim Peters7571a0f2003-03-23 17:52:28 +000063#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 if (!force) {
65 /* If it's initialized memory, op must be in or out of
66 * the list unambiguously.
67 */
68 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
69 }
Tim Peters78be7992003-03-23 02:51:01 +000070#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 if (force || op->_ob_prev == NULL) {
72 op->_ob_next = refchain._ob_next;
73 op->_ob_prev = &refchain;
74 refchain._ob_next->_ob_prev = op;
75 refchain._ob_next = op;
76 }
Tim Peters7571a0f2003-03-23 17:52:28 +000077}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000079
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000080#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000081static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000082/* All types are added to type_list, at least when
83 they get one object created. That makes them
84 immortal, which unfortunately contributes to
85 garbage itself. If unlist_types_without_objects
86 is set, they will be removed from the type_list
87 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +000088static int unlist_types_without_objects;
89extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
90extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
91extern Py_ssize_t null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000092void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000093dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 for (tp = type_list; tp; tp = tp->tp_next)
98 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
99 "freed: %" PY_FORMAT_SIZE_T "d, "
100 "max in use: %" PY_FORMAT_SIZE_T "d\n",
101 tp->tp_name, tp->tp_allocs, tp->tp_frees,
102 tp->tp_maxalloc);
103 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
104 "empty: %" PY_FORMAT_SIZE_T "d\n",
105 fast_tuple_allocs, tuple_zero_allocs);
106 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
107 "neg: %" PY_FORMAT_SIZE_T "d\n",
108 quick_int_allocs, quick_neg_int_allocs);
109 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
110 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
111 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000112}
113
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000114PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000115get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 PyTypeObject *tp;
118 PyObject *result;
119 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 result = PyList_New(0);
122 if (result == NULL)
123 return NULL;
124 for (tp = type_list; tp; tp = tp->tp_next) {
125 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
126 tp->tp_frees, tp->tp_maxalloc);
127 if (v == NULL) {
128 Py_DECREF(result);
129 return NULL;
130 }
131 if (PyList_Append(result, v) < 0) {
132 Py_DECREF(v);
133 Py_DECREF(result);
134 return NULL;
135 }
136 Py_DECREF(v);
137 }
138 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000139}
140
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000141void
Fred Drake100814d2000-07-09 15:48:49 +0000142inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
145 /* first time; insert in linked list */
146 if (tp->tp_next != NULL) /* sanity check */
147 Py_FatalError("XXX inc_count sanity check");
148 if (type_list)
149 type_list->tp_prev = tp;
150 tp->tp_next = type_list;
151 /* Note that as of Python 2.2, heap-allocated type objects
152 * can go away, but this code requires that they stay alive
153 * until program exit. That's why we're careful with
154 * refcounts here. type_list gets a new reference to tp,
155 * while ownership of the reference type_list used to hold
156 * (if any) was transferred to tp->tp_next in the line above.
157 * tp is thus effectively immortal after this.
158 */
159 Py_INCREF(tp);
160 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000161#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 /* Also insert in the doubly-linked list of all objects,
163 * if not already there.
164 */
165 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000166#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 }
168 tp->tp_allocs++;
169 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
170 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000171}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000172
173void dec_count(PyTypeObject *tp)
174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 tp->tp_frees++;
176 if (unlist_types_without_objects &&
177 tp->tp_allocs == tp->tp_frees) {
178 /* unlink the type from type_list */
179 if (tp->tp_prev)
180 tp->tp_prev->tp_next = tp->tp_next;
181 else
182 type_list = tp->tp_next;
183 if (tp->tp_next)
184 tp->tp_next->tp_prev = tp->tp_prev;
185 tp->tp_next = tp->tp_prev = NULL;
186 Py_DECREF(tp);
187 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000188}
189
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000190#endif
191
Tim Peters7c321a82002-07-09 02:57:01 +0000192#ifdef Py_REF_DEBUG
193/* Log a fatal error; doesn't return. */
194void
195_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 char buf[300];
Tim Peters7c321a82002-07-09 02:57:01 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 PyOS_snprintf(buf, sizeof(buf),
200 "%s:%i object at %p has negative ref count "
201 "%" PY_FORMAT_SIZE_T "d",
202 fname, lineno, op, op->ob_refcnt);
203 Py_FatalError(buf);
Tim Peters7c321a82002-07-09 02:57:01 +0000204}
205
206#endif /* Py_REF_DEBUG */
207
Thomas Heller1328b522004-04-22 17:23:49 +0000208void
209Py_IncRef(PyObject *o)
210{
211 Py_XINCREF(o);
212}
213
214void
215Py_DecRef(PyObject *o)
216{
217 Py_XDECREF(o);
218}
219
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000220PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000221PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (op == NULL)
224 return PyErr_NoMemory();
225 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
226 Py_TYPE(op) = tp;
227 _Py_NewReference(op);
228 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229}
230
Guido van Rossumb18618d2000-05-03 23:44:39 +0000231PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000232PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (op == NULL)
235 return (PyVarObject *) PyErr_NoMemory();
236 /* Any changes should be reflected in PyObject_INIT_VAR */
237 op->ob_size = size;
238 Py_TYPE(op) = tp;
239 _Py_NewReference((PyObject *)op);
240 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000241}
242
243PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000244_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyObject *op;
247 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
248 if (op == NULL)
249 return PyErr_NoMemory();
250 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000251}
252
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000253PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000254_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 PyVarObject *op;
257 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
258 op = (PyVarObject *) PyObject_MALLOC(size);
259 if (op == NULL)
260 return (PyVarObject *)PyErr_NoMemory();
261 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000262}
263
Antoine Pitrou796564c2013-07-30 19:59:21 +0200264void
265PyObject_CallFinalizer(PyObject *self)
266{
267 PyTypeObject *tp = Py_TYPE(self);
268
269 /* The former could happen on heaptypes created from the C API, e.g.
270 PyType_FromSpec(). */
271 if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
272 tp->tp_finalize == NULL)
273 return;
274 /* tp_finalize should only be called once. */
275 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
276 return;
277
278 tp->tp_finalize(self);
279 if (PyType_IS_GC(tp))
280 _PyGC_SET_FINALIZED(self, 1);
281}
282
283int
284PyObject_CallFinalizerFromDealloc(PyObject *self)
285{
286 Py_ssize_t refcnt;
287
288 /* Temporarily resurrect the object. */
289 if (self->ob_refcnt != 0) {
290 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
291 "object with a non-zero refcount");
292 }
293 self->ob_refcnt = 1;
294
295 PyObject_CallFinalizer(self);
296
297 /* Undo the temporary resurrection; can't use DECREF here, it would
298 * cause a recursive call.
299 */
300 assert(self->ob_refcnt > 0);
301 if (--self->ob_refcnt == 0)
302 return 0; /* this is the normal path out */
303
304 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
305 * never happened.
306 */
307 refcnt = self->ob_refcnt;
308 _Py_NewReference(self);
309 self->ob_refcnt = refcnt;
310
311 if (PyType_IS_GC(Py_TYPE(self))) {
312 assert(_PyGC_REFS(self) != _PyGC_REFS_UNTRACKED);
313 }
314 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
315 * we need to undo that. */
316 _Py_DEC_REFTOTAL;
317 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
318 * chain, so no more to do there.
319 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
320 * _Py_NewReference bumped tp_allocs: both of those need to be
321 * undone.
322 */
323#ifdef COUNT_ALLOCS
324 --Py_TYPE(self)->tp_frees;
325 --Py_TYPE(self)->tp_allocs;
326#endif
327 return -1;
328}
329
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000330int
331PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (PyErr_CheckSignals())
335 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000336#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (PyOS_CheckStack()) {
338 PyErr_SetString(PyExc_MemoryError, "stack overflow");
339 return -1;
340 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000341#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 clearerr(fp); /* Clear any previous error condition */
343 if (op == NULL) {
344 Py_BEGIN_ALLOW_THREADS
345 fprintf(fp, "<nil>");
346 Py_END_ALLOW_THREADS
347 }
348 else {
349 if (op->ob_refcnt <= 0)
350 /* XXX(twouters) cast refcount to long until %zd is
351 universally available */
352 Py_BEGIN_ALLOW_THREADS
353 fprintf(fp, "<refcnt %ld at %p>",
354 (long)op->ob_refcnt, op);
355 Py_END_ALLOW_THREADS
356 else {
357 PyObject *s;
358 if (flags & Py_PRINT_RAW)
359 s = PyObject_Str(op);
360 else
361 s = PyObject_Repr(op);
362 if (s == NULL)
363 ret = -1;
364 else if (PyBytes_Check(s)) {
365 fwrite(PyBytes_AS_STRING(s), 1,
366 PyBytes_GET_SIZE(s), fp);
367 }
368 else if (PyUnicode_Check(s)) {
369 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200370 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (t == NULL)
372 ret = 0;
373 else {
374 fwrite(PyBytes_AS_STRING(t), 1,
375 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000376 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 }
378 }
379 else {
380 PyErr_Format(PyExc_TypeError,
381 "str() or repr() returned '%.100s'",
382 s->ob_type->tp_name);
383 ret = -1;
384 }
385 Py_XDECREF(s);
386 }
387 }
388 if (ret == 0) {
389 if (ferror(fp)) {
390 PyErr_SetFromErrno(PyExc_IOError);
391 clearerr(fp);
392 ret = -1;
393 }
394 }
395 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396}
397
Guido van Rossum38938152006-08-21 23:36:26 +0000398/* For debugging convenience. Set a breakpoint here and call it from your DLL */
399void
Thomas Woutersb2137042007-02-01 18:02:27 +0000400_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000401{
402}
403
Neal Norwitz1a997502003-01-13 20:13:12 +0000404
Barry Warsaw9bf16442001-01-23 16:24:35 +0000405/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000406void
407_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (op == NULL)
410 fprintf(stderr, "NULL\n");
411 else {
Georg Brandldfd73442009-04-05 11:47:34 +0000412#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 PyGILState_STATE gil;
Georg Brandldfd73442009-04-05 11:47:34 +0000414#endif
Victor Stinnere5132102013-08-26 13:49:06 +0200415 PyObject *error_type, *error_value, *error_traceback;
416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 fprintf(stderr, "object : ");
Georg Brandldfd73442009-04-05 11:47:34 +0000418#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 gil = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000420#endif
Victor Stinnere5132102013-08-26 13:49:06 +0200421
422 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 (void)PyObject_Print(op, stderr, 0);
Victor Stinnere5132102013-08-26 13:49:06 +0200424 PyErr_Restore(error_type, error_value, error_traceback);
425
Georg Brandldfd73442009-04-05 11:47:34 +0000426#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyGILState_Release(gil);
Georg Brandldfd73442009-04-05 11:47:34 +0000428#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* XXX(twouters) cast refcount to long until %zd is
430 universally available */
431 fprintf(stderr, "\n"
432 "type : %s\n"
433 "refcount: %ld\n"
434 "address : %p\n",
435 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
436 (long)op->ob_refcnt,
437 op);
438 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000439}
Barry Warsaw903138f2001-01-23 16:33:18 +0000440
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000442PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyObject *res;
445 if (PyErr_CheckSignals())
446 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000447#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (PyOS_CheckStack()) {
449 PyErr_SetString(PyExc_MemoryError, "stack overflow");
450 return NULL;
451 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000452#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (v == NULL)
454 return PyUnicode_FromString("<NULL>");
455 if (Py_TYPE(v)->tp_repr == NULL)
456 return PyUnicode_FromFormat("<%s object at %p>",
457 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200458
459#ifdef Py_DEBUG
460 /* PyObject_Repr() must not be called with an exception set,
461 because it may clear it (directly or indirectly) and so the
462 caller looses its exception */
463 assert(!PyErr_Occurred());
464#endif
465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 res = (*v->ob_type->tp_repr)(v);
Victor Stinner0a54cf12011-12-01 03:22:44 +0100467 if (res == NULL)
468 return NULL;
469 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 PyErr_Format(PyExc_TypeError,
471 "__repr__ returned non-string (type %.200s)",
472 res->ob_type->tp_name);
473 Py_DECREF(res);
474 return NULL;
475 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100476#ifndef Py_DEBUG
477 if (PyUnicode_READY(res) < 0)
478 return NULL;
479#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000481}
482
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000484PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyObject *res;
487 if (PyErr_CheckSignals())
488 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000489#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (PyOS_CheckStack()) {
491 PyErr_SetString(PyExc_MemoryError, "stack overflow");
492 return NULL;
493 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000494#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (v == NULL)
496 return PyUnicode_FromString("<NULL>");
497 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100498#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100499 if (PyUnicode_READY(v) < 0)
500 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100501#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 Py_INCREF(v);
503 return v;
504 }
505 if (Py_TYPE(v)->tp_str == NULL)
506 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000507
Victor Stinner33824f62013-08-26 14:05:19 +0200508#ifdef Py_DEBUG
509 /* PyObject_Str() must not be called with an exception set,
510 because it may clear it (directly or indirectly) and so the
511 caller looses its exception */
512 assert(!PyErr_Occurred());
513#endif
514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 /* It is possible for a type to have a tp_str representation that loops
516 infinitely. */
517 if (Py_EnterRecursiveCall(" while getting the str of an object"))
518 return NULL;
519 res = (*Py_TYPE(v)->tp_str)(v);
520 Py_LeaveRecursiveCall();
521 if (res == NULL)
522 return NULL;
523 if (!PyUnicode_Check(res)) {
524 PyErr_Format(PyExc_TypeError,
525 "__str__ returned non-string (type %.200s)",
526 Py_TYPE(res)->tp_name);
527 Py_DECREF(res);
528 return NULL;
529 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100530#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100531 if (PyUnicode_READY(res) < 0)
532 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100533#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100534 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000536}
537
Georg Brandl559e5d72008-06-11 18:37:52 +0000538PyObject *
539PyObject_ASCII(PyObject *v)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 repr = PyObject_Repr(v);
544 if (repr == NULL)
545 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000546
Victor Stinneraf037572013-04-14 18:44:10 +0200547 if (PyUnicode_IS_ASCII(repr))
548 return repr;
549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200551 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 Py_DECREF(repr);
553 if (ascii == NULL)
554 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 res = PyUnicode_DecodeASCII(
557 PyBytes_AS_STRING(ascii),
558 PyBytes_GET_SIZE(ascii),
559 NULL);
560
561 Py_DECREF(ascii);
562 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000563}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000564
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000565PyObject *
566PyObject_Bytes(PyObject *v)
567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (v == NULL)
571 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (PyBytes_CheckExact(v)) {
574 Py_INCREF(v);
575 return v;
576 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000577
Benjamin Petersonce798522012-01-22 11:24:29 -0500578 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (func != NULL) {
580 result = PyObject_CallFunctionObjArgs(func, NULL);
581 Py_DECREF(func);
582 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000583 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000585 PyErr_Format(PyExc_TypeError,
586 "__bytes__ returned non-bytes (type %.200s)",
587 Py_TYPE(result)->tp_name);
588 Py_DECREF(result);
589 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 }
591 return result;
592 }
593 else if (PyErr_Occurred())
594 return NULL;
595 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000596}
597
Mark Dickinsonc008a172009-02-01 13:59:22 +0000598/* For Python 3.0.1 and later, the old three-way comparison has been
599 completely removed in favour of rich comparisons. PyObject_Compare() and
600 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000601 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000602 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000603
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000604 See (*) below for practical amendments.
605
Mark Dickinsonc008a172009-02-01 13:59:22 +0000606 tp_richcompare gets called with a first argument of the appropriate type
607 and a second object of an arbitrary type. We never do any kind of
608 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000609
Mark Dickinsonc008a172009-02-01 13:59:22 +0000610 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000611
612 NULL if an exception occurred
613 NotImplemented if the requested comparison is not implemented
614 any other false value if the requested comparison is false
615 any other true value if the requested comparison is true
616
617 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
618 NotImplemented.
619
620 (*) Practical amendments:
621
622 - If rich comparison returns NotImplemented, == and != are decided by
623 comparing the object pointer (i.e. falling back to the base object
624 implementation).
625
Guido van Rossuma4073002002-05-31 20:03:54 +0000626*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000627
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000628/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000629int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000630
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000631static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000632
633/* Perform a rich comparison, raising TypeError when the requested comparison
634 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000635static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000636do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 richcmpfunc f;
639 PyObject *res;
640 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (v->ob_type != w->ob_type &&
643 PyType_IsSubtype(w->ob_type, v->ob_type) &&
644 (f = w->ob_type->tp_richcompare) != NULL) {
645 checked_reverse_op = 1;
646 res = (*f)(w, v, _Py_SwappedOp[op]);
647 if (res != Py_NotImplemented)
648 return res;
649 Py_DECREF(res);
650 }
651 if ((f = v->ob_type->tp_richcompare) != NULL) {
652 res = (*f)(v, w, op);
653 if (res != Py_NotImplemented)
654 return res;
655 Py_DECREF(res);
656 }
657 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
658 res = (*f)(w, v, _Py_SwappedOp[op]);
659 if (res != Py_NotImplemented)
660 return res;
661 Py_DECREF(res);
662 }
663 /* If neither object implements it, provide a sensible default
664 for == and !=, but raise an exception for ordering. */
665 switch (op) {
666 case Py_EQ:
667 res = (v == w) ? Py_True : Py_False;
668 break;
669 case Py_NE:
670 res = (v != w) ? Py_True : Py_False;
671 break;
672 default:
673 /* XXX Special-case None so it doesn't show as NoneType() */
674 PyErr_Format(PyExc_TypeError,
675 "unorderable types: %.100s() %s %.100s()",
676 v->ob_type->tp_name,
677 opstrings[op],
678 w->ob_type->tp_name);
679 return NULL;
680 }
681 Py_INCREF(res);
682 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000683}
684
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000685/* Perform a rich comparison with object result. This wraps do_richcompare()
686 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000687
Guido van Rossume797ec12001-01-17 15:24:28 +0000688PyObject *
689PyObject_RichCompare(PyObject *v, PyObject *w, int op)
690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 assert(Py_LT <= op && op <= Py_GE);
694 if (v == NULL || w == NULL) {
695 if (!PyErr_Occurred())
696 PyErr_BadInternalCall();
697 return NULL;
698 }
699 if (Py_EnterRecursiveCall(" in comparison"))
700 return NULL;
701 res = do_richcompare(v, w, op);
702 Py_LeaveRecursiveCall();
703 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000704}
705
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000706/* Perform a rich comparison with integer result. This wraps
707 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000708int
709PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 PyObject *res;
712 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 /* Quick result when objects are the same.
715 Guarantees that identity implies equality. */
716 if (v == w) {
717 if (op == Py_EQ)
718 return 1;
719 else if (op == Py_NE)
720 return 0;
721 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 res = PyObject_RichCompare(v, w, op);
724 if (res == NULL)
725 return -1;
726 if (PyBool_Check(res))
727 ok = (res == Py_True);
728 else
729 ok = PyObject_IsTrue(res);
730 Py_DECREF(res);
731 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000732}
Fred Drake13634cf2000-06-29 19:17:04 +0000733
734/* Set of hash utility functions to help maintaining the invariant that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000736
737 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
738*/
739
Mark Dickinsondc787d22010-05-23 13:33:13 +0000740/* For numeric types, the hash of a number x is based on the reduction
741 of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that
742 hash(x) == hash(y) whenever x and y are numerically equal, even if
743 x and y have different types.
744
745 A quick summary of the hashing strategy:
746
747 (1) First define the 'reduction of x modulo P' for any rational
748 number x; this is a standard extension of the usual notion of
749 reduction modulo P for integers. If x == p/q (written in lowest
750 terms), the reduction is interpreted as the reduction of p times
751 the inverse of the reduction of q, all modulo P; if q is exactly
752 divisible by P then define the reduction to be infinity. So we've
753 got a well-defined map
754
755 reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }.
756
757 (2) Now for a rational number x, define hash(x) by:
758
759 reduce(x) if x >= 0
760 -reduce(-x) if x < 0
761
762 If the result of the reduction is infinity (this is impossible for
763 integers, floats and Decimals) then use the predefined hash value
764 _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead.
765 _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the
766 hashes of float and Decimal infinities and nans.
767
768 A selling point for the above strategy is that it makes it possible
769 to compute hashes of decimal and binary floating-point numbers
770 efficiently, even if the exponent of the binary or decimal number
771 is large. The key point is that
772
773 reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS)
774
775 provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a
776 binary or decimal float is never infinity, since the denominator is a power
777 of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have,
778 for nonnegative x,
779
780 reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS
781
782 reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS
783
784 and reduce(10**e) can be computed efficiently by the usual modular
785 exponentiation algorithm. For reduce(2**e) it's even better: since
786 P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication
787 by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits.
788
789 */
790
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000791Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000792_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000793{
Mark Dickinsondc787d22010-05-23 13:33:13 +0000794 int e, sign;
795 double m;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000796 Py_uhash_t x, y;
Tim Peters39dce292000-08-15 03:34:48 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 if (!Py_IS_FINITE(v)) {
799 if (Py_IS_INFINITY(v))
Mark Dickinsondc787d22010-05-23 13:33:13 +0000800 return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 else
Mark Dickinsondc787d22010-05-23 13:33:13 +0000802 return _PyHASH_NAN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000804
805 m = frexp(v, &e);
806
807 sign = 1;
808 if (m < 0) {
809 sign = -1;
810 m = -m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000812
813 /* process 28 bits at a time; this should work well both for binary
814 and hexadecimal floating point. */
815 x = 0;
816 while (m) {
817 x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28);
818 m *= 268435456.0; /* 2**28 */
819 e -= 28;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000820 y = (Py_uhash_t)m; /* pull out integer part */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000821 m -= y;
822 x += y;
823 if (x >= _PyHASH_MODULUS)
824 x -= _PyHASH_MODULUS;
825 }
826
827 /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */
828 e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);
829 x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e);
830
831 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000832 if (x == (Py_uhash_t)-1)
833 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000834 return (Py_hash_t)x;
Fred Drake13634cf2000-06-29 19:17:04 +0000835}
836
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000837Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000838_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000839{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000840 Py_hash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 size_t y = (size_t)p;
842 /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
843 excessive hash collisions for dicts and sets */
844 y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000845 x = (Py_hash_t)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 if (x == -1)
847 x = -2;
848 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000849}
850
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000851Py_hash_t
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100852_Py_HashBytes(unsigned char *p, Py_ssize_t len)
853{
854 Py_uhash_t x;
855 Py_ssize_t i;
856
Georg Brandl2fb477c2012-02-21 00:33:36 +0100857 /*
858 We make the hash of the empty string be 0, rather than using
859 (prefix ^ suffix), since this slightly obfuscates the hash secret
860 */
Benjamin Peterson64ed5762012-04-09 15:04:39 -0400861#ifdef Py_DEBUG
Benjamin Petersond9a35912012-02-21 11:12:14 -0500862 assert(_Py_HashSecret_Initialized);
Benjamin Peterson64ed5762012-04-09 15:04:39 -0400863#endif
Georg Brandl2fb477c2012-02-21 00:33:36 +0100864 if (len == 0) {
865 return 0;
866 }
867 x = (Py_uhash_t) _Py_HashSecret.prefix;
868 x ^= (Py_uhash_t) *p << 7;
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100869 for (i = 0; i < len; i++)
Gregory P. Smithf5b62a92012-01-14 15:45:13 -0800870 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *p++;
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100871 x ^= (Py_uhash_t) len;
Georg Brandl2fb477c2012-02-21 00:33:36 +0100872 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100873 if (x == -1)
874 x = -2;
875 return x;
876}
877
878Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000879PyObject_HashNotImplemented(PyObject *v)
880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
882 Py_TYPE(v)->tp_name);
883 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000884}
Fred Drake13634cf2000-06-29 19:17:04 +0000885
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100886_Py_HashSecret_t _Py_HashSecret;
887
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000888Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000889PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 PyTypeObject *tp = Py_TYPE(v);
892 if (tp->tp_hash != NULL)
893 return (*tp->tp_hash)(v);
894 /* To keep to the general practice that inheriting
895 * solely from object in C code should work without
896 * an explicit call to PyType_Ready, we implicitly call
897 * PyType_Ready here and then check the tp_hash slot again
898 */
899 if (tp->tp_dict == NULL) {
900 if (PyType_Ready(tp) < 0)
901 return -1;
902 if (tp->tp_hash != NULL)
903 return (*tp->tp_hash)(v);
904 }
905 /* Otherwise, the object can't be hashed */
906 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000907}
908
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000909PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000910PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (Py_TYPE(v)->tp_getattr != NULL)
915 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
916 w = PyUnicode_InternFromString(name);
917 if (w == NULL)
918 return NULL;
919 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100920 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000922}
923
924int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000925PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 PyObject *res = PyObject_GetAttrString(v, name);
928 if (res != NULL) {
929 Py_DECREF(res);
930 return 1;
931 }
932 PyErr_Clear();
933 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000934}
935
936int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000937PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyObject *s;
940 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (Py_TYPE(v)->tp_setattr != NULL)
943 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
944 s = PyUnicode_InternFromString(name);
945 if (s == NULL)
946 return -1;
947 res = PyObject_SetAttr(v, s, w);
948 Py_XDECREF(s);
949 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000950}
951
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500952int
953_PyObject_IsAbstract(PyObject *obj)
954{
955 int res;
956 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500957
958 if (obj == NULL)
959 return 0;
960
961 isabstract = _PyObject_GetAttrId(obj, &PyId___isabstractmethod__);
962 if (isabstract == NULL) {
963 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
964 PyErr_Clear();
965 return 0;
966 }
967 return -1;
968 }
969 res = PyObject_IsTrue(isabstract);
970 Py_DECREF(isabstract);
971 return res;
972}
973
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000974PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200975_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
976{
977 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100978 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200979 if (!oname)
980 return NULL;
981 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200982 return result;
983}
984
985int
986_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
987{
988 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100989 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200990 if (!oname)
991 return -1;
992 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200993 return result;
994}
995
996int
997_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
998{
999 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +01001000 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001001 if (!oname)
1002 return -1;
1003 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001004 return result;
1005}
1006
1007PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001008PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (!PyUnicode_Check(name)) {
1013 PyErr_Format(PyExc_TypeError,
1014 "attribute name must be string, not '%.200s'",
1015 name->ob_type->tp_name);
1016 return NULL;
1017 }
1018 if (tp->tp_getattro != NULL)
1019 return (*tp->tp_getattro)(v, name);
1020 if (tp->tp_getattr != NULL) {
1021 char *name_str = _PyUnicode_AsString(name);
1022 if (name_str == NULL)
1023 return NULL;
1024 return (*tp->tp_getattr)(v, name_str);
1025 }
1026 PyErr_Format(PyExc_AttributeError,
1027 "'%.50s' object has no attribute '%U'",
1028 tp->tp_name, name);
1029 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001030}
1031
1032int
Fred Drake100814d2000-07-09 15:48:49 +00001033PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyObject *res = PyObject_GetAttr(v, name);
1036 if (res != NULL) {
1037 Py_DECREF(res);
1038 return 1;
1039 }
1040 PyErr_Clear();
1041 return 0;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001042}
1043
1044int
Fred Drake100814d2000-07-09 15:48:49 +00001045PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyTypeObject *tp = Py_TYPE(v);
1048 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (!PyUnicode_Check(name)) {
1051 PyErr_Format(PyExc_TypeError,
1052 "attribute name must be string, not '%.200s'",
1053 name->ob_type->tp_name);
1054 return -1;
1055 }
1056 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 PyUnicode_InternInPlace(&name);
1059 if (tp->tp_setattro != NULL) {
1060 err = (*tp->tp_setattro)(v, name, value);
1061 Py_DECREF(name);
1062 return err;
1063 }
1064 if (tp->tp_setattr != NULL) {
1065 char *name_str = _PyUnicode_AsString(name);
1066 if (name_str == NULL)
1067 return -1;
1068 err = (*tp->tp_setattr)(v, name_str, value);
1069 Py_DECREF(name);
1070 return err;
1071 }
1072 Py_DECREF(name);
1073 assert(name->ob_refcnt >= 1);
1074 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1075 PyErr_Format(PyExc_TypeError,
1076 "'%.100s' object has no attributes "
1077 "(%s .%U)",
1078 tp->tp_name,
1079 value==NULL ? "del" : "assign to",
1080 name);
1081 else
1082 PyErr_Format(PyExc_TypeError,
1083 "'%.100s' object has only read-only attributes "
1084 "(%s .%U)",
1085 tp->tp_name,
1086 value==NULL ? "del" : "assign to",
1087 name);
1088 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001089}
1090
1091/* Helper to get a pointer to an object's __dict__ slot, if any */
1092
1093PyObject **
1094_PyObject_GetDictPtr(PyObject *obj)
1095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 Py_ssize_t dictoffset;
1097 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 dictoffset = tp->tp_dictoffset;
1100 if (dictoffset == 0)
1101 return NULL;
1102 if (dictoffset < 0) {
1103 Py_ssize_t tsize;
1104 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 tsize = ((PyVarObject *)obj)->ob_size;
1107 if (tsize < 0)
1108 tsize = -tsize;
1109 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 dictoffset += (long)size;
1112 assert(dictoffset > 0);
1113 assert(dictoffset % SIZEOF_VOID_P == 0);
1114 }
1115 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116}
1117
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001119PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 Py_INCREF(obj);
1122 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001123}
1124
Antoine Pitroua7013882012-04-05 00:04:20 +02001125/* Convenience function to get a builtin from its name */
1126PyObject *
1127_PyObject_GetBuiltin(const char *name)
1128{
Victor Stinner53e9ec42013-11-07 00:43:05 +01001129 PyObject *mod_name, *mod, *attr;
1130
Victor Stinnerbd303c12013-11-07 23:07:29 +01001131 mod_name = _PyUnicode_FromId(&PyId_builtins); /* borrowed */
Victor Stinner53e9ec42013-11-07 00:43:05 +01001132 if (mod_name == NULL)
1133 return NULL;
1134 mod = PyImport_Import(mod_name);
Antoine Pitroua7013882012-04-05 00:04:20 +02001135 if (mod == NULL)
1136 return NULL;
1137 attr = PyObject_GetAttrString(mod, name);
1138 Py_DECREF(mod);
1139 return attr;
1140}
1141
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001142/* Helper used when the __next__ method is removed from a type:
1143 tp_iternext is never NULL and can be safely called without checking
1144 on every iteration.
1145 */
1146
1147PyObject *
1148_PyObject_NextNotImplemented(PyObject *self)
1149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 PyErr_Format(PyExc_TypeError,
1151 "'%.200s' object is not iterable",
1152 Py_TYPE(self)->tp_name);
1153 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001154}
1155
Michael W. Hudson1593f502004-09-14 17:09:47 +00001156/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1157
Raymond Hettinger01538262003-03-17 08:24:35 +00001158PyObject *
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001159_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyTypeObject *tp = Py_TYPE(obj);
1162 PyObject *descr = NULL;
1163 PyObject *res = NULL;
1164 descrgetfunc f;
1165 Py_ssize_t dictoffset;
1166 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (!PyUnicode_Check(name)){
1169 PyErr_Format(PyExc_TypeError,
1170 "attribute name must be string, not '%.200s'",
1171 name->ob_type->tp_name);
1172 return NULL;
1173 }
1174 else
1175 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (tp->tp_dict == NULL) {
1178 if (PyType_Ready(tp) < 0)
1179 goto done;
1180 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 descr = _PyType_Lookup(tp, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_XINCREF(descr);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 f = NULL;
1186 if (descr != NULL) {
1187 f = descr->ob_type->tp_descr_get;
1188 if (f != NULL && PyDescr_IsData(descr)) {
1189 res = f(descr, obj, (PyObject *)obj->ob_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 goto done;
1191 }
1192 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001194 if (dict == NULL) {
1195 /* Inline _PyObject_GetDictPtr */
1196 dictoffset = tp->tp_dictoffset;
1197 if (dictoffset != 0) {
1198 if (dictoffset < 0) {
1199 Py_ssize_t tsize;
1200 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001201
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001202 tsize = ((PyVarObject *)obj)->ob_size;
1203 if (tsize < 0)
1204 tsize = -tsize;
1205 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001206
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001207 dictoffset += (long)size;
1208 assert(dictoffset > 0);
1209 assert(dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001211 dictptr = (PyObject **) ((char *)obj + dictoffset);
1212 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
1214 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001215 if (dict != NULL) {
1216 Py_INCREF(dict);
1217 res = PyDict_GetItem(dict, name);
1218 if (res != NULL) {
1219 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001220 Py_DECREF(dict);
1221 goto done;
1222 }
1223 Py_DECREF(dict);
1224 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 if (f != NULL) {
1227 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 goto done;
1229 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (descr != NULL) {
1232 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001233 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 goto done;
1235 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 PyErr_Format(PyExc_AttributeError,
1238 "'%.50s' object has no attribute '%U'",
1239 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001240 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001241 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 Py_DECREF(name);
1243 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244}
1245
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001246PyObject *
1247PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1248{
1249 return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1250}
1251
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001253_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1254 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 PyTypeObject *tp = Py_TYPE(obj);
1257 PyObject *descr;
1258 descrsetfunc f;
1259 PyObject **dictptr;
1260 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (!PyUnicode_Check(name)){
1263 PyErr_Format(PyExc_TypeError,
1264 "attribute name must be string, not '%.200s'",
1265 name->ob_type->tp_name);
1266 return -1;
1267 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001268
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001269 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1270 return -1;
1271
1272 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001275 Py_XINCREF(descr);
1276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 f = NULL;
1278 if (descr != NULL) {
1279 f = descr->ob_type->tp_descr_set;
1280 if (f != NULL && PyDescr_IsData(descr)) {
1281 res = f(descr, obj, value);
1282 goto done;
1283 }
1284 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001285
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001286 if (dict == NULL) {
1287 dictptr = _PyObject_GetDictPtr(obj);
1288 if (dictptr != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001289 res = _PyObjectDict_SetItem(Py_TYPE(obj), dictptr, name, value);
1290 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1291 PyErr_SetObject(PyExc_AttributeError, name);
1292 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001294 }
1295 if (dict != NULL) {
1296 Py_INCREF(dict);
1297 if (value == NULL)
1298 res = PyDict_DelItem(dict, name);
1299 else
1300 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001301 Py_DECREF(dict);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001302 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1303 PyErr_SetObject(PyExc_AttributeError, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001304 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (f != NULL) {
1308 res = f(descr, obj, value);
1309 goto done;
1310 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (descr == NULL) {
1313 PyErr_Format(PyExc_AttributeError,
1314 "'%.100s' object has no attribute '%U'",
1315 tp->tp_name, name);
1316 goto done;
1317 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 PyErr_Format(PyExc_AttributeError,
1320 "'%.50s' object attribute '%U' is read-only",
1321 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001322 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001323 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 Py_DECREF(name);
1325 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001326}
1327
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001328int
1329PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1330{
1331 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1332}
1333
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001334int
1335PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1336{
1337 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
1338 if (dictptr == NULL) {
1339 PyErr_SetString(PyExc_AttributeError,
1340 "This object has no __dict__");
1341 return -1;
1342 }
1343 if (value == NULL) {
1344 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1345 return -1;
1346 }
1347 if (!PyDict_Check(value)) {
1348 PyErr_Format(PyExc_TypeError,
1349 "__dict__ must be set to a dictionary, "
1350 "not a '%.200s'", Py_TYPE(value)->tp_name);
1351 return -1;
1352 }
1353 dict = *dictptr;
1354 Py_XINCREF(value);
1355 *dictptr = value;
1356 Py_XDECREF(dict);
1357 return 0;
1358}
1359
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001360
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001361/* Test a value used as condition, e.g., in a for or if statement.
1362 Return -1 if an error occurred */
1363
1364int
Fred Drake100814d2000-07-09 15:48:49 +00001365PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 Py_ssize_t res;
1368 if (v == Py_True)
1369 return 1;
1370 if (v == Py_False)
1371 return 0;
1372 if (v == Py_None)
1373 return 0;
1374 else if (v->ob_type->tp_as_number != NULL &&
1375 v->ob_type->tp_as_number->nb_bool != NULL)
1376 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1377 else if (v->ob_type->tp_as_mapping != NULL &&
1378 v->ob_type->tp_as_mapping->mp_length != NULL)
1379 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1380 else if (v->ob_type->tp_as_sequence != NULL &&
1381 v->ob_type->tp_as_sequence->sq_length != NULL)
1382 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1383 else
1384 return 1;
1385 /* if it is negative, it should be either -1 or -2 */
1386 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001387}
1388
Tim Peters803526b2002-07-07 05:13:56 +00001389/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001390 Return -1 if an error occurred */
1391
1392int
Fred Drake100814d2000-07-09 15:48:49 +00001393PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 int res;
1396 res = PyObject_IsTrue(v);
1397 if (res < 0)
1398 return res;
1399 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001400}
1401
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001402/* Test whether an object can be called */
1403
1404int
Fred Drake100814d2000-07-09 15:48:49 +00001405PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (x == NULL)
1408 return 0;
1409 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001410}
1411
Tim Peters7eea37e2001-09-04 22:08:56 +00001412
Georg Brandle32b4222007-03-10 22:13:27 +00001413/* Helper for PyObject_Dir without arguments: returns the local scope. */
1414static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001415_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001418 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001419
Victor Stinner41bb43a2013-10-29 01:19:37 +01001420 locals = PyEval_GetLocals();
1421 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 names = PyMapping_Keys(locals);
1425 if (!names)
1426 return NULL;
1427 if (!PyList_Check(names)) {
1428 PyErr_Format(PyExc_TypeError,
1429 "dir(): expected keys() of locals to be a list, "
1430 "not '%.200s'", Py_TYPE(names)->tp_name);
1431 Py_DECREF(names);
1432 return NULL;
1433 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001434 if (PyList_Sort(names)) {
1435 Py_DECREF(names);
1436 return NULL;
1437 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 /* the locals don't need to be DECREF'd */
1439 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001440}
1441
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001442/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001443static PyObject *
1444_dir_object(PyObject *obj)
1445{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001446 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001447 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 assert(obj);
1450 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001451 if (!PyErr_Occurred())
1452 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1453 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001455 /* use __dir__ */
1456 result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
1457 Py_DECREF(dirfunc);
1458 if (result == NULL)
1459 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001460 /* return sorted(result) */
1461 sorted = PySequence_List(result);
1462 Py_DECREF(result);
1463 if (sorted == NULL)
1464 return NULL;
1465 if (PyList_Sort(sorted)) {
1466 Py_DECREF(sorted);
1467 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001469 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001470}
1471
1472/* Implementation of dir() -- if obj is NULL, returns the names in the current
1473 (local) scope. Otherwise, performs introspection of the object: returns a
1474 sorted list of attribute names (supposedly) accessible from the object
1475*/
1476PyObject *
1477PyObject_Dir(PyObject *obj)
1478{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001479 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001480}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001481
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001482/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001483None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001484There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001485so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001486*/
1487
Guido van Rossum0c182a11992-03-27 17:26:13 +00001488/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001490none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001493}
1494
Barry Warsaw9bf16442001-01-23 16:24:35 +00001495/* ARGUSED */
1496static void
Tim Peters803526b2002-07-07 05:13:56 +00001497none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 /* This should never get called, but we also don't want to SEGV if
1500 * we accidentally decref None out of existence.
1501 */
1502 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001503}
1504
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001505static PyObject *
1506none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1507{
1508 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1509 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1510 return NULL;
1511 }
1512 Py_RETURN_NONE;
1513}
1514
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001515static int
1516none_bool(PyObject *v)
1517{
1518 return 0;
1519}
1520
1521static PyNumberMethods none_as_number = {
1522 0, /* nb_add */
1523 0, /* nb_subtract */
1524 0, /* nb_multiply */
1525 0, /* nb_remainder */
1526 0, /* nb_divmod */
1527 0, /* nb_power */
1528 0, /* nb_negative */
1529 0, /* nb_positive */
1530 0, /* nb_absolute */
1531 (inquiry)none_bool, /* nb_bool */
1532 0, /* nb_invert */
1533 0, /* nb_lshift */
1534 0, /* nb_rshift */
1535 0, /* nb_and */
1536 0, /* nb_xor */
1537 0, /* nb_or */
1538 0, /* nb_int */
1539 0, /* nb_reserved */
1540 0, /* nb_float */
1541 0, /* nb_inplace_add */
1542 0, /* nb_inplace_subtract */
1543 0, /* nb_inplace_multiply */
1544 0, /* nb_inplace_remainder */
1545 0, /* nb_inplace_power */
1546 0, /* nb_inplace_lshift */
1547 0, /* nb_inplace_rshift */
1548 0, /* nb_inplace_and */
1549 0, /* nb_inplace_xor */
1550 0, /* nb_inplace_or */
1551 0, /* nb_floor_divide */
1552 0, /* nb_true_divide */
1553 0, /* nb_inplace_floor_divide */
1554 0, /* nb_inplace_true_divide */
1555 0, /* nb_index */
1556};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001557
Guido van Rossumba21a492001-08-16 08:17:26 +00001558static PyTypeObject PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1560 "NoneType",
1561 0,
1562 0,
1563 none_dealloc, /*tp_dealloc*/ /*never called*/
1564 0, /*tp_print*/
1565 0, /*tp_getattr*/
1566 0, /*tp_setattr*/
1567 0, /*tp_reserved*/
1568 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001569 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 0, /*tp_as_sequence*/
1571 0, /*tp_as_mapping*/
1572 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001573 0, /*tp_call */
1574 0, /*tp_str */
1575 0, /*tp_getattro */
1576 0, /*tp_setattro */
1577 0, /*tp_as_buffer */
1578 Py_TPFLAGS_DEFAULT, /*tp_flags */
1579 0, /*tp_doc */
1580 0, /*tp_traverse */
1581 0, /*tp_clear */
1582 0, /*tp_richcompare */
1583 0, /*tp_weaklistoffset */
1584 0, /*tp_iter */
1585 0, /*tp_iternext */
1586 0, /*tp_methods */
1587 0, /*tp_members */
1588 0, /*tp_getset */
1589 0, /*tp_base */
1590 0, /*tp_dict */
1591 0, /*tp_descr_get */
1592 0, /*tp_descr_set */
1593 0, /*tp_dictoffset */
1594 0, /*tp_init */
1595 0, /*tp_alloc */
1596 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001597};
1598
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001599PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001600 _PyObject_EXTRA_INIT
1601 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001602};
1603
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001604/* NotImplemented is an object that can be used to signal that an
1605 operation is not implemented for the given type combination. */
1606
1607static PyObject *
1608NotImplemented_repr(PyObject *op)
1609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001611}
1612
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001613static PyObject *
1614notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1615{
1616 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1617 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1618 return NULL;
1619 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001620 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001621}
1622
Armin Ronacher226b1db2012-10-06 14:28:58 +02001623static void
1624notimplemented_dealloc(PyObject* ignore)
1625{
1626 /* This should never get called, but we also don't want to SEGV if
1627 * we accidentally decref NotImplemented out of existence.
1628 */
1629 Py_FatalError("deallocating NotImplemented");
1630}
1631
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001632static PyTypeObject PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1634 "NotImplementedType",
1635 0,
1636 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001637 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 0, /*tp_print*/
1639 0, /*tp_getattr*/
1640 0, /*tp_setattr*/
1641 0, /*tp_reserved*/
1642 NotImplemented_repr, /*tp_repr*/
1643 0, /*tp_as_number*/
1644 0, /*tp_as_sequence*/
1645 0, /*tp_as_mapping*/
1646 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001647 0, /*tp_call */
1648 0, /*tp_str */
1649 0, /*tp_getattro */
1650 0, /*tp_setattro */
1651 0, /*tp_as_buffer */
1652 Py_TPFLAGS_DEFAULT, /*tp_flags */
1653 0, /*tp_doc */
1654 0, /*tp_traverse */
1655 0, /*tp_clear */
1656 0, /*tp_richcompare */
1657 0, /*tp_weaklistoffset */
1658 0, /*tp_iter */
1659 0, /*tp_iternext */
1660 0, /*tp_methods */
1661 0, /*tp_members */
1662 0, /*tp_getset */
1663 0, /*tp_base */
1664 0, /*tp_dict */
1665 0, /*tp_descr_get */
1666 0, /*tp_descr_set */
1667 0, /*tp_dictoffset */
1668 0, /*tp_init */
1669 0, /*tp_alloc */
1670 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001671};
1672
1673PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 _PyObject_EXTRA_INIT
1675 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001676};
1677
Guido van Rossumba21a492001-08-16 08:17:26 +00001678void
1679_Py_ReadyTypes(void)
1680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (PyType_Ready(&PyType_Type) < 0)
1682 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1685 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1688 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1691 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (PyType_Ready(&PyBool_Type) < 0)
1694 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (PyType_Ready(&PyByteArray_Type) < 0)
1697 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 if (PyType_Ready(&PyBytes_Type) < 0)
1700 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (PyType_Ready(&PyList_Type) < 0)
1703 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 if (PyType_Ready(&PyNone_Type) < 0)
1706 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1709 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (PyType_Ready(&PyTraceBack_Type) < 0)
1712 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (PyType_Ready(&PySuper_Type) < 0)
1715 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 if (PyType_Ready(&PyBaseObject_Type) < 0)
1718 Py_FatalError("Can't initialize object type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (PyType_Ready(&PyRange_Type) < 0)
1721 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (PyType_Ready(&PyDict_Type) < 0)
1724 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 if (PyType_Ready(&PySet_Type) < 0)
1727 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (PyType_Ready(&PyUnicode_Type) < 0)
1730 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 if (PyType_Ready(&PySlice_Type) < 0)
1733 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1736 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 if (PyType_Ready(&PyComplex_Type) < 0)
1739 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (PyType_Ready(&PyFloat_Type) < 0)
1742 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (PyType_Ready(&PyLong_Type) < 0)
1745 Py_FatalError("Can't initialize int type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1748 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 if (PyType_Ready(&PyProperty_Type) < 0)
1751 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001752
Stefan Krah9a2d99e2012-02-25 12:24:21 +01001753 if (PyType_Ready(&_PyManagedBuffer_Type) < 0)
1754 Py_FatalError("Can't initialize managed buffer type");
1755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (PyType_Ready(&PyMemoryView_Type) < 0)
1757 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (PyType_Ready(&PyTuple_Type) < 0)
1760 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (PyType_Ready(&PyEnum_Type) < 0)
1763 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (PyType_Ready(&PyReversed_Type) < 0)
1766 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1769 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (PyType_Ready(&PyCode_Type) < 0)
1772 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (PyType_Ready(&PyFrame_Type) < 0)
1775 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (PyType_Ready(&PyCFunction_Type) < 0)
1778 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (PyType_Ready(&PyMethod_Type) < 0)
1781 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 if (PyType_Ready(&PyFunction_Type) < 0)
1784 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (PyType_Ready(&PyDictProxy_Type) < 0)
1787 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (PyType_Ready(&PyGen_Type) < 0)
1790 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1793 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1796 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001797
Benjamin Petersoneff61f62011-09-01 16:32:31 -04001798 if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1799 Py_FatalError("Can't initialize method wrapper type");
1800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (PyType_Ready(&PyEllipsis_Type) < 0)
1802 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1805 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001806
Barry Warsaw409da152012-06-03 16:18:47 -04001807 if (PyType_Ready(&_PyNamespace_Type) < 0)
1808 Py_FatalError("Can't initialize namespace type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -04001809
Benjamin Petersonc4311282012-10-30 23:21:10 -04001810 if (PyType_Ready(&PyCapsule_Type) < 0)
1811 Py_FatalError("Can't initialize capsule type");
1812
1813 if (PyType_Ready(&PyLongRangeIter_Type) < 0)
1814 Py_FatalError("Can't initialize long range iterator type");
1815
1816 if (PyType_Ready(&PyCell_Type) < 0)
1817 Py_FatalError("Can't initialize cell type");
1818
1819 if (PyType_Ready(&PyInstanceMethod_Type) < 0)
1820 Py_FatalError("Can't initialize instance method type");
1821
1822 if (PyType_Ready(&PyClassMethodDescr_Type) < 0)
1823 Py_FatalError("Can't initialize class method descr type");
1824
1825 if (PyType_Ready(&PyMethodDescr_Type) < 0)
1826 Py_FatalError("Can't initialize method descr type");
1827
1828 if (PyType_Ready(&PyCallIter_Type) < 0)
1829 Py_FatalError("Can't initialize call iter type");
1830
1831 if (PyType_Ready(&PySeqIter_Type) < 0)
1832 Py_FatalError("Can't initialize sequence iterator type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001833}
1834
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001835
Guido van Rossum84a90321996-05-22 16:34:47 +00001836#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001837
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001838void
Fred Drake100814d2000-07-09 15:48:49 +00001839_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 _Py_INC_REFTOTAL;
1842 op->ob_refcnt = 1;
1843 _Py_AddToAllObjects(op, 1);
1844 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001845}
1846
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001847void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001848_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001849{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001850#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001851 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001852#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 if (op->ob_refcnt < 0)
1854 Py_FatalError("UNREF negative refcnt");
1855 if (op == &refchain ||
1856 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1857 fprintf(stderr, "* ob\n");
1858 _PyObject_Dump(op);
1859 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1860 _PyObject_Dump(op->_ob_prev->_ob_next);
1861 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1862 _PyObject_Dump(op->_ob_next->_ob_prev);
1863 Py_FatalError("UNREF invalid object");
1864 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001865#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1867 if (p == op)
1868 break;
1869 }
1870 if (p == &refchain) /* Not found */
1871 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001872#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 op->_ob_next->_ob_prev = op->_ob_prev;
1874 op->_ob_prev->_ob_next = op->_ob_next;
1875 op->_ob_next = op->_ob_prev = NULL;
1876 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001877}
1878
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001879void
Fred Drake100814d2000-07-09 15:48:49 +00001880_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1883 _Py_ForgetReference(op);
1884 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001885}
1886
Tim Peters269b2a62003-04-17 19:52:29 +00001887/* Print all live objects. Because PyObject_Print is called, the
1888 * interpreter must be in a healthy state.
1889 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001890void
Fred Drake100814d2000-07-09 15:48:49 +00001891_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyObject *op;
1894 fprintf(fp, "Remaining objects:\n");
1895 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1896 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1897 if (PyObject_Print(op, fp, 0) != 0)
1898 PyErr_Clear();
1899 putc('\n', fp);
1900 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001901}
1902
Tim Peters269b2a62003-04-17 19:52:29 +00001903/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1904 * doesn't make any calls to the Python C API, so is always safe to call.
1905 */
1906void
1907_Py_PrintReferenceAddresses(FILE *fp)
1908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 PyObject *op;
1910 fprintf(fp, "Remaining object addresses:\n");
1911 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1912 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1913 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001914}
1915
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001916PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001917_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 int i, n;
1920 PyObject *t = NULL;
1921 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1924 return NULL;
1925 op = refchain._ob_next;
1926 res = PyList_New(0);
1927 if (res == NULL)
1928 return NULL;
1929 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1930 while (op == self || op == args || op == res || op == t ||
1931 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1932 op = op->_ob_next;
1933 if (op == &refchain)
1934 return res;
1935 }
1936 if (PyList_Append(res, op) < 0) {
1937 Py_DECREF(res);
1938 return NULL;
1939 }
1940 op = op->_ob_next;
1941 }
1942 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001943}
1944
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001945#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001946
Benjamin Petersonb173f782009-05-05 22:31:58 +00001947/* Hack to force loading of pycapsule.o */
1948PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
1949
1950
Guido van Rossum84a90321996-05-22 16:34:47 +00001951/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001952Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001953
1954
David Malcolm49526f42012-06-22 14:55:41 -04001955void
1956_PyObject_DebugTypeStats(FILE *out)
1957{
1958 _PyCFunction_DebugMallocStats(out);
1959 _PyDict_DebugMallocStats(out);
1960 _PyFloat_DebugMallocStats(out);
1961 _PyFrame_DebugMallocStats(out);
1962 _PyList_DebugMallocStats(out);
1963 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001964 _PyTuple_DebugMallocStats(out);
1965}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001966
Guido van Rossum86610361998-04-10 22:32:46 +00001967/* These methods are used to control infinite recursion in repr, str, print,
1968 etc. Container objects that may recursively contain themselves,
1969 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1970 Py_ReprLeave() to avoid infinite recursion.
1971
1972 Py_ReprEnter() returns 0 the first time it is called for a particular
1973 object and 1 every time thereafter. It returns -1 if an exception
1974 occurred. Py_ReprLeave() has no return value.
1975
1976 See dictobject.c and listobject.c for examples of use.
1977*/
1978
Guido van Rossum86610361998-04-10 22:32:46 +00001979int
Fred Drake100814d2000-07-09 15:48:49 +00001980Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 PyObject *dict;
1983 PyObject *list;
1984 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 dict = PyThreadState_GetDict();
1987 if (dict == NULL)
1988 return 0;
Victor Stinner7a07e452013-11-06 18:57:29 +01001989 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 if (list == NULL) {
1991 list = PyList_New(0);
1992 if (list == NULL)
1993 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01001994 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 return -1;
1996 Py_DECREF(list);
1997 }
1998 i = PyList_GET_SIZE(list);
1999 while (--i >= 0) {
2000 if (PyList_GET_ITEM(list, i) == obj)
2001 return 1;
2002 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002003 if (PyList_Append(list, obj) < 0)
2004 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002006}
2007
2008void
Fred Drake100814d2000-07-09 15:48:49 +00002009Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 PyObject *dict;
2012 PyObject *list;
2013 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002014 PyObject *error_type, *error_value, *error_traceback;
2015
2016 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 dict = PyThreadState_GetDict();
2019 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002020 goto finally;
2021
Victor Stinner7a07e452013-11-06 18:57:29 +01002022 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002024 goto finally;
2025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 i = PyList_GET_SIZE(list);
2027 /* Count backwards because we always expect obj to be list[-1] */
2028 while (--i >= 0) {
2029 if (PyList_GET_ITEM(list, i) == obj) {
2030 PyList_SetSlice(list, i, i + 1, NULL);
2031 break;
2032 }
2033 }
Victor Stinner1b634932013-07-16 22:24:44 +02002034
2035finally:
2036 /* ignore exceptions because there is no way to report them. */
2037 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002038}
Guido van Rossumd724b232000-03-13 16:01:29 +00002039
Tim Peters803526b2002-07-07 05:13:56 +00002040/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002041
Tim Peters803526b2002-07-07 05:13:56 +00002042/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002043int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002044
Tim Peters803526b2002-07-07 05:13:56 +00002045/* List of objects that still need to be cleaned up, singly linked via their
2046 * gc headers' gc_prev pointers.
2047 */
2048PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002049
Tim Peters803526b2002-07-07 05:13:56 +00002050/* Add op to the _PyTrash_delete_later list. Called when the current
2051 * call-stack depth gets large. op must be a currently untracked gc'ed
2052 * object, with refcount 0. Py_DECREF must already have been called on it.
2053 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002054void
Fred Drake100814d2000-07-09 15:48:49 +00002055_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 assert(PyObject_IS_GC(op));
Antoine Pitrou796564c2013-07-30 19:59:21 +02002058 assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 assert(op->ob_refcnt == 0);
2060 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2061 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002062}
2063
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002064/* The equivalent API, using per-thread state recursion info */
2065void
2066_PyTrash_thread_deposit_object(PyObject *op)
2067{
2068 PyThreadState *tstate = PyThreadState_GET();
2069 assert(PyObject_IS_GC(op));
Antoine Pitrou796564c2013-07-30 19:59:21 +02002070 assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002071 assert(op->ob_refcnt == 0);
2072 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *) tstate->trash_delete_later;
2073 tstate->trash_delete_later = op;
2074}
2075
Tim Peters803526b2002-07-07 05:13:56 +00002076/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2077 * the call-stack unwinds again.
2078 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002079void
Fred Drake100814d2000-07-09 15:48:49 +00002080_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 while (_PyTrash_delete_later) {
2083 PyObject *op = _PyTrash_delete_later;
2084 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 _PyTrash_delete_later =
2087 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 /* Call the deallocator directly. This used to try to
2090 * fool Py_DECREF into calling it indirectly, but
2091 * Py_DECREF was already called on this object, and in
2092 * assorted non-release builds calling Py_DECREF again ends
2093 * up distorting allocation statistics.
2094 */
2095 assert(op->ob_refcnt == 0);
2096 ++_PyTrash_delete_nesting;
2097 (*dealloc)(op);
2098 --_PyTrash_delete_nesting;
2099 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002100}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002101
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002102/* The equivalent API, using per-thread state recursion info */
2103void
2104_PyTrash_thread_destroy_chain(void)
2105{
2106 PyThreadState *tstate = PyThreadState_GET();
2107 while (tstate->trash_delete_later) {
2108 PyObject *op = tstate->trash_delete_later;
2109 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2110
2111 tstate->trash_delete_later =
2112 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
2113
2114 /* Call the deallocator directly. This used to try to
2115 * fool Py_DECREF into calling it indirectly, but
2116 * Py_DECREF was already called on this object, and in
2117 * assorted non-release builds calling Py_DECREF again ends
2118 * up distorting allocation statistics.
2119 */
2120 assert(op->ob_refcnt == 0);
2121 ++tstate->trash_delete_nesting;
2122 (*dealloc)(op);
2123 --tstate->trash_delete_nesting;
2124 }
2125}
2126
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002127#ifndef Py_TRACE_REFS
2128/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
2129 Define this here, so we can undefine the macro. */
2130#undef _Py_Dealloc
2131PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
2132void
2133_Py_Dealloc(PyObject *op)
2134{
2135 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
2136 (*Py_TYPE(op)->tp_dealloc)(op);
2137}
2138#endif
2139
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002140#ifdef __cplusplus
2141}
2142#endif