blob: e1718eafcdbf77f1dc3f7d8cc8b37257008643e7 [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}
Nick Coghland6009512014-11-20 21:39:37 +100036
37void
38_PyDebug_PrintTotalRefs(void) {
39 PyObject *xoptions, *value;
40 _Py_IDENTIFIER(showrefcount);
41
42 xoptions = PySys_GetXOptions();
43 if (xoptions == NULL)
44 return;
45 value = _PyDict_GetItemId(xoptions, &PyId_showrefcount);
46 if (value == Py_True)
47 fprintf(stderr,
48 "[%" PY_FORMAT_SIZE_T "d refs, "
49 "%" PY_FORMAT_SIZE_T "d blocks]\n",
50 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
51}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053
Guido van Rossum3f5da241990-12-20 15:06:42 +000054/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
55 These are used by the individual routines for object creation.
56 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057
Tim Peters78be7992003-03-23 02:51:01 +000058#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000059/* Head of circular doubly-linked list of all objects. These are linked
60 * together via the _ob_prev and _ob_next members of a PyObject, which
61 * exist only in a Py_TRACE_REFS build.
62 */
Tim Peters78be7992003-03-23 02:51:01 +000063static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000064
Tim Peters7571a0f2003-03-23 17:52:28 +000065/* Insert op at the front of the list of all objects. If force is true,
66 * op is added even if _ob_prev and _ob_next are non-NULL already. If
67 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
68 * force should be true if and only if op points to freshly allocated,
69 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000070 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000071 * Note that objects are normally added to the list via _Py_NewReference,
72 * which is called by PyObject_Init. Not all objects are initialized that
73 * way, though; exceptions include statically allocated type objects, and
74 * statically allocated singletons (like Py_True and Py_None).
75 */
Tim Peters36eb4df2003-03-23 03:33:13 +000076void
Tim Peters7571a0f2003-03-23 17:52:28 +000077_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000078{
Tim Peters7571a0f2003-03-23 17:52:28 +000079#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 if (!force) {
81 /* If it's initialized memory, op must be in or out of
82 * the list unambiguously.
83 */
84 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
85 }
Tim Peters78be7992003-03-23 02:51:01 +000086#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 if (force || op->_ob_prev == NULL) {
88 op->_ob_next = refchain._ob_next;
89 op->_ob_prev = &refchain;
90 refchain._ob_next->_ob_prev = op;
91 refchain._ob_next = op;
92 }
Tim Peters7571a0f2003-03-23 17:52:28 +000093}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000095
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000096#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000098/* All types are added to type_list, at least when
99 they get one object created. That makes them
100 immortal, which unfortunately contributes to
101 garbage itself. If unlist_types_without_objects
102 is set, they will be removed from the type_list
103 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +0000104static int unlist_types_without_objects;
105extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
106extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
107extern Py_ssize_t null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000108void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000109dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 for (tp = type_list; tp; tp = tp->tp_next)
114 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
115 "freed: %" PY_FORMAT_SIZE_T "d, "
116 "max in use: %" PY_FORMAT_SIZE_T "d\n",
117 tp->tp_name, tp->tp_allocs, tp->tp_frees,
118 tp->tp_maxalloc);
119 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
120 "empty: %" PY_FORMAT_SIZE_T "d\n",
121 fast_tuple_allocs, tuple_zero_allocs);
122 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
123 "neg: %" PY_FORMAT_SIZE_T "d\n",
124 quick_int_allocs, quick_neg_int_allocs);
125 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
126 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
127 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000128}
129
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000130PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000131get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 PyTypeObject *tp;
134 PyObject *result;
135 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 result = PyList_New(0);
138 if (result == NULL)
139 return NULL;
140 for (tp = type_list; tp; tp = tp->tp_next) {
141 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
142 tp->tp_frees, tp->tp_maxalloc);
143 if (v == NULL) {
144 Py_DECREF(result);
145 return NULL;
146 }
147 if (PyList_Append(result, v) < 0) {
148 Py_DECREF(v);
149 Py_DECREF(result);
150 return NULL;
151 }
152 Py_DECREF(v);
153 }
154 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000155}
156
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000157void
Fred Drake100814d2000-07-09 15:48:49 +0000158inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
161 /* first time; insert in linked list */
162 if (tp->tp_next != NULL) /* sanity check */
163 Py_FatalError("XXX inc_count sanity check");
164 if (type_list)
165 type_list->tp_prev = tp;
166 tp->tp_next = type_list;
167 /* Note that as of Python 2.2, heap-allocated type objects
168 * can go away, but this code requires that they stay alive
169 * until program exit. That's why we're careful with
170 * refcounts here. type_list gets a new reference to tp,
171 * while ownership of the reference type_list used to hold
172 * (if any) was transferred to tp->tp_next in the line above.
173 * tp is thus effectively immortal after this.
174 */
175 Py_INCREF(tp);
176 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000177#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 /* Also insert in the doubly-linked list of all objects,
179 * if not already there.
180 */
181 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000182#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 }
184 tp->tp_allocs++;
185 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
186 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000187}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000188
189void dec_count(PyTypeObject *tp)
190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 tp->tp_frees++;
192 if (unlist_types_without_objects &&
193 tp->tp_allocs == tp->tp_frees) {
194 /* unlink the type from type_list */
195 if (tp->tp_prev)
196 tp->tp_prev->tp_next = tp->tp_next;
197 else
198 type_list = tp->tp_next;
199 if (tp->tp_next)
200 tp->tp_next->tp_prev = tp->tp_prev;
201 tp->tp_next = tp->tp_prev = NULL;
202 Py_DECREF(tp);
203 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000204}
205
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000206#endif
207
Tim Peters7c321a82002-07-09 02:57:01 +0000208#ifdef Py_REF_DEBUG
209/* Log a fatal error; doesn't return. */
210void
211_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 char buf[300];
Tim Peters7c321a82002-07-09 02:57:01 +0000214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 PyOS_snprintf(buf, sizeof(buf),
216 "%s:%i object at %p has negative ref count "
217 "%" PY_FORMAT_SIZE_T "d",
218 fname, lineno, op, op->ob_refcnt);
219 Py_FatalError(buf);
Tim Peters7c321a82002-07-09 02:57:01 +0000220}
221
222#endif /* Py_REF_DEBUG */
223
Thomas Heller1328b522004-04-22 17:23:49 +0000224void
225Py_IncRef(PyObject *o)
226{
227 Py_XINCREF(o);
228}
229
230void
231Py_DecRef(PyObject *o)
232{
233 Py_XDECREF(o);
234}
235
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000236PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000237PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (op == NULL)
240 return PyErr_NoMemory();
241 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
242 Py_TYPE(op) = tp;
243 _Py_NewReference(op);
244 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245}
246
Guido van Rossumb18618d2000-05-03 23:44:39 +0000247PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000248PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (op == NULL)
251 return (PyVarObject *) PyErr_NoMemory();
252 /* Any changes should be reflected in PyObject_INIT_VAR */
253 op->ob_size = size;
254 Py_TYPE(op) = tp;
255 _Py_NewReference((PyObject *)op);
256 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000257}
258
259PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000260_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 PyObject *op;
263 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
264 if (op == NULL)
265 return PyErr_NoMemory();
266 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000267}
268
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000269PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000270_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PyVarObject *op;
273 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
274 op = (PyVarObject *) PyObject_MALLOC(size);
275 if (op == NULL)
276 return (PyVarObject *)PyErr_NoMemory();
277 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000278}
279
Antoine Pitrou796564c2013-07-30 19:59:21 +0200280void
281PyObject_CallFinalizer(PyObject *self)
282{
283 PyTypeObject *tp = Py_TYPE(self);
284
285 /* The former could happen on heaptypes created from the C API, e.g.
286 PyType_FromSpec(). */
287 if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
288 tp->tp_finalize == NULL)
289 return;
290 /* tp_finalize should only be called once. */
291 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
292 return;
293
294 tp->tp_finalize(self);
295 if (PyType_IS_GC(tp))
296 _PyGC_SET_FINALIZED(self, 1);
297}
298
299int
300PyObject_CallFinalizerFromDealloc(PyObject *self)
301{
302 Py_ssize_t refcnt;
303
304 /* Temporarily resurrect the object. */
305 if (self->ob_refcnt != 0) {
306 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
307 "object with a non-zero refcount");
308 }
309 self->ob_refcnt = 1;
310
311 PyObject_CallFinalizer(self);
312
313 /* Undo the temporary resurrection; can't use DECREF here, it would
314 * cause a recursive call.
315 */
316 assert(self->ob_refcnt > 0);
317 if (--self->ob_refcnt == 0)
318 return 0; /* this is the normal path out */
319
320 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
321 * never happened.
322 */
323 refcnt = self->ob_refcnt;
324 _Py_NewReference(self);
325 self->ob_refcnt = refcnt;
326
327 if (PyType_IS_GC(Py_TYPE(self))) {
328 assert(_PyGC_REFS(self) != _PyGC_REFS_UNTRACKED);
329 }
330 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
331 * we need to undo that. */
332 _Py_DEC_REFTOTAL;
333 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
334 * chain, so no more to do there.
335 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
336 * _Py_NewReference bumped tp_allocs: both of those need to be
337 * undone.
338 */
339#ifdef COUNT_ALLOCS
340 --Py_TYPE(self)->tp_frees;
341 --Py_TYPE(self)->tp_allocs;
342#endif
343 return -1;
344}
345
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000346int
347PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (PyErr_CheckSignals())
351 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000352#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 if (PyOS_CheckStack()) {
354 PyErr_SetString(PyExc_MemoryError, "stack overflow");
355 return -1;
356 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000357#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 clearerr(fp); /* Clear any previous error condition */
359 if (op == NULL) {
360 Py_BEGIN_ALLOW_THREADS
361 fprintf(fp, "<nil>");
362 Py_END_ALLOW_THREADS
363 }
364 else {
365 if (op->ob_refcnt <= 0)
366 /* XXX(twouters) cast refcount to long until %zd is
367 universally available */
368 Py_BEGIN_ALLOW_THREADS
369 fprintf(fp, "<refcnt %ld at %p>",
370 (long)op->ob_refcnt, op);
371 Py_END_ALLOW_THREADS
372 else {
373 PyObject *s;
374 if (flags & Py_PRINT_RAW)
375 s = PyObject_Str(op);
376 else
377 s = PyObject_Repr(op);
378 if (s == NULL)
379 ret = -1;
380 else if (PyBytes_Check(s)) {
381 fwrite(PyBytes_AS_STRING(s), 1,
382 PyBytes_GET_SIZE(s), fp);
383 }
384 else if (PyUnicode_Check(s)) {
385 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200386 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (t == NULL)
388 ret = 0;
389 else {
390 fwrite(PyBytes_AS_STRING(t), 1,
391 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000392 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 }
394 }
395 else {
396 PyErr_Format(PyExc_TypeError,
397 "str() or repr() returned '%.100s'",
398 s->ob_type->tp_name);
399 ret = -1;
400 }
401 Py_XDECREF(s);
402 }
403 }
404 if (ret == 0) {
405 if (ferror(fp)) {
406 PyErr_SetFromErrno(PyExc_IOError);
407 clearerr(fp);
408 ret = -1;
409 }
410 }
411 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412}
413
Guido van Rossum38938152006-08-21 23:36:26 +0000414/* For debugging convenience. Set a breakpoint here and call it from your DLL */
415void
Thomas Woutersb2137042007-02-01 18:02:27 +0000416_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000417{
418}
419
Neal Norwitz1a997502003-01-13 20:13:12 +0000420
Barry Warsaw9bf16442001-01-23 16:24:35 +0000421/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000422void
423_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (op == NULL)
426 fprintf(stderr, "NULL\n");
427 else {
Georg Brandldfd73442009-04-05 11:47:34 +0000428#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PyGILState_STATE gil;
Georg Brandldfd73442009-04-05 11:47:34 +0000430#endif
Victor Stinnere5132102013-08-26 13:49:06 +0200431 PyObject *error_type, *error_value, *error_traceback;
432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 fprintf(stderr, "object : ");
Georg Brandldfd73442009-04-05 11:47:34 +0000434#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 gil = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000436#endif
Victor Stinnere5132102013-08-26 13:49:06 +0200437
438 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 (void)PyObject_Print(op, stderr, 0);
Victor Stinnere5132102013-08-26 13:49:06 +0200440 PyErr_Restore(error_type, error_value, error_traceback);
441
Georg Brandldfd73442009-04-05 11:47:34 +0000442#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 PyGILState_Release(gil);
Georg Brandldfd73442009-04-05 11:47:34 +0000444#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 /* XXX(twouters) cast refcount to long until %zd is
446 universally available */
447 fprintf(stderr, "\n"
448 "type : %s\n"
449 "refcount: %ld\n"
450 "address : %p\n",
451 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
452 (long)op->ob_refcnt,
453 op);
454 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000455}
Barry Warsaw903138f2001-01-23 16:33:18 +0000456
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000458PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyObject *res;
461 if (PyErr_CheckSignals())
462 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000463#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (PyOS_CheckStack()) {
465 PyErr_SetString(PyExc_MemoryError, "stack overflow");
466 return NULL;
467 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000468#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (v == NULL)
470 return PyUnicode_FromString("<NULL>");
471 if (Py_TYPE(v)->tp_repr == NULL)
472 return PyUnicode_FromFormat("<%s object at %p>",
473 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200474
475#ifdef Py_DEBUG
476 /* PyObject_Repr() must not be called with an exception set,
477 because it may clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000478 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200479 assert(!PyErr_Occurred());
480#endif
481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 res = (*v->ob_type->tp_repr)(v);
Victor Stinner0a54cf12011-12-01 03:22:44 +0100483 if (res == NULL)
484 return NULL;
485 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyErr_Format(PyExc_TypeError,
487 "__repr__ returned non-string (type %.200s)",
488 res->ob_type->tp_name);
489 Py_DECREF(res);
490 return NULL;
491 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100492#ifndef Py_DEBUG
493 if (PyUnicode_READY(res) < 0)
494 return NULL;
495#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000497}
498
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000500PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 PyObject *res;
503 if (PyErr_CheckSignals())
504 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000505#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (PyOS_CheckStack()) {
507 PyErr_SetString(PyExc_MemoryError, "stack overflow");
508 return NULL;
509 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000510#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (v == NULL)
512 return PyUnicode_FromString("<NULL>");
513 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100514#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100515 if (PyUnicode_READY(v) < 0)
516 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100517#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 Py_INCREF(v);
519 return v;
520 }
521 if (Py_TYPE(v)->tp_str == NULL)
522 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000523
Victor Stinner33824f62013-08-26 14:05:19 +0200524#ifdef Py_DEBUG
525 /* PyObject_Str() must not be called with an exception set,
526 because it may clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000527 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200528 assert(!PyErr_Occurred());
529#endif
530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 /* It is possible for a type to have a tp_str representation that loops
532 infinitely. */
533 if (Py_EnterRecursiveCall(" while getting the str of an object"))
534 return NULL;
535 res = (*Py_TYPE(v)->tp_str)(v);
536 Py_LeaveRecursiveCall();
537 if (res == NULL)
538 return NULL;
539 if (!PyUnicode_Check(res)) {
540 PyErr_Format(PyExc_TypeError,
541 "__str__ returned non-string (type %.200s)",
542 Py_TYPE(res)->tp_name);
543 Py_DECREF(res);
544 return NULL;
545 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100546#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100547 if (PyUnicode_READY(res) < 0)
548 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100549#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100550 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000552}
553
Georg Brandl559e5d72008-06-11 18:37:52 +0000554PyObject *
555PyObject_ASCII(PyObject *v)
556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 repr = PyObject_Repr(v);
560 if (repr == NULL)
561 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000562
Victor Stinneraf037572013-04-14 18:44:10 +0200563 if (PyUnicode_IS_ASCII(repr))
564 return repr;
565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200567 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 Py_DECREF(repr);
569 if (ascii == NULL)
570 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 res = PyUnicode_DecodeASCII(
573 PyBytes_AS_STRING(ascii),
574 PyBytes_GET_SIZE(ascii),
575 NULL);
576
577 Py_DECREF(ascii);
578 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000579}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000580
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000581PyObject *
582PyObject_Bytes(PyObject *v)
583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 if (v == NULL)
587 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (PyBytes_CheckExact(v)) {
590 Py_INCREF(v);
591 return v;
592 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000593
Benjamin Petersonce798522012-01-22 11:24:29 -0500594 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (func != NULL) {
596 result = PyObject_CallFunctionObjArgs(func, NULL);
597 Py_DECREF(func);
598 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000599 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000601 PyErr_Format(PyExc_TypeError,
602 "__bytes__ returned non-bytes (type %.200s)",
603 Py_TYPE(result)->tp_name);
604 Py_DECREF(result);
605 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
607 return result;
608 }
609 else if (PyErr_Occurred())
610 return NULL;
611 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000612}
613
Mark Dickinsonc008a172009-02-01 13:59:22 +0000614/* For Python 3.0.1 and later, the old three-way comparison has been
615 completely removed in favour of rich comparisons. PyObject_Compare() and
616 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000617 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000618 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000619
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000620 See (*) below for practical amendments.
621
Mark Dickinsonc008a172009-02-01 13:59:22 +0000622 tp_richcompare gets called with a first argument of the appropriate type
623 and a second object of an arbitrary type. We never do any kind of
624 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000625
Mark Dickinsonc008a172009-02-01 13:59:22 +0000626 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000627
628 NULL if an exception occurred
629 NotImplemented if the requested comparison is not implemented
630 any other false value if the requested comparison is false
631 any other true value if the requested comparison is true
632
633 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
634 NotImplemented.
635
636 (*) Practical amendments:
637
638 - If rich comparison returns NotImplemented, == and != are decided by
639 comparing the object pointer (i.e. falling back to the base object
640 implementation).
641
Guido van Rossuma4073002002-05-31 20:03:54 +0000642*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000643
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000644/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000645int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000646
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000647static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000648
649/* Perform a rich comparison, raising TypeError when the requested comparison
650 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000651static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000652do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 richcmpfunc f;
655 PyObject *res;
656 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 if (v->ob_type != w->ob_type &&
659 PyType_IsSubtype(w->ob_type, v->ob_type) &&
660 (f = w->ob_type->tp_richcompare) != NULL) {
661 checked_reverse_op = 1;
662 res = (*f)(w, v, _Py_SwappedOp[op]);
663 if (res != Py_NotImplemented)
664 return res;
665 Py_DECREF(res);
666 }
667 if ((f = v->ob_type->tp_richcompare) != NULL) {
668 res = (*f)(v, w, op);
669 if (res != Py_NotImplemented)
670 return res;
671 Py_DECREF(res);
672 }
673 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
674 res = (*f)(w, v, _Py_SwappedOp[op]);
675 if (res != Py_NotImplemented)
676 return res;
677 Py_DECREF(res);
678 }
679 /* If neither object implements it, provide a sensible default
680 for == and !=, but raise an exception for ordering. */
681 switch (op) {
682 case Py_EQ:
683 res = (v == w) ? Py_True : Py_False;
684 break;
685 case Py_NE:
686 res = (v != w) ? Py_True : Py_False;
687 break;
688 default:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 PyErr_Format(PyExc_TypeError,
Victor Stinner91108f02015-10-14 18:25:31 +0200690 "'%s' not supported between instances of '%.100s' and '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 opstrings[op],
Victor Stinner91108f02015-10-14 18:25:31 +0200692 v->ob_type->tp_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 w->ob_type->tp_name);
694 return NULL;
695 }
696 Py_INCREF(res);
697 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000698}
699
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000700/* Perform a rich comparison with object result. This wraps do_richcompare()
701 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000702
Guido van Rossume797ec12001-01-17 15:24:28 +0000703PyObject *
704PyObject_RichCompare(PyObject *v, PyObject *w, int op)
705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 assert(Py_LT <= op && op <= Py_GE);
709 if (v == NULL || w == NULL) {
710 if (!PyErr_Occurred())
711 PyErr_BadInternalCall();
712 return NULL;
713 }
714 if (Py_EnterRecursiveCall(" in comparison"))
715 return NULL;
716 res = do_richcompare(v, w, op);
717 Py_LeaveRecursiveCall();
718 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000719}
720
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000721/* Perform a rich comparison with integer result. This wraps
722 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000723int
724PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyObject *res;
727 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 /* Quick result when objects are the same.
730 Guarantees that identity implies equality. */
731 if (v == w) {
732 if (op == Py_EQ)
733 return 1;
734 else if (op == Py_NE)
735 return 0;
736 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 res = PyObject_RichCompare(v, w, op);
739 if (res == NULL)
740 return -1;
741 if (PyBool_Check(res))
742 ok = (res == Py_True);
743 else
744 ok = PyObject_IsTrue(res);
745 Py_DECREF(res);
746 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000747}
Fred Drake13634cf2000-06-29 19:17:04 +0000748
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100749Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000750PyObject_HashNotImplemented(PyObject *v)
751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
753 Py_TYPE(v)->tp_name);
754 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000755}
Fred Drake13634cf2000-06-29 19:17:04 +0000756
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000757Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000758PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyTypeObject *tp = Py_TYPE(v);
761 if (tp->tp_hash != NULL)
762 return (*tp->tp_hash)(v);
763 /* To keep to the general practice that inheriting
764 * solely from object in C code should work without
765 * an explicit call to PyType_Ready, we implicitly call
766 * PyType_Ready here and then check the tp_hash slot again
767 */
768 if (tp->tp_dict == NULL) {
769 if (PyType_Ready(tp) < 0)
770 return -1;
771 if (tp->tp_hash != NULL)
772 return (*tp->tp_hash)(v);
773 }
774 /* Otherwise, the object can't be hashed */
775 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000776}
777
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000779PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (Py_TYPE(v)->tp_getattr != NULL)
784 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
785 w = PyUnicode_InternFromString(name);
786 if (w == NULL)
787 return NULL;
788 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100789 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000791}
792
793int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000794PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyObject *res = PyObject_GetAttrString(v, name);
797 if (res != NULL) {
798 Py_DECREF(res);
799 return 1;
800 }
801 PyErr_Clear();
802 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000803}
804
805int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000806PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyObject *s;
809 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (Py_TYPE(v)->tp_setattr != NULL)
812 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
813 s = PyUnicode_InternFromString(name);
814 if (s == NULL)
815 return -1;
816 res = PyObject_SetAttr(v, s, w);
817 Py_XDECREF(s);
818 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000819}
820
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500821int
822_PyObject_IsAbstract(PyObject *obj)
823{
824 int res;
825 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500826
827 if (obj == NULL)
828 return 0;
829
830 isabstract = _PyObject_GetAttrId(obj, &PyId___isabstractmethod__);
831 if (isabstract == NULL) {
832 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
833 PyErr_Clear();
834 return 0;
835 }
836 return -1;
837 }
838 res = PyObject_IsTrue(isabstract);
839 Py_DECREF(isabstract);
840 return res;
841}
842
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000843PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200844_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
845{
846 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100847 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200848 if (!oname)
849 return NULL;
850 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200851 return result;
852}
853
854int
855_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
856{
857 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100858 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200859 if (!oname)
860 return -1;
861 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200862 return result;
863}
864
865int
866_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
867{
868 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100869 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200870 if (!oname)
871 return -1;
872 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200873 return result;
874}
875
876PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000877PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (!PyUnicode_Check(name)) {
882 PyErr_Format(PyExc_TypeError,
883 "attribute name must be string, not '%.200s'",
884 name->ob_type->tp_name);
885 return NULL;
886 }
887 if (tp->tp_getattro != NULL)
888 return (*tp->tp_getattro)(v, name);
889 if (tp->tp_getattr != NULL) {
890 char *name_str = _PyUnicode_AsString(name);
891 if (name_str == NULL)
892 return NULL;
893 return (*tp->tp_getattr)(v, name_str);
894 }
895 PyErr_Format(PyExc_AttributeError,
896 "'%.50s' object has no attribute '%U'",
897 tp->tp_name, name);
898 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000899}
900
901int
Fred Drake100814d2000-07-09 15:48:49 +0000902PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 PyObject *res = PyObject_GetAttr(v, name);
905 if (res != NULL) {
906 Py_DECREF(res);
907 return 1;
908 }
909 PyErr_Clear();
910 return 0;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000911}
912
913int
Fred Drake100814d2000-07-09 15:48:49 +0000914PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyTypeObject *tp = Py_TYPE(v);
917 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (!PyUnicode_Check(name)) {
920 PyErr_Format(PyExc_TypeError,
921 "attribute name must be string, not '%.200s'",
922 name->ob_type->tp_name);
923 return -1;
924 }
925 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 PyUnicode_InternInPlace(&name);
928 if (tp->tp_setattro != NULL) {
929 err = (*tp->tp_setattro)(v, name, value);
930 Py_DECREF(name);
931 return err;
932 }
933 if (tp->tp_setattr != NULL) {
934 char *name_str = _PyUnicode_AsString(name);
935 if (name_str == NULL)
936 return -1;
937 err = (*tp->tp_setattr)(v, name_str, value);
938 Py_DECREF(name);
939 return err;
940 }
941 Py_DECREF(name);
942 assert(name->ob_refcnt >= 1);
943 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
944 PyErr_Format(PyExc_TypeError,
945 "'%.100s' object has no attributes "
946 "(%s .%U)",
947 tp->tp_name,
948 value==NULL ? "del" : "assign to",
949 name);
950 else
951 PyErr_Format(PyExc_TypeError,
952 "'%.100s' object has only read-only attributes "
953 "(%s .%U)",
954 tp->tp_name,
955 value==NULL ? "del" : "assign to",
956 name);
957 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000958}
959
960/* Helper to get a pointer to an object's __dict__ slot, if any */
961
962PyObject **
963_PyObject_GetDictPtr(PyObject *obj)
964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 Py_ssize_t dictoffset;
966 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 dictoffset = tp->tp_dictoffset;
969 if (dictoffset == 0)
970 return NULL;
971 if (dictoffset < 0) {
972 Py_ssize_t tsize;
973 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 tsize = ((PyVarObject *)obj)->ob_size;
976 if (tsize < 0)
977 tsize = -tsize;
978 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 dictoffset += (long)size;
981 assert(dictoffset > 0);
982 assert(dictoffset % SIZEOF_VOID_P == 0);
983 }
984 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985}
986
Tim Peters6d6c1a32001-08-02 04:15:00 +0000987PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +0000988PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +0000989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 Py_INCREF(obj);
991 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +0000992}
993
Antoine Pitroua7013882012-04-05 00:04:20 +0200994/* Convenience function to get a builtin from its name */
995PyObject *
996_PyObject_GetBuiltin(const char *name)
997{
Victor Stinner53e9ec42013-11-07 00:43:05 +0100998 PyObject *mod_name, *mod, *attr;
999
Victor Stinnerbd303c12013-11-07 23:07:29 +01001000 mod_name = _PyUnicode_FromId(&PyId_builtins); /* borrowed */
Victor Stinner53e9ec42013-11-07 00:43:05 +01001001 if (mod_name == NULL)
1002 return NULL;
1003 mod = PyImport_Import(mod_name);
Antoine Pitroua7013882012-04-05 00:04:20 +02001004 if (mod == NULL)
1005 return NULL;
1006 attr = PyObject_GetAttrString(mod, name);
1007 Py_DECREF(mod);
1008 return attr;
1009}
1010
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001011/* Helper used when the __next__ method is removed from a type:
1012 tp_iternext is never NULL and can be safely called without checking
1013 on every iteration.
1014 */
1015
1016PyObject *
1017_PyObject_NextNotImplemented(PyObject *self)
1018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyErr_Format(PyExc_TypeError,
1020 "'%.200s' object is not iterable",
1021 Py_TYPE(self)->tp_name);
1022 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001023}
1024
Michael W. Hudson1593f502004-09-14 17:09:47 +00001025/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1026
Raymond Hettinger01538262003-03-17 08:24:35 +00001027PyObject *
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001028_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 PyTypeObject *tp = Py_TYPE(obj);
1031 PyObject *descr = NULL;
1032 PyObject *res = NULL;
1033 descrgetfunc f;
1034 Py_ssize_t dictoffset;
1035 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 if (!PyUnicode_Check(name)){
1038 PyErr_Format(PyExc_TypeError,
1039 "attribute name must be string, not '%.200s'",
1040 name->ob_type->tp_name);
1041 return NULL;
1042 }
1043 else
1044 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 if (tp->tp_dict == NULL) {
1047 if (PyType_Ready(tp) < 0)
1048 goto done;
1049 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 descr = _PyType_Lookup(tp, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 Py_XINCREF(descr);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 f = NULL;
1055 if (descr != NULL) {
1056 f = descr->ob_type->tp_descr_get;
1057 if (f != NULL && PyDescr_IsData(descr)) {
1058 res = f(descr, obj, (PyObject *)obj->ob_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 goto done;
1060 }
1061 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001062
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001063 if (dict == NULL) {
1064 /* Inline _PyObject_GetDictPtr */
1065 dictoffset = tp->tp_dictoffset;
1066 if (dictoffset != 0) {
1067 if (dictoffset < 0) {
1068 Py_ssize_t tsize;
1069 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001070
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001071 tsize = ((PyVarObject *)obj)->ob_size;
1072 if (tsize < 0)
1073 tsize = -tsize;
1074 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001075
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001076 dictoffset += (long)size;
1077 assert(dictoffset > 0);
1078 assert(dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001080 dictptr = (PyObject **) ((char *)obj + dictoffset);
1081 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 }
1083 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001084 if (dict != NULL) {
1085 Py_INCREF(dict);
1086 res = PyDict_GetItem(dict, name);
1087 if (res != NULL) {
1088 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001089 Py_DECREF(dict);
1090 goto done;
1091 }
1092 Py_DECREF(dict);
1093 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 if (f != NULL) {
1096 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 goto done;
1098 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 if (descr != NULL) {
1101 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001102 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 goto done;
1104 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 PyErr_Format(PyExc_AttributeError,
1107 "'%.50s' object has no attribute '%U'",
1108 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001109 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001110 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 Py_DECREF(name);
1112 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113}
1114
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001115PyObject *
1116PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1117{
1118 return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1119}
1120
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001122_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1123 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 PyTypeObject *tp = Py_TYPE(obj);
1126 PyObject *descr;
1127 descrsetfunc f;
1128 PyObject **dictptr;
1129 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (!PyUnicode_Check(name)){
1132 PyErr_Format(PyExc_TypeError,
1133 "attribute name must be string, not '%.200s'",
1134 name->ob_type->tp_name);
1135 return -1;
1136 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001137
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001138 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1139 return -1;
1140
1141 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001144 Py_XINCREF(descr);
1145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 f = NULL;
1147 if (descr != NULL) {
1148 f = descr->ob_type->tp_descr_set;
1149 if (f != NULL && PyDescr_IsData(descr)) {
1150 res = f(descr, obj, value);
1151 goto done;
1152 }
1153 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001154
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001155 if (dict == NULL) {
1156 dictptr = _PyObject_GetDictPtr(obj);
1157 if (dictptr != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001158 res = _PyObjectDict_SetItem(Py_TYPE(obj), dictptr, name, value);
1159 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1160 PyErr_SetObject(PyExc_AttributeError, name);
1161 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001163 }
1164 if (dict != NULL) {
1165 Py_INCREF(dict);
1166 if (value == NULL)
1167 res = PyDict_DelItem(dict, name);
1168 else
1169 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001170 Py_DECREF(dict);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001171 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1172 PyErr_SetObject(PyExc_AttributeError, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001173 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (f != NULL) {
1177 res = f(descr, obj, value);
1178 goto done;
1179 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (descr == NULL) {
1182 PyErr_Format(PyExc_AttributeError,
1183 "'%.100s' object has no attribute '%U'",
1184 tp->tp_name, name);
1185 goto done;
1186 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyErr_Format(PyExc_AttributeError,
1189 "'%.50s' object attribute '%U' is read-only",
1190 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001191 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001192 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 Py_DECREF(name);
1194 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001195}
1196
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001197int
1198PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1199{
1200 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1201}
1202
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001203int
1204PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1205{
1206 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
1207 if (dictptr == NULL) {
1208 PyErr_SetString(PyExc_AttributeError,
1209 "This object has no __dict__");
1210 return -1;
1211 }
1212 if (value == NULL) {
1213 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1214 return -1;
1215 }
1216 if (!PyDict_Check(value)) {
1217 PyErr_Format(PyExc_TypeError,
1218 "__dict__ must be set to a dictionary, "
1219 "not a '%.200s'", Py_TYPE(value)->tp_name);
1220 return -1;
1221 }
1222 dict = *dictptr;
1223 Py_XINCREF(value);
1224 *dictptr = value;
1225 Py_XDECREF(dict);
1226 return 0;
1227}
1228
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001229
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001230/* Test a value used as condition, e.g., in a for or if statement.
1231 Return -1 if an error occurred */
1232
1233int
Fred Drake100814d2000-07-09 15:48:49 +00001234PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 Py_ssize_t res;
1237 if (v == Py_True)
1238 return 1;
1239 if (v == Py_False)
1240 return 0;
1241 if (v == Py_None)
1242 return 0;
1243 else if (v->ob_type->tp_as_number != NULL &&
1244 v->ob_type->tp_as_number->nb_bool != NULL)
1245 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1246 else if (v->ob_type->tp_as_mapping != NULL &&
1247 v->ob_type->tp_as_mapping->mp_length != NULL)
1248 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1249 else if (v->ob_type->tp_as_sequence != NULL &&
1250 v->ob_type->tp_as_sequence->sq_length != NULL)
1251 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1252 else
1253 return 1;
1254 /* if it is negative, it should be either -1 or -2 */
1255 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001256}
1257
Tim Peters803526b2002-07-07 05:13:56 +00001258/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001259 Return -1 if an error occurred */
1260
1261int
Fred Drake100814d2000-07-09 15:48:49 +00001262PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 int res;
1265 res = PyObject_IsTrue(v);
1266 if (res < 0)
1267 return res;
1268 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001269}
1270
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001271/* Test whether an object can be called */
1272
1273int
Fred Drake100814d2000-07-09 15:48:49 +00001274PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (x == NULL)
1277 return 0;
1278 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001279}
1280
Tim Peters7eea37e2001-09-04 22:08:56 +00001281
Georg Brandle32b4222007-03-10 22:13:27 +00001282/* Helper for PyObject_Dir without arguments: returns the local scope. */
1283static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001284_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001287 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001288
Victor Stinner41bb43a2013-10-29 01:19:37 +01001289 locals = PyEval_GetLocals();
1290 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 names = PyMapping_Keys(locals);
1294 if (!names)
1295 return NULL;
1296 if (!PyList_Check(names)) {
1297 PyErr_Format(PyExc_TypeError,
1298 "dir(): expected keys() of locals to be a list, "
1299 "not '%.200s'", Py_TYPE(names)->tp_name);
1300 Py_DECREF(names);
1301 return NULL;
1302 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001303 if (PyList_Sort(names)) {
1304 Py_DECREF(names);
1305 return NULL;
1306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 /* the locals don't need to be DECREF'd */
1308 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001309}
1310
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001311/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001312static PyObject *
1313_dir_object(PyObject *obj)
1314{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001315 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001316 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 assert(obj);
1319 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001320 if (!PyErr_Occurred())
1321 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1322 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001324 /* use __dir__ */
1325 result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
1326 Py_DECREF(dirfunc);
1327 if (result == NULL)
1328 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001329 /* return sorted(result) */
1330 sorted = PySequence_List(result);
1331 Py_DECREF(result);
1332 if (sorted == NULL)
1333 return NULL;
1334 if (PyList_Sort(sorted)) {
1335 Py_DECREF(sorted);
1336 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001338 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001339}
1340
1341/* Implementation of dir() -- if obj is NULL, returns the names in the current
1342 (local) scope. Otherwise, performs introspection of the object: returns a
1343 sorted list of attribute names (supposedly) accessible from the object
1344*/
1345PyObject *
1346PyObject_Dir(PyObject *obj)
1347{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001348 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001349}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001350
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001351/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001352None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001353There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001354so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001355*/
1356
Guido van Rossum0c182a11992-03-27 17:26:13 +00001357/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001358static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001359none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001362}
1363
Barry Warsaw9bf16442001-01-23 16:24:35 +00001364/* ARGUSED */
1365static void
Tim Peters803526b2002-07-07 05:13:56 +00001366none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* This should never get called, but we also don't want to SEGV if
1369 * we accidentally decref None out of existence.
1370 */
1371 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001372}
1373
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001374static PyObject *
1375none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1376{
1377 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1378 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1379 return NULL;
1380 }
1381 Py_RETURN_NONE;
1382}
1383
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001384static int
1385none_bool(PyObject *v)
1386{
1387 return 0;
1388}
1389
1390static PyNumberMethods none_as_number = {
1391 0, /* nb_add */
1392 0, /* nb_subtract */
1393 0, /* nb_multiply */
1394 0, /* nb_remainder */
1395 0, /* nb_divmod */
1396 0, /* nb_power */
1397 0, /* nb_negative */
1398 0, /* nb_positive */
1399 0, /* nb_absolute */
1400 (inquiry)none_bool, /* nb_bool */
1401 0, /* nb_invert */
1402 0, /* nb_lshift */
1403 0, /* nb_rshift */
1404 0, /* nb_and */
1405 0, /* nb_xor */
1406 0, /* nb_or */
1407 0, /* nb_int */
1408 0, /* nb_reserved */
1409 0, /* nb_float */
1410 0, /* nb_inplace_add */
1411 0, /* nb_inplace_subtract */
1412 0, /* nb_inplace_multiply */
1413 0, /* nb_inplace_remainder */
1414 0, /* nb_inplace_power */
1415 0, /* nb_inplace_lshift */
1416 0, /* nb_inplace_rshift */
1417 0, /* nb_inplace_and */
1418 0, /* nb_inplace_xor */
1419 0, /* nb_inplace_or */
1420 0, /* nb_floor_divide */
1421 0, /* nb_true_divide */
1422 0, /* nb_inplace_floor_divide */
1423 0, /* nb_inplace_true_divide */
1424 0, /* nb_index */
1425};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001426
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001427PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1429 "NoneType",
1430 0,
1431 0,
1432 none_dealloc, /*tp_dealloc*/ /*never called*/
1433 0, /*tp_print*/
1434 0, /*tp_getattr*/
1435 0, /*tp_setattr*/
1436 0, /*tp_reserved*/
1437 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001438 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 0, /*tp_as_sequence*/
1440 0, /*tp_as_mapping*/
1441 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001442 0, /*tp_call */
1443 0, /*tp_str */
1444 0, /*tp_getattro */
1445 0, /*tp_setattro */
1446 0, /*tp_as_buffer */
1447 Py_TPFLAGS_DEFAULT, /*tp_flags */
1448 0, /*tp_doc */
1449 0, /*tp_traverse */
1450 0, /*tp_clear */
1451 0, /*tp_richcompare */
1452 0, /*tp_weaklistoffset */
1453 0, /*tp_iter */
1454 0, /*tp_iternext */
1455 0, /*tp_methods */
1456 0, /*tp_members */
1457 0, /*tp_getset */
1458 0, /*tp_base */
1459 0, /*tp_dict */
1460 0, /*tp_descr_get */
1461 0, /*tp_descr_set */
1462 0, /*tp_dictoffset */
1463 0, /*tp_init */
1464 0, /*tp_alloc */
1465 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001466};
1467
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001468PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001469 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001470 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001471};
1472
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001473/* NotImplemented is an object that can be used to signal that an
1474 operation is not implemented for the given type combination. */
1475
1476static PyObject *
1477NotImplemented_repr(PyObject *op)
1478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001480}
1481
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001482static PyObject *
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001483NotImplemented_reduce(PyObject *op)
1484{
1485 return PyUnicode_FromString("NotImplemented");
1486}
1487
1488static PyMethodDef notimplemented_methods[] = {
1489 {"__reduce__", (PyCFunction)NotImplemented_reduce, METH_NOARGS, NULL},
1490 {NULL, NULL}
1491};
1492
1493static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001494notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1495{
1496 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1497 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1498 return NULL;
1499 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001500 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001501}
1502
Armin Ronacher226b1db2012-10-06 14:28:58 +02001503static void
1504notimplemented_dealloc(PyObject* ignore)
1505{
1506 /* This should never get called, but we also don't want to SEGV if
1507 * we accidentally decref NotImplemented out of existence.
1508 */
1509 Py_FatalError("deallocating NotImplemented");
1510}
1511
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001512PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1514 "NotImplementedType",
1515 0,
1516 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001517 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 0, /*tp_print*/
1519 0, /*tp_getattr*/
1520 0, /*tp_setattr*/
1521 0, /*tp_reserved*/
1522 NotImplemented_repr, /*tp_repr*/
1523 0, /*tp_as_number*/
1524 0, /*tp_as_sequence*/
1525 0, /*tp_as_mapping*/
1526 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001527 0, /*tp_call */
1528 0, /*tp_str */
1529 0, /*tp_getattro */
1530 0, /*tp_setattro */
1531 0, /*tp_as_buffer */
1532 Py_TPFLAGS_DEFAULT, /*tp_flags */
1533 0, /*tp_doc */
1534 0, /*tp_traverse */
1535 0, /*tp_clear */
1536 0, /*tp_richcompare */
1537 0, /*tp_weaklistoffset */
1538 0, /*tp_iter */
1539 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001540 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001541 0, /*tp_members */
1542 0, /*tp_getset */
1543 0, /*tp_base */
1544 0, /*tp_dict */
1545 0, /*tp_descr_get */
1546 0, /*tp_descr_set */
1547 0, /*tp_dictoffset */
1548 0, /*tp_init */
1549 0, /*tp_alloc */
1550 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001551};
1552
1553PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001555 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001556};
1557
Guido van Rossumba21a492001-08-16 08:17:26 +00001558void
1559_Py_ReadyTypes(void)
1560{
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001561 if (PyType_Ready(&PyBaseObject_Type) < 0)
1562 Py_FatalError("Can't initialize object type");
1563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 if (PyType_Ready(&PyType_Type) < 0)
1565 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1568 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1571 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1574 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001575
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001576 if (PyType_Ready(&PyLong_Type) < 0)
1577 Py_FatalError("Can't initialize int type");
1578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 if (PyType_Ready(&PyBool_Type) < 0)
1580 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 if (PyType_Ready(&PyByteArray_Type) < 0)
1583 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 if (PyType_Ready(&PyBytes_Type) < 0)
1586 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (PyType_Ready(&PyList_Type) < 0)
1589 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001590
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001591 if (PyType_Ready(&_PyNone_Type) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001593
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001594 if (PyType_Ready(&_PyNotImplemented_Type) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 if (PyType_Ready(&PyTraceBack_Type) < 0)
1598 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 if (PyType_Ready(&PySuper_Type) < 0)
1601 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (PyType_Ready(&PyRange_Type) < 0)
1604 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (PyType_Ready(&PyDict_Type) < 0)
1607 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001608
Eric Snow96c6af92015-05-29 22:21:39 -06001609 if (PyType_Ready(&PyODict_Type) < 0)
1610 Py_FatalError("Can't initialize OrderedDict type");
1611
1612 if (PyType_Ready(&PyODictKeys_Type) < 0)
1613 Py_FatalError("Can't initialize odict_keys type");
1614
1615 if (PyType_Ready(&PyODictItems_Type) < 0)
1616 Py_FatalError("Can't initialize odict_items type");
1617
1618 if (PyType_Ready(&PyODictValues_Type) < 0)
1619 Py_FatalError("Can't initialize odict_values type");
1620
1621 if (PyType_Ready(&PyODictIter_Type) < 0)
1622 Py_FatalError("Can't initialize odict_keyiterator type");
1623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (PyType_Ready(&PySet_Type) < 0)
1625 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (PyType_Ready(&PyUnicode_Type) < 0)
1628 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 if (PyType_Ready(&PySlice_Type) < 0)
1631 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1634 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (PyType_Ready(&PyComplex_Type) < 0)
1637 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (PyType_Ready(&PyFloat_Type) < 0)
1640 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1643 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 if (PyType_Ready(&PyProperty_Type) < 0)
1646 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001647
Stefan Krah9a2d99e2012-02-25 12:24:21 +01001648 if (PyType_Ready(&_PyManagedBuffer_Type) < 0)
1649 Py_FatalError("Can't initialize managed buffer type");
1650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 if (PyType_Ready(&PyMemoryView_Type) < 0)
1652 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 if (PyType_Ready(&PyTuple_Type) < 0)
1655 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 if (PyType_Ready(&PyEnum_Type) < 0)
1658 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 if (PyType_Ready(&PyReversed_Type) < 0)
1661 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1664 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 if (PyType_Ready(&PyCode_Type) < 0)
1667 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (PyType_Ready(&PyFrame_Type) < 0)
1670 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (PyType_Ready(&PyCFunction_Type) < 0)
1673 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (PyType_Ready(&PyMethod_Type) < 0)
1676 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (PyType_Ready(&PyFunction_Type) < 0)
1679 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (PyType_Ready(&PyDictProxy_Type) < 0)
1682 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (PyType_Ready(&PyGen_Type) < 0)
1685 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1688 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1691 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001692
Benjamin Petersoneff61f62011-09-01 16:32:31 -04001693 if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1694 Py_FatalError("Can't initialize method wrapper type");
1695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (PyType_Ready(&PyEllipsis_Type) < 0)
1697 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1700 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001701
Barry Warsaw409da152012-06-03 16:18:47 -04001702 if (PyType_Ready(&_PyNamespace_Type) < 0)
1703 Py_FatalError("Can't initialize namespace type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -04001704
Benjamin Petersonc4311282012-10-30 23:21:10 -04001705 if (PyType_Ready(&PyCapsule_Type) < 0)
1706 Py_FatalError("Can't initialize capsule type");
1707
1708 if (PyType_Ready(&PyLongRangeIter_Type) < 0)
1709 Py_FatalError("Can't initialize long range iterator type");
1710
1711 if (PyType_Ready(&PyCell_Type) < 0)
1712 Py_FatalError("Can't initialize cell type");
1713
1714 if (PyType_Ready(&PyInstanceMethod_Type) < 0)
1715 Py_FatalError("Can't initialize instance method type");
1716
1717 if (PyType_Ready(&PyClassMethodDescr_Type) < 0)
1718 Py_FatalError("Can't initialize class method descr type");
1719
1720 if (PyType_Ready(&PyMethodDescr_Type) < 0)
1721 Py_FatalError("Can't initialize method descr type");
1722
1723 if (PyType_Ready(&PyCallIter_Type) < 0)
1724 Py_FatalError("Can't initialize call iter type");
1725
1726 if (PyType_Ready(&PySeqIter_Type) < 0)
1727 Py_FatalError("Can't initialize sequence iterator type");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001728
1729 if (PyType_Ready(&PyCoro_Type) < 0)
1730 Py_FatalError("Can't initialize coroutine type");
1731
1732 if (PyType_Ready(&_PyCoroWrapper_Type) < 0)
1733 Py_FatalError("Can't initialize coroutine wrapper type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001734}
1735
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001736
Guido van Rossum84a90321996-05-22 16:34:47 +00001737#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001738
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001739void
Fred Drake100814d2000-07-09 15:48:49 +00001740_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 _Py_INC_REFTOTAL;
1743 op->ob_refcnt = 1;
1744 _Py_AddToAllObjects(op, 1);
1745 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001746}
1747
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001748void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001749_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001750{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001751#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001752 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001753#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (op->ob_refcnt < 0)
1755 Py_FatalError("UNREF negative refcnt");
1756 if (op == &refchain ||
1757 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1758 fprintf(stderr, "* ob\n");
1759 _PyObject_Dump(op);
1760 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1761 _PyObject_Dump(op->_ob_prev->_ob_next);
1762 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1763 _PyObject_Dump(op->_ob_next->_ob_prev);
1764 Py_FatalError("UNREF invalid object");
1765 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001766#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1768 if (p == op)
1769 break;
1770 }
1771 if (p == &refchain) /* Not found */
1772 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001773#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 op->_ob_next->_ob_prev = op->_ob_prev;
1775 op->_ob_prev->_ob_next = op->_ob_next;
1776 op->_ob_next = op->_ob_prev = NULL;
1777 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001778}
1779
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001780void
Fred Drake100814d2000-07-09 15:48:49 +00001781_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1784 _Py_ForgetReference(op);
1785 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001786}
1787
Tim Peters269b2a62003-04-17 19:52:29 +00001788/* Print all live objects. Because PyObject_Print is called, the
1789 * interpreter must be in a healthy state.
1790 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001791void
Fred Drake100814d2000-07-09 15:48:49 +00001792_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyObject *op;
1795 fprintf(fp, "Remaining objects:\n");
1796 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1797 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1798 if (PyObject_Print(op, fp, 0) != 0)
1799 PyErr_Clear();
1800 putc('\n', fp);
1801 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001802}
1803
Tim Peters269b2a62003-04-17 19:52:29 +00001804/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1805 * doesn't make any calls to the Python C API, so is always safe to call.
1806 */
1807void
1808_Py_PrintReferenceAddresses(FILE *fp)
1809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 PyObject *op;
1811 fprintf(fp, "Remaining object addresses:\n");
1812 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1813 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1814 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001815}
1816
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001817PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001818_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 int i, n;
1821 PyObject *t = NULL;
1822 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1825 return NULL;
1826 op = refchain._ob_next;
1827 res = PyList_New(0);
1828 if (res == NULL)
1829 return NULL;
1830 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1831 while (op == self || op == args || op == res || op == t ||
1832 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1833 op = op->_ob_next;
1834 if (op == &refchain)
1835 return res;
1836 }
1837 if (PyList_Append(res, op) < 0) {
1838 Py_DECREF(res);
1839 return NULL;
1840 }
1841 op = op->_ob_next;
1842 }
1843 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001844}
1845
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001847
Benjamin Petersonb173f782009-05-05 22:31:58 +00001848
Guido van Rossum84a90321996-05-22 16:34:47 +00001849/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001850Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001851
1852
David Malcolm49526f42012-06-22 14:55:41 -04001853void
1854_PyObject_DebugTypeStats(FILE *out)
1855{
1856 _PyCFunction_DebugMallocStats(out);
1857 _PyDict_DebugMallocStats(out);
1858 _PyFloat_DebugMallocStats(out);
1859 _PyFrame_DebugMallocStats(out);
1860 _PyList_DebugMallocStats(out);
1861 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001862 _PyTuple_DebugMallocStats(out);
1863}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001864
Guido van Rossum86610361998-04-10 22:32:46 +00001865/* These methods are used to control infinite recursion in repr, str, print,
1866 etc. Container objects that may recursively contain themselves,
1867 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1868 Py_ReprLeave() to avoid infinite recursion.
1869
1870 Py_ReprEnter() returns 0 the first time it is called for a particular
1871 object and 1 every time thereafter. It returns -1 if an exception
1872 occurred. Py_ReprLeave() has no return value.
1873
1874 See dictobject.c and listobject.c for examples of use.
1875*/
1876
Guido van Rossum86610361998-04-10 22:32:46 +00001877int
Fred Drake100814d2000-07-09 15:48:49 +00001878Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 PyObject *dict;
1881 PyObject *list;
1882 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02001885 /* Ignore a missing thread-state, so that this function can be called
1886 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (dict == NULL)
1888 return 0;
Victor Stinner7a07e452013-11-06 18:57:29 +01001889 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 if (list == NULL) {
1891 list = PyList_New(0);
1892 if (list == NULL)
1893 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01001894 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 return -1;
1896 Py_DECREF(list);
1897 }
1898 i = PyList_GET_SIZE(list);
1899 while (--i >= 0) {
1900 if (PyList_GET_ITEM(list, i) == obj)
1901 return 1;
1902 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02001903 if (PyList_Append(list, obj) < 0)
1904 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001906}
1907
1908void
Fred Drake100814d2000-07-09 15:48:49 +00001909Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 PyObject *dict;
1912 PyObject *list;
1913 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02001914 PyObject *error_type, *error_value, *error_traceback;
1915
1916 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 dict = PyThreadState_GetDict();
1919 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02001920 goto finally;
1921
Victor Stinner7a07e452013-11-06 18:57:29 +01001922 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02001924 goto finally;
1925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 i = PyList_GET_SIZE(list);
1927 /* Count backwards because we always expect obj to be list[-1] */
1928 while (--i >= 0) {
1929 if (PyList_GET_ITEM(list, i) == obj) {
1930 PyList_SetSlice(list, i, i + 1, NULL);
1931 break;
1932 }
1933 }
Victor Stinner1b634932013-07-16 22:24:44 +02001934
1935finally:
1936 /* ignore exceptions because there is no way to report them. */
1937 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00001938}
Guido van Rossumd724b232000-03-13 16:01:29 +00001939
Tim Peters803526b2002-07-07 05:13:56 +00001940/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001941
Tim Peters803526b2002-07-07 05:13:56 +00001942/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001943int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001944
Tim Peters803526b2002-07-07 05:13:56 +00001945/* List of objects that still need to be cleaned up, singly linked via their
1946 * gc headers' gc_prev pointers.
1947 */
1948PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001949
Tim Peters803526b2002-07-07 05:13:56 +00001950/* Add op to the _PyTrash_delete_later list. Called when the current
1951 * call-stack depth gets large. op must be a currently untracked gc'ed
1952 * object, with refcount 0. Py_DECREF must already have been called on it.
1953 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001954void
Fred Drake100814d2000-07-09 15:48:49 +00001955_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 assert(PyObject_IS_GC(op));
Antoine Pitrou796564c2013-07-30 19:59:21 +02001958 assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 assert(op->ob_refcnt == 0);
1960 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
1961 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001962}
1963
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02001964/* The equivalent API, using per-thread state recursion info */
1965void
1966_PyTrash_thread_deposit_object(PyObject *op)
1967{
1968 PyThreadState *tstate = PyThreadState_GET();
1969 assert(PyObject_IS_GC(op));
Antoine Pitrou796564c2013-07-30 19:59:21 +02001970 assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02001971 assert(op->ob_refcnt == 0);
1972 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *) tstate->trash_delete_later;
1973 tstate->trash_delete_later = op;
1974}
1975
Tim Peters803526b2002-07-07 05:13:56 +00001976/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1977 * the call-stack unwinds again.
1978 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001979void
Fred Drake100814d2000-07-09 15:48:49 +00001980_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 while (_PyTrash_delete_later) {
1983 PyObject *op = _PyTrash_delete_later;
1984 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 _PyTrash_delete_later =
1987 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 /* Call the deallocator directly. This used to try to
1990 * fool Py_DECREF into calling it indirectly, but
1991 * Py_DECREF was already called on this object, and in
1992 * assorted non-release builds calling Py_DECREF again ends
1993 * up distorting allocation statistics.
1994 */
1995 assert(op->ob_refcnt == 0);
1996 ++_PyTrash_delete_nesting;
1997 (*dealloc)(op);
1998 --_PyTrash_delete_nesting;
1999 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002000}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002001
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002002/* The equivalent API, using per-thread state recursion info */
2003void
2004_PyTrash_thread_destroy_chain(void)
2005{
2006 PyThreadState *tstate = PyThreadState_GET();
2007 while (tstate->trash_delete_later) {
2008 PyObject *op = tstate->trash_delete_later;
2009 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2010
2011 tstate->trash_delete_later =
2012 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
2013
2014 /* Call the deallocator directly. This used to try to
2015 * fool Py_DECREF into calling it indirectly, but
2016 * Py_DECREF was already called on this object, and in
2017 * assorted non-release builds calling Py_DECREF again ends
2018 * up distorting allocation statistics.
2019 */
2020 assert(op->ob_refcnt == 0);
2021 ++tstate->trash_delete_nesting;
2022 (*dealloc)(op);
2023 --tstate->trash_delete_nesting;
2024 }
2025}
2026
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002027#ifndef Py_TRACE_REFS
2028/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
2029 Define this here, so we can undefine the macro. */
2030#undef _Py_Dealloc
2031PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
2032void
2033_Py_Dealloc(PyObject *op)
2034{
2035 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
2036 (*Py_TYPE(op)->tp_dealloc)(op);
2037}
2038#endif
2039
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002040#ifdef __cplusplus
2041}
2042#endif