blob: 4f61d1e710a10e2fd5f54cf7b286a0981fbbbed9 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Victor Stinnerbd303c12013-11-07 23:07:29 +010035_Py_IDENTIFIER(__builtins__);
36_Py_IDENTIFIER(__dict__);
37_Py_IDENTIFIER(__prepare__);
38_Py_IDENTIFIER(__round__);
39_Py_IDENTIFIER(encoding);
40_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020041_Py_IDENTIFIER(fileno);
42_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010043_Py_IDENTIFIER(metaclass);
44_Py_IDENTIFIER(sort);
45_Py_IDENTIFIER(stdin);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020048
Nick Coghlanf9e227e2014-08-17 14:01:19 +100049/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000050static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000051builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
52{
Nick Coghlande31b192011-10-23 22:04:16 +100053 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020055 Py_ssize_t nargs;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010056 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 assert(args != NULL);
59 if (!PyTuple_Check(args)) {
60 PyErr_SetString(PyExc_TypeError,
61 "__build_class__: args is not a tuple");
62 return NULL;
63 }
64 nargs = PyTuple_GET_SIZE(args);
65 if (nargs < 2) {
66 PyErr_SetString(PyExc_TypeError,
67 "__build_class__: not enough arguments");
68 return NULL;
69 }
70 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050071 if (!PyFunction_Check(func)) {
72 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050073 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050074 return NULL;
75 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 name = PyTuple_GET_ITEM(args, 1);
77 if (!PyUnicode_Check(name)) {
78 PyErr_SetString(PyExc_TypeError,
79 "__build_class__: name is not a string");
80 return NULL;
81 }
82 bases = PyTuple_GetSlice(args, 2, nargs);
83 if (bases == NULL)
84 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 if (kwds == NULL) {
87 meta = NULL;
88 mkw = NULL;
89 }
90 else {
91 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
92 if (mkw == NULL) {
93 Py_DECREF(bases);
94 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000095 }
Victor Stinnerae9f1612013-11-06 22:46:51 +010096 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 if (meta != NULL) {
98 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010099 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 Py_DECREF(meta);
101 Py_DECREF(mkw);
102 Py_DECREF(bases);
103 return NULL;
104 }
Nick Coghlande31b192011-10-23 22:04:16 +1000105 /* metaclass is explicitly given, check if it's indeed a class */
106 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 }
108 }
109 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000110 /* if there are no bases, use type: */
111 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000113 }
114 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 else {
116 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
117 meta = (PyObject *) (base0->ob_type);
118 }
119 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000120 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000122
Nick Coghlande31b192011-10-23 22:04:16 +1000123 if (isclass) {
124 /* meta is really a class, so check for a more derived
125 metaclass, or possible metaclass conflicts: */
126 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
127 bases);
128 if (winner == NULL) {
129 Py_DECREF(meta);
130 Py_XDECREF(mkw);
131 Py_DECREF(bases);
132 return NULL;
133 }
134 if (winner != meta) {
135 Py_DECREF(meta);
136 meta = winner;
137 Py_INCREF(meta);
138 }
139 }
140 /* else: meta is not a class, so we cannot do the metaclass
141 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200142 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (prep == NULL) {
144 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
145 PyErr_Clear();
146 ns = PyDict_New();
147 }
148 else {
149 Py_DECREF(meta);
150 Py_XDECREF(mkw);
151 Py_DECREF(bases);
152 return NULL;
153 }
154 }
155 else {
156 PyObject *pargs = PyTuple_Pack(2, name, bases);
157 if (pargs == NULL) {
158 Py_DECREF(prep);
159 Py_DECREF(meta);
160 Py_XDECREF(mkw);
161 Py_DECREF(bases);
162 return NULL;
163 }
164 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
165 Py_DECREF(pargs);
166 Py_DECREF(prep);
167 }
168 if (ns == NULL) {
169 Py_DECREF(meta);
170 Py_XDECREF(mkw);
171 Py_DECREF(bases);
172 return NULL;
173 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500174 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
175 NULL, 0, NULL, 0, NULL, 0, NULL,
176 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (cell != NULL) {
178 PyObject *margs;
179 margs = PyTuple_Pack(3, name, bases, ns);
180 if (margs != NULL) {
181 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
182 Py_DECREF(margs);
183 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700184 if (cls != NULL && PyCell_Check(cell))
185 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 Py_DECREF(cell);
187 }
188 Py_DECREF(ns);
189 Py_DECREF(meta);
190 Py_XDECREF(mkw);
191 Py_DECREF(bases);
192 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000193}
194
195PyDoc_STRVAR(build_class_doc,
196"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
197\n\
198Internal helper function used by the class statement.");
199
200static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000201builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
204 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400205 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400206 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000207
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400208 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 kwlist, &name, &globals, &locals, &fromlist, &level))
210 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400211 return PyImport_ImportModuleLevelObject(name, globals, locals,
212 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000213}
214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000215PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400216"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000217\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000218Import a module. Because this function is meant for use by the Python\n\
219interpreter and not for general use it is better to use\n\
220importlib.import_module() to programmatically import a module.\n\
221\n\
222The globals argument is only used to determine the context;\n\
223they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000224should be a list of names to emulate ``from name import ...'', or an\n\
225empty list to emulate ``import name''.\n\
226When importing a module from a package, note that __import__('A.B', ...)\n\
227returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000228fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400229absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000230is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000231
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000232
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000233/*[clinic input]
234abs as builtin_abs
235
236 x: 'O'
237 /
238
239Return the absolute value of the argument.
240[clinic start generated code]*/
241
242PyDoc_STRVAR(builtin_abs__doc__,
243"abs($module, x, /)\n"
244"--\n"
245"\n"
246"Return the absolute value of the argument.");
247
248#define BUILTIN_ABS_METHODDEF \
249 {"abs", (PyCFunction)builtin_abs, METH_O, builtin_abs__doc__},
250
Guido van Rossum79f25d91997-04-29 20:08:16 +0000251static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000252builtin_abs(PyModuleDef *module, PyObject *x)
253/*[clinic end generated code: output=f85095528ce7e2e5 input=aa29cc07869b4732]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000254{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000255 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000256}
257
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000258/*[clinic input]
259all as builtin_all
260
261 iterable: 'O'
262 /
263
264Return True if bool(x) is True for all values x in the iterable.
265
266If the iterable is empty, return True.
267[clinic start generated code]*/
268
269PyDoc_STRVAR(builtin_all__doc__,
270"all($module, iterable, /)\n"
271"--\n"
272"\n"
273"Return True if bool(x) is True for all values x in the iterable.\n"
274"\n"
275"If the iterable is empty, return True.");
276
277#define BUILTIN_ALL_METHODDEF \
278 {"all", (PyCFunction)builtin_all, METH_O, builtin_all__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000279
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000281builtin_all(PyModuleDef *module, PyObject *iterable)
282/*[clinic end generated code: output=d001db739ba83b46 input=dd506dc9998d42bd]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 PyObject *it, *item;
285 PyObject *(*iternext)(PyObject *);
286 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000287
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000288 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 if (it == NULL)
290 return NULL;
291 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 for (;;) {
294 item = iternext(it);
295 if (item == NULL)
296 break;
297 cmp = PyObject_IsTrue(item);
298 Py_DECREF(item);
299 if (cmp < 0) {
300 Py_DECREF(it);
301 return NULL;
302 }
303 if (cmp == 0) {
304 Py_DECREF(it);
305 Py_RETURN_FALSE;
306 }
307 }
308 Py_DECREF(it);
309 if (PyErr_Occurred()) {
310 if (PyErr_ExceptionMatches(PyExc_StopIteration))
311 PyErr_Clear();
312 else
313 return NULL;
314 }
315 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000316}
317
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000318/*[clinic input]
319any as builtin_any
320
321 iterable: 'O'
322 /
323
324Return True if bool(x) is True for any x in the iterable.
325
326If the iterable is empty, return False.
327[clinic start generated code]*/
328
329PyDoc_STRVAR(builtin_any__doc__,
330"any($module, iterable, /)\n"
331"--\n"
332"\n"
333"Return True if bool(x) is True for any x in the iterable.\n"
334"\n"
335"If the iterable is empty, return False.");
336
337#define BUILTIN_ANY_METHODDEF \
338 {"any", (PyCFunction)builtin_any, METH_O, builtin_any__doc__},
Raymond Hettinger96229b12005-03-11 06:49:40 +0000339
340static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000341builtin_any(PyModuleDef *module, PyObject *iterable)
342/*[clinic end generated code: output=3a4b6dbe6a0d6f61 input=8fe8460f3fbbced8]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 PyObject *it, *item;
345 PyObject *(*iternext)(PyObject *);
346 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000347
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000348 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 if (it == NULL)
350 return NULL;
351 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 for (;;) {
354 item = iternext(it);
355 if (item == NULL)
356 break;
357 cmp = PyObject_IsTrue(item);
358 Py_DECREF(item);
359 if (cmp < 0) {
360 Py_DECREF(it);
361 return NULL;
362 }
363 if (cmp == 1) {
364 Py_DECREF(it);
365 Py_RETURN_TRUE;
366 }
367 }
368 Py_DECREF(it);
369 if (PyErr_Occurred()) {
370 if (PyErr_ExceptionMatches(PyExc_StopIteration))
371 PyErr_Clear();
372 else
373 return NULL;
374 }
375 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000376}
377
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000378/*[clinic input]
379ascii as builtin_ascii
380
381 obj: 'O'
382 /
383
384Return an ASCII-only representation of an object.
385
386As repr(), return a string containing a printable representation of an
387object, but escape the non-ASCII characters in the string returned by
388repr() using \\x, \\u or \\U escapes. This generates a string similar
389to that returned by repr() in Python 2.
390[clinic start generated code]*/
391
392PyDoc_STRVAR(builtin_ascii__doc__,
393"ascii($module, obj, /)\n"
394"--\n"
395"\n"
396"Return an ASCII-only representation of an object.\n"
397"\n"
398"As repr(), return a string containing a printable representation of an\n"
399"object, but escape the non-ASCII characters in the string returned by\n"
400"repr() using \\\\x, \\\\u or \\\\U escapes. This generates a string similar\n"
401"to that returned by repr() in Python 2.");
402
403#define BUILTIN_ASCII_METHODDEF \
404 {"ascii", (PyCFunction)builtin_ascii, METH_O, builtin_ascii__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000405
Georg Brandl559e5d72008-06-11 18:37:52 +0000406static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000407builtin_ascii(PyModuleDef *module, PyObject *obj)
408/*[clinic end generated code: output=f0e6754154c2d30b input=0cbdc1420a306325]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000409{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000410 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000411}
412
Georg Brandl559e5d72008-06-11 18:37:52 +0000413
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000414/*[clinic input]
415bin as builtin_bin
416
417 number: 'O'
418 /
419
420Return the binary representation of an integer.
421
422 >>> bin(2796202)
423 '0b1010101010101010101010'
424[clinic start generated code]*/
425
426PyDoc_STRVAR(builtin_bin__doc__,
427"bin($module, number, /)\n"
428"--\n"
429"\n"
430"Return the binary representation of an integer.\n"
431"\n"
432" >>> bin(2796202)\n"
433" \'0b1010101010101010101010\'");
434
435#define BUILTIN_BIN_METHODDEF \
436 {"bin", (PyCFunction)builtin_bin, METH_O, builtin_bin__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000437
Guido van Rossum79f25d91997-04-29 20:08:16 +0000438static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000439builtin_bin(PyModuleDef *module, PyObject *number)
440/*[clinic end generated code: output=18fed0e943650da1 input=2a6362ae9a9c9203]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000441{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000442 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000443}
444
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000445
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000446/*[clinic input]
447callable as builtin_callable
448
449 obj: 'O'
450 /
451
452Return whether the object is callable (i.e., some kind of function).
453
454Note that classes are callable, as are instances of classes with a
455__call__() method.
456[clinic start generated code]*/
457
458PyDoc_STRVAR(builtin_callable__doc__,
459"callable($module, obj, /)\n"
460"--\n"
461"\n"
462"Return whether the object is callable (i.e., some kind of function).\n"
463"\n"
464"Note that classes are callable, as are instances of classes with a\n"
465"__call__() method.");
466
467#define BUILTIN_CALLABLE_METHODDEF \
468 {"callable", (PyCFunction)builtin_callable, METH_O, builtin_callable__doc__},
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000469
Antoine Pitroue71362d2010-11-27 22:00:11 +0000470static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000471builtin_callable(PyModuleDef *module, PyObject *obj)
472/*[clinic end generated code: output=b3a92cbe635f32af input=bb3bb528fffdade4]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000473{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000474 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000475}
476
Antoine Pitroue71362d2010-11-27 22:00:11 +0000477
Raymond Hettinger17301e92008-03-13 00:19:26 +0000478typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyObject_HEAD
480 PyObject *func;
481 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000482} filterobject;
483
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000484static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000485filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PyObject *func, *seq;
488 PyObject *it;
489 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
492 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
495 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 /* Get iterator. */
498 it = PyObject_GetIter(seq);
499 if (it == NULL)
500 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 /* create filterobject structure */
503 lz = (filterobject *)type->tp_alloc(type, 0);
504 if (lz == NULL) {
505 Py_DECREF(it);
506 return NULL;
507 }
508 Py_INCREF(func);
509 lz->func = func;
510 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000513}
514
515static void
516filter_dealloc(filterobject *lz)
517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 PyObject_GC_UnTrack(lz);
519 Py_XDECREF(lz->func);
520 Py_XDECREF(lz->it);
521 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000522}
523
524static int
525filter_traverse(filterobject *lz, visitproc visit, void *arg)
526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 Py_VISIT(lz->it);
528 Py_VISIT(lz->func);
529 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000530}
531
532static PyObject *
533filter_next(filterobject *lz)
534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 PyObject *item;
536 PyObject *it = lz->it;
537 long ok;
538 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 iternext = *Py_TYPE(it)->tp_iternext;
541 for (;;) {
542 item = iternext(it);
543 if (item == NULL)
544 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
547 ok = PyObject_IsTrue(item);
548 } else {
549 PyObject *good;
550 good = PyObject_CallFunctionObjArgs(lz->func,
551 item, NULL);
552 if (good == NULL) {
553 Py_DECREF(item);
554 return NULL;
555 }
556 ok = PyObject_IsTrue(good);
557 Py_DECREF(good);
558 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200559 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return item;
561 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200562 if (ok < 0)
563 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000565}
566
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000567static PyObject *
568filter_reduce(filterobject *lz)
569{
570 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
571}
572
573PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
574
575static PyMethodDef filter_methods[] = {
576 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
577 {NULL, NULL} /* sentinel */
578};
579
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000580PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000581"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000582\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000583Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000584is true. If function is None, return the items that are true.");
585
586PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 PyVarObject_HEAD_INIT(&PyType_Type, 0)
588 "filter", /* tp_name */
589 sizeof(filterobject), /* tp_basicsize */
590 0, /* tp_itemsize */
591 /* methods */
592 (destructor)filter_dealloc, /* tp_dealloc */
593 0, /* tp_print */
594 0, /* tp_getattr */
595 0, /* tp_setattr */
596 0, /* tp_reserved */
597 0, /* tp_repr */
598 0, /* tp_as_number */
599 0, /* tp_as_sequence */
600 0, /* tp_as_mapping */
601 0, /* tp_hash */
602 0, /* tp_call */
603 0, /* tp_str */
604 PyObject_GenericGetAttr, /* tp_getattro */
605 0, /* tp_setattro */
606 0, /* tp_as_buffer */
607 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
608 Py_TPFLAGS_BASETYPE, /* tp_flags */
609 filter_doc, /* tp_doc */
610 (traverseproc)filter_traverse, /* tp_traverse */
611 0, /* tp_clear */
612 0, /* tp_richcompare */
613 0, /* tp_weaklistoffset */
614 PyObject_SelfIter, /* tp_iter */
615 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000616 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 0, /* tp_members */
618 0, /* tp_getset */
619 0, /* tp_base */
620 0, /* tp_dict */
621 0, /* tp_descr_get */
622 0, /* tp_descr_set */
623 0, /* tp_dictoffset */
624 0, /* tp_init */
625 PyType_GenericAlloc, /* tp_alloc */
626 filter_new, /* tp_new */
627 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000628};
629
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000630
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000631/*[clinic input]
632format as builtin_format
633
634 value: 'O'
635 format_spec: unicode(c_default="NULL") = ''
636 /
637
638Return value.__format__(format_spec)
639
640format_spec defaults to the empty string
641[clinic start generated code]*/
642
643PyDoc_STRVAR(builtin_format__doc__,
644"format($module, value, format_spec=\'\', /)\n"
645"--\n"
646"\n"
647"Return value.__format__(format_spec)\n"
648"\n"
649"format_spec defaults to the empty string");
650
651#define BUILTIN_FORMAT_METHODDEF \
652 {"format", (PyCFunction)builtin_format, METH_VARARGS, builtin_format__doc__},
653
Eric Smith8c663262007-08-25 02:26:07 +0000654static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000655builtin_format_impl(PyModuleDef *module, PyObject *value, PyObject *format_spec);
656
657static PyObject *
658builtin_format(PyModuleDef *module, PyObject *args)
Eric Smith8c663262007-08-25 02:26:07 +0000659{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000660 PyObject *return_value = NULL;
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000661 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000662 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000663
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000664 if (!PyArg_ParseTuple(args,
665 "O|U:format",
666 &value, &format_spec))
667 goto exit;
668 return_value = builtin_format_impl(module, value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000669
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000670exit:
671 return return_value;
672}
673
674static PyObject *
675builtin_format_impl(PyModuleDef *module, PyObject *value, PyObject *format_spec)
676/*[clinic end generated code: output=39723a58c72e8871 input=e23f2f11e0098c64]*/
677{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000678 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000679}
680
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000681/*[clinic input]
682chr as builtin_chr
683
684 i: 'i'
685 /
686
687Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
688[clinic start generated code]*/
689
690PyDoc_STRVAR(builtin_chr__doc__,
691"chr($module, i, /)\n"
692"--\n"
693"\n"
694"Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
695
696#define BUILTIN_CHR_METHODDEF \
697 {"chr", (PyCFunction)builtin_chr, METH_VARARGS, builtin_chr__doc__},
Eric Smith81936692007-08-31 01:14:01 +0000698
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000699static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000700builtin_chr_impl(PyModuleDef *module, int i);
701
702static PyObject *
703builtin_chr(PyModuleDef *module, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000704{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000705 PyObject *return_value = NULL;
706 int i;
Guido van Rossum09095f32000-03-10 23:00:52 +0000707
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000708 if (!PyArg_ParseTuple(args,
709 "i:chr",
710 &i))
711 goto exit;
712 return_value = builtin_chr_impl(module, i);
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000713
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000714exit:
715 return return_value;
Guido van Rossum09095f32000-03-10 23:00:52 +0000716}
717
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000718static PyObject *
719builtin_chr_impl(PyModuleDef *module, int i)
720/*[clinic end generated code: output=4d6bbe948f56e2ae input=9b1ced29615adf66]*/
721{
722 return PyUnicode_FromOrdinal(i);
723}
Guido van Rossum09095f32000-03-10 23:00:52 +0000724
725
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200726static const char *
727source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, Py_buffer *view)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000728{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200729 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (PyUnicode_Check(cmd)) {
733 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200734 str = PyUnicode_AsUTF8AndSize(cmd, &size);
735 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return NULL;
737 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200738 else if (PyObject_GetBuffer(cmd, view, PyBUF_SIMPLE) == 0) {
739 str = (const char *)view->buf;
740 size = view->len;
741 }
742 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyErr_Format(PyExc_TypeError,
744 "%s() arg 1 must be a %s object",
745 funcname, what);
746 return NULL;
747 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200748
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200749 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300750 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 "source code string cannot contain null bytes");
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200752 PyBuffer_Release(view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 return NULL;
754 }
755 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000756}
757
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000758/*[clinic input]
759compile as builtin_compile
760
761 source: 'O'
762 filename: object(converter="PyUnicode_FSDecoder")
763 mode: 's'
764 flags: 'i' = 0
765 dont_inherit: 'i' = 0
766 optimize: 'i' = -1
767
768Compile source into a code object that can be executed by exec() or eval().
769
770The source code may represent a Python module, statement or expression.
771The filename will be used for run-time error messages.
772The mode must be 'exec' to compile a module, 'single' to compile a
773single (interactive) statement, or 'eval' to compile an expression.
774The flags argument, if present, controls which future statements influence
775the compilation of the code.
776The dont_inherit argument, if non-zero, stops the compilation inheriting
777the effects of any future statements in effect in the code calling
778compile; if absent or zero these statements do influence the compilation,
779in addition to any features explicitly specified.
780[clinic start generated code]*/
781
782PyDoc_STRVAR(builtin_compile__doc__,
783"compile($module, /, source, filename, mode, flags=0, dont_inherit=0,\n"
784" optimize=-1)\n"
785"--\n"
786"\n"
787"Compile source into a code object that can be executed by exec() or eval().\n"
788"\n"
789"The source code may represent a Python module, statement or expression.\n"
790"The filename will be used for run-time error messages.\n"
791"The mode must be \'exec\' to compile a module, \'single\' to compile a\n"
792"single (interactive) statement, or \'eval\' to compile an expression.\n"
793"The flags argument, if present, controls which future statements influence\n"
794"the compilation of the code.\n"
795"The dont_inherit argument, if non-zero, stops the compilation inheriting\n"
796"the effects of any future statements in effect in the code calling\n"
797"compile; if absent or zero these statements do influence the compilation,\n"
798"in addition to any features explicitly specified.");
799
800#define BUILTIN_COMPILE_METHODDEF \
801 {"compile", (PyCFunction)builtin_compile, METH_VARARGS|METH_KEYWORDS, builtin_compile__doc__},
802
Guido van Rossum79f25d91997-04-29 20:08:16 +0000803static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000804builtin_compile_impl(PyModuleDef *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize);
805
806static PyObject *
807builtin_compile(PyModuleDef *module, PyObject *args, PyObject *kwargs)
808{
809 PyObject *return_value = NULL;
810 static char *_keywords[] = {"source", "filename", "mode", "flags", "dont_inherit", "optimize", NULL};
811 PyObject *source;
812 PyObject *filename;
813 const char *mode;
814 int flags = 0;
815 int dont_inherit = 0;
816 int optimize = -1;
817
818 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
819 "OO&s|iii:compile", _keywords,
820 &source, PyUnicode_FSDecoder, &filename, &mode, &flags, &dont_inherit, &optimize))
821 goto exit;
822 return_value = builtin_compile_impl(module, source, filename, mode, flags, dont_inherit, optimize);
823
824exit:
825 return return_value;
826}
827
828static PyObject *
829builtin_compile_impl(PyModuleDef *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize)
830/*[clinic end generated code: output=c72d197809d178fc input=c6212a9d21472f7e]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000831{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200832 Py_buffer view = {NULL, NULL};
833 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000834 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 int is_ast;
836 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000838 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000839
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000840 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000841
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000842 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
844 {
845 PyErr_SetString(PyExc_ValueError,
846 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000847 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
849 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000850
Georg Brandl8334fd92010-12-04 10:26:46 +0000851 if (optimize < -1 || optimize > 2) {
852 PyErr_SetString(PyExc_ValueError,
853 "compile(): invalid optimize value");
854 goto error;
855 }
856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (!dont_inherit) {
858 PyEval_MergeCompilerFlags(&cf);
859 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000860
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000861 if (strcmp(mode, "exec") == 0)
862 compile_mode = 0;
863 else if (strcmp(mode, "eval") == 0)
864 compile_mode = 1;
865 else if (strcmp(mode, "single") == 0)
866 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 else {
868 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000869 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000870 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000872
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000873 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000875 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000877 if (flags & PyCF_ONLY_AST) {
878 Py_INCREF(source);
879 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 }
881 else {
882 PyArena *arena;
883 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200886 if (arena == NULL)
887 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000888 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (mod == NULL) {
890 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000891 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500893 if (!PyAST_Validate(mod)) {
894 PyArena_Free(arena);
895 goto error;
896 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200897 result = (PyObject*)PyAST_CompileObject(mod, filename,
898 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 PyArena_Free(arena);
900 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000901 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000903
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200904 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000906 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000907
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000908 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200909 PyBuffer_Release(&view);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000910 goto finally;
911
912error:
913 result = NULL;
914finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200915 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000916 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000917}
918
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000919/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000920static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000921builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
926 return NULL;
927 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000928}
929
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000930PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000931"dir([object]) -> list of strings\n"
932"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000933"If called without an argument, return the names in the current scope.\n"
934"Else, return an alphabetized list of names comprising (some of) the attributes\n"
935"of the given object, and of attributes reachable from it.\n"
936"If the object supplies a method named __dir__, it will be used; otherwise\n"
937"the default dir() logic is used and returns:\n"
938" for a module object: the module's attributes.\n"
939" for a class object: its attributes, and recursively the attributes\n"
940" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000941" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000942" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000943
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000944/*[clinic input]
945divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000946
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000947 x: 'O'
948 y: 'O'
949 /
950
951Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.
952[clinic start generated code]*/
953
954PyDoc_STRVAR(builtin_divmod__doc__,
955"divmod($module, x, y, /)\n"
956"--\n"
957"\n"
958"Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
959
960#define BUILTIN_DIVMOD_METHODDEF \
961 {"divmod", (PyCFunction)builtin_divmod, METH_VARARGS, builtin_divmod__doc__},
962
963static PyObject *
964builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y);
965
966static PyObject *
967builtin_divmod(PyModuleDef *module, PyObject *args)
968{
969 PyObject *return_value = NULL;
970 PyObject *x;
971 PyObject *y;
972
973 if (!PyArg_UnpackTuple(args, "divmod",
974 2, 2,
975 &x, &y))
976 goto exit;
977 return_value = builtin_divmod_impl(module, x, y);
978
979exit:
980 return return_value;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000981}
982
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000983static PyObject *
984builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y)
985/*[clinic end generated code: output=77e8d408b1338886 input=c9c617b7bb74c615]*/
986{
987 return PyNumber_Divmod(x, y);
988}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000989
990
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000991/*[clinic input]
992eval as builtin_eval
993
994 source: 'O'
995 globals: 'O' = None
996 locals: 'O' = None
997 /
998
999Evaluate the given source in the context of globals and locals.
1000
1001The source may be a string representing a Python expression
1002or a code object as returned by compile().
1003The globals must be a dictionary and locals can be any mapping,
1004defaulting to the current globals and locals.
1005If only globals is given, locals defaults to it.
1006[clinic start generated code]*/
1007
1008PyDoc_STRVAR(builtin_eval__doc__,
1009"eval($module, source, globals=None, locals=None, /)\n"
1010"--\n"
1011"\n"
1012"Evaluate the given source in the context of globals and locals.\n"
1013"\n"
1014"The source may be a string representing a Python expression\n"
1015"or a code object as returned by compile().\n"
1016"The globals must be a dictionary and locals can be any mapping,\n"
1017"defaulting to the current globals and locals.\n"
1018"If only globals is given, locals defaults to it.");
1019
1020#define BUILTIN_EVAL_METHODDEF \
1021 {"eval", (PyCFunction)builtin_eval, METH_VARARGS, builtin_eval__doc__},
1022
Guido van Rossum79f25d91997-04-29 20:08:16 +00001023static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001024builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals);
1025
1026static PyObject *
1027builtin_eval(PyModuleDef *module, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001028{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001029 PyObject *return_value = NULL;
1030 PyObject *source;
1031 PyObject *globals = Py_None;
1032 PyObject *locals = Py_None;
1033
1034 if (!PyArg_UnpackTuple(args, "eval",
1035 1, 3,
1036 &source, &globals, &locals))
1037 goto exit;
1038 return_value = builtin_eval_impl(module, source, globals, locals);
1039
1040exit:
1041 return return_value;
1042}
1043
1044static PyObject *
1045builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals)
1046/*[clinic end generated code: output=644fd59012538ce6 input=31e42c1d2125b50b]*/
1047{
1048 PyObject *result, *tmp = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001049 Py_buffer view = {NULL, NULL};
1050 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 if (locals != Py_None && !PyMapping_Check(locals)) {
1054 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
1055 return NULL;
1056 }
1057 if (globals != Py_None && !PyDict_Check(globals)) {
1058 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
1059 "globals must be a real dict; try eval(expr, {}, mapping)"
1060 : "globals must be a dict");
1061 return NULL;
1062 }
1063 if (globals == Py_None) {
1064 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001065 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001067 if (locals == NULL)
1068 return NULL;
1069 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 }
1071 else if (locals == Py_None)
1072 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 if (globals == NULL || locals == NULL) {
1075 PyErr_SetString(PyExc_TypeError,
1076 "eval must be given globals and locals "
1077 "when called without a frame");
1078 return NULL;
1079 }
Georg Brandl77c85e62005-09-15 10:46:13 +00001080
Victor Stinnerb44562b2013-11-06 19:03:11 +01001081 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
1082 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1083 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 return NULL;
1085 }
Tim Peters9fa96be2001-08-17 23:04:59 +00001086
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001087 if (PyCode_Check(source)) {
1088 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyErr_SetString(PyExc_TypeError,
1090 "code object passed to eval() may not contain free variables");
1091 return NULL;
1092 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001093 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 }
Tim Peters9fa96be2001-08-17 23:04:59 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001097 str = source_as_string(source, "eval", "string, bytes or code", &cf, &view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (str == NULL)
1099 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 while (*str == ' ' || *str == '\t')
1102 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 (void)PyEval_MergeCompilerFlags(&cf);
1105 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001106 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 Py_XDECREF(tmp);
1108 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001109}
1110
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001111/*[clinic input]
1112exec as builtin_exec
1113
1114 source: 'O'
1115 globals: 'O' = None
1116 locals: 'O' = None
1117 /
1118
1119Execute the given source in the context of globals and locals.
1120
1121The source may be a string representing one or more Python statements
1122or a code object as returned by compile().
1123The globals must be a dictionary and locals can be any mapping,
1124defaulting to the current globals and locals.
1125If only globals is given, locals defaults to it.
1126[clinic start generated code]*/
1127
1128PyDoc_STRVAR(builtin_exec__doc__,
1129"exec($module, source, globals=None, locals=None, /)\n"
1130"--\n"
1131"\n"
1132"Execute the given source in the context of globals and locals.\n"
1133"\n"
1134"The source may be a string representing one or more Python statements\n"
1135"or a code object as returned by compile().\n"
1136"The globals must be a dictionary and locals can be any mapping,\n"
1137"defaulting to the current globals and locals.\n"
1138"If only globals is given, locals defaults to it.");
1139
1140#define BUILTIN_EXEC_METHODDEF \
1141 {"exec", (PyCFunction)builtin_exec, METH_VARARGS, builtin_exec__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001142
Georg Brandl7cae87c2006-09-06 06:51:57 +00001143static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001144builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals);
1145
1146static PyObject *
1147builtin_exec(PyModuleDef *module, PyObject *args)
1148{
1149 PyObject *return_value = NULL;
1150 PyObject *source;
1151 PyObject *globals = Py_None;
1152 PyObject *locals = Py_None;
1153
1154 if (!PyArg_UnpackTuple(args, "exec",
1155 1, 3,
1156 &source, &globals, &locals))
1157 goto exit;
1158 return_value = builtin_exec_impl(module, source, globals, locals);
1159
1160exit:
1161 return return_value;
1162}
1163
1164static PyObject *
1165builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals)
1166/*[clinic end generated code: output=0281b48bfa8e3c87 input=536e057b5e00d89e]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (globals == Py_None) {
1171 globals = PyEval_GetGlobals();
1172 if (locals == Py_None) {
1173 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001174 if (locals == NULL)
1175 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 }
1177 if (!globals || !locals) {
1178 PyErr_SetString(PyExc_SystemError,
1179 "globals and locals cannot be NULL");
1180 return NULL;
1181 }
1182 }
1183 else if (locals == Py_None)
1184 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001187 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 globals->ob_type->tp_name);
1189 return NULL;
1190 }
1191 if (!PyMapping_Check(locals)) {
1192 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001193 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 locals->ob_type->tp_name);
1195 return NULL;
1196 }
Victor Stinnerb44562b2013-11-06 19:03:11 +01001197 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
1198 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1199 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 return NULL;
1201 }
1202
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001203 if (PyCode_Check(source)) {
1204 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 PyErr_SetString(PyExc_TypeError,
1206 "code object passed to exec() may not "
1207 "contain free variables");
1208 return NULL;
1209 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001210 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 }
1212 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001213 Py_buffer view = {NULL, NULL};
1214 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyCompilerFlags cf;
1216 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001217 str = source_as_string(source, "exec",
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +02001218 "string, bytes or code", &cf, &view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 if (str == NULL)
1220 return NULL;
1221 if (PyEval_MergeCompilerFlags(&cf))
1222 v = PyRun_StringFlags(str, Py_file_input, globals,
1223 locals, &cf);
1224 else
1225 v = PyRun_String(str, Py_file_input, globals, locals);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001226 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 }
1228 if (v == NULL)
1229 return NULL;
1230 Py_DECREF(v);
1231 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001232}
1233
Georg Brandl7cae87c2006-09-06 06:51:57 +00001234
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001235/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001236static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001237builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 PyObject *v, *result, *dflt = NULL;
1240 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
1243 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (!PyUnicode_Check(name)) {
1246 PyErr_SetString(PyExc_TypeError,
1247 "getattr(): attribute name must be string");
1248 return NULL;
1249 }
1250 result = PyObject_GetAttr(v, name);
1251 if (result == NULL && dflt != NULL &&
1252 PyErr_ExceptionMatches(PyExc_AttributeError))
1253 {
1254 PyErr_Clear();
1255 Py_INCREF(dflt);
1256 result = dflt;
1257 }
1258 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001259}
1260
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001261PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001262"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001263\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001264Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1265When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001266exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001267
1268
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001269/*[clinic input]
1270globals as builtin_globals
1271
1272Return the dictionary containing the current scope's global variables.
1273
1274NOTE: Updates to this dictionary *will* affect name lookups in the current
1275global scope and vice-versa.
1276[clinic start generated code]*/
1277
1278PyDoc_STRVAR(builtin_globals__doc__,
1279"globals($module, /)\n"
1280"--\n"
1281"\n"
1282"Return the dictionary containing the current scope\'s global variables.\n"
1283"\n"
1284"NOTE: Updates to this dictionary *will* affect name lookups in the current\n"
1285"global scope and vice-versa.");
1286
1287#define BUILTIN_GLOBALS_METHODDEF \
1288 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, builtin_globals__doc__},
1289
Guido van Rossum79f25d91997-04-29 20:08:16 +00001290static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001291builtin_globals_impl(PyModuleDef *module);
1292
1293static PyObject *
1294builtin_globals(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1295{
1296 return builtin_globals_impl(module);
1297}
1298
1299static PyObject *
1300builtin_globals_impl(PyModuleDef *module)
1301/*[clinic end generated code: output=048640f58b1f20ad input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 d = PyEval_GetGlobals();
1306 Py_XINCREF(d);
1307 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001308}
1309
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001310
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001311/*[clinic input]
1312hasattr as builtin_hasattr
1313
1314 obj: 'O'
1315 name: 'O'
1316 /
1317
1318Return whether the object has an attribute with the given name.
1319
1320This is done by calling getattr(obj, name) and catching AttributeError.
1321[clinic start generated code]*/
1322
1323PyDoc_STRVAR(builtin_hasattr__doc__,
1324"hasattr($module, obj, name, /)\n"
1325"--\n"
1326"\n"
1327"Return whether the object has an attribute with the given name.\n"
1328"\n"
1329"This is done by calling getattr(obj, name) and catching AttributeError.");
1330
1331#define BUILTIN_HASATTR_METHODDEF \
1332 {"hasattr", (PyCFunction)builtin_hasattr, METH_VARARGS, builtin_hasattr__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001333
Guido van Rossum79f25d91997-04-29 20:08:16 +00001334static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001335builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name);
1336
1337static PyObject *
1338builtin_hasattr(PyModuleDef *module, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001339{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001340 PyObject *return_value = NULL;
1341 PyObject *obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001343
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001344 if (!PyArg_UnpackTuple(args, "hasattr",
1345 2, 2,
1346 &obj, &name))
1347 goto exit;
1348 return_value = builtin_hasattr_impl(module, obj, name);
1349
1350exit:
1351 return return_value;
1352}
1353
1354static PyObject *
1355builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
1356/*[clinic end generated code: output=e0bd996ef73d1217 input=b50bad5f739ea10d]*/
1357{
1358 PyObject *v;
1359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (!PyUnicode_Check(name)) {
1361 PyErr_SetString(PyExc_TypeError,
1362 "hasattr(): attribute name must be string");
1363 return NULL;
1364 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001365 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001367 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001369 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001371 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 }
1373 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001374 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001375}
1376
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001377
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001378/* AC: gdb's integration with CPython relies on builtin_id having
1379 * the *exact* parameter names of "self" and "v", so we ensure we
1380 * preserve those name rather than using the AC defaults.
1381 */
1382/*[clinic input]
1383id as builtin_id
1384
1385 self: self(type="PyModuleDef *")
1386 obj as v: 'O'
1387 /
1388
1389Return the identity of an object.
1390
1391This is guaranteed to be unique among simultaneously existing objects.
1392(CPython uses the object's memory address.)
1393[clinic start generated code]*/
1394
1395PyDoc_STRVAR(builtin_id__doc__,
1396"id($module, obj, /)\n"
1397"--\n"
1398"\n"
1399"Return the identity of an object.\n"
1400"\n"
1401"This is guaranteed to be unique among simultaneously existing objects.\n"
1402"(CPython uses the object\'s memory address.)");
1403
1404#define BUILTIN_ID_METHODDEF \
1405 {"id", (PyCFunction)builtin_id, METH_O, builtin_id__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001406
Guido van Rossum79f25d91997-04-29 20:08:16 +00001407static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001408builtin_id(PyModuleDef *self, PyObject *v)
1409/*[clinic end generated code: output=f54da09c91992e63 input=a1f988d98357341d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001412}
1413
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001414
Raymond Hettingera6c60372008-03-13 01:26:19 +00001415/* map object ************************************************************/
1416
1417typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 PyObject_HEAD
1419 PyObject *iters;
1420 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001421} mapobject;
1422
Guido van Rossum79f25d91997-04-29 20:08:16 +00001423static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001424map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 PyObject *it, *iters, *func;
1427 mapobject *lz;
1428 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1431 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 numargs = PyTuple_Size(args);
1434 if (numargs < 2) {
1435 PyErr_SetString(PyExc_TypeError,
1436 "map() must have at least two arguments.");
1437 return NULL;
1438 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 iters = PyTuple_New(numargs-1);
1441 if (iters == NULL)
1442 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 for (i=1 ; i<numargs ; i++) {
1445 /* Get iterator. */
1446 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1447 if (it == NULL) {
1448 Py_DECREF(iters);
1449 return NULL;
1450 }
1451 PyTuple_SET_ITEM(iters, i-1, it);
1452 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 /* create mapobject structure */
1455 lz = (mapobject *)type->tp_alloc(type, 0);
1456 if (lz == NULL) {
1457 Py_DECREF(iters);
1458 return NULL;
1459 }
1460 lz->iters = iters;
1461 func = PyTuple_GET_ITEM(args, 0);
1462 Py_INCREF(func);
1463 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001466}
1467
1468static void
1469map_dealloc(mapobject *lz)
1470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 PyObject_GC_UnTrack(lz);
1472 Py_XDECREF(lz->iters);
1473 Py_XDECREF(lz->func);
1474 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001475}
1476
1477static int
1478map_traverse(mapobject *lz, visitproc visit, void *arg)
1479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 Py_VISIT(lz->iters);
1481 Py_VISIT(lz->func);
1482 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001483}
1484
1485static PyObject *
1486map_next(mapobject *lz)
1487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 PyObject *val;
1489 PyObject *argtuple;
1490 PyObject *result;
1491 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 numargs = PyTuple_Size(lz->iters);
1494 argtuple = PyTuple_New(numargs);
1495 if (argtuple == NULL)
1496 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 for (i=0 ; i<numargs ; i++) {
1499 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1500 if (val == NULL) {
1501 Py_DECREF(argtuple);
1502 return NULL;
1503 }
1504 PyTuple_SET_ITEM(argtuple, i, val);
1505 }
1506 result = PyObject_Call(lz->func, argtuple, NULL);
1507 Py_DECREF(argtuple);
1508 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001509}
1510
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001511static PyObject *
1512map_reduce(mapobject *lz)
1513{
1514 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1515 PyObject *args = PyTuple_New(numargs+1);
1516 Py_ssize_t i;
1517 if (args == NULL)
1518 return NULL;
1519 Py_INCREF(lz->func);
1520 PyTuple_SET_ITEM(args, 0, lz->func);
1521 for (i = 0; i<numargs; i++){
1522 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1523 Py_INCREF(it);
1524 PyTuple_SET_ITEM(args, i+1, it);
1525 }
1526
1527 return Py_BuildValue("ON", Py_TYPE(lz), args);
1528}
1529
1530static PyMethodDef map_methods[] = {
1531 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1532 {NULL, NULL} /* sentinel */
1533};
1534
1535
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001536PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001537"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001538\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001539Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001541
Raymond Hettingera6c60372008-03-13 01:26:19 +00001542PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1544 "map", /* tp_name */
1545 sizeof(mapobject), /* tp_basicsize */
1546 0, /* tp_itemsize */
1547 /* methods */
1548 (destructor)map_dealloc, /* tp_dealloc */
1549 0, /* tp_print */
1550 0, /* tp_getattr */
1551 0, /* tp_setattr */
1552 0, /* tp_reserved */
1553 0, /* tp_repr */
1554 0, /* tp_as_number */
1555 0, /* tp_as_sequence */
1556 0, /* tp_as_mapping */
1557 0, /* tp_hash */
1558 0, /* tp_call */
1559 0, /* tp_str */
1560 PyObject_GenericGetAttr, /* tp_getattro */
1561 0, /* tp_setattro */
1562 0, /* tp_as_buffer */
1563 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1564 Py_TPFLAGS_BASETYPE, /* tp_flags */
1565 map_doc, /* tp_doc */
1566 (traverseproc)map_traverse, /* tp_traverse */
1567 0, /* tp_clear */
1568 0, /* tp_richcompare */
1569 0, /* tp_weaklistoffset */
1570 PyObject_SelfIter, /* tp_iter */
1571 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001572 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 0, /* tp_members */
1574 0, /* tp_getset */
1575 0, /* tp_base */
1576 0, /* tp_dict */
1577 0, /* tp_descr_get */
1578 0, /* tp_descr_set */
1579 0, /* tp_dictoffset */
1580 0, /* tp_init */
1581 PyType_GenericAlloc, /* tp_alloc */
1582 map_new, /* tp_new */
1583 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001584};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001585
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001586
1587/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001588static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001589builtin_next(PyObject *self, PyObject *args)
1590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 PyObject *it, *res;
1592 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1595 return NULL;
1596 if (!PyIter_Check(it)) {
1597 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001598 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 it->ob_type->tp_name);
1600 return NULL;
1601 }
1602
1603 res = (*it->ob_type->tp_iternext)(it);
1604 if (res != NULL) {
1605 return res;
1606 } else if (def != NULL) {
1607 if (PyErr_Occurred()) {
1608 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1609 return NULL;
1610 PyErr_Clear();
1611 }
1612 Py_INCREF(def);
1613 return def;
1614 } else if (PyErr_Occurred()) {
1615 return NULL;
1616 } else {
1617 PyErr_SetNone(PyExc_StopIteration);
1618 return NULL;
1619 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001620}
1621
1622PyDoc_STRVAR(next_doc,
1623"next(iterator[, default])\n\
1624\n\
1625Return the next item from the iterator. If default is given and the iterator\n\
1626is exhausted, it is returned instead of raising StopIteration.");
1627
1628
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001629/*[clinic input]
1630setattr as builtin_setattr
1631
1632 obj: 'O'
1633 name: 'O'
1634 value: 'O'
1635 /
1636
1637Sets the named attribute on the given object to the specified value.
1638
1639setattr(x, 'y', v) is equivalent to ``x.y = v''
1640[clinic start generated code]*/
1641
1642PyDoc_STRVAR(builtin_setattr__doc__,
1643"setattr($module, obj, name, value, /)\n"
1644"--\n"
1645"\n"
1646"Sets the named attribute on the given object to the specified value.\n"
1647"\n"
1648"setattr(x, \'y\', v) is equivalent to ``x.y = v\'\'");
1649
1650#define BUILTIN_SETATTR_METHODDEF \
1651 {"setattr", (PyCFunction)builtin_setattr, METH_VARARGS, builtin_setattr__doc__},
1652
Georg Brandla18af4e2007-04-21 15:47:16 +00001653static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001654builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name, PyObject *value);
1655
1656static PyObject *
1657builtin_setattr(PyModuleDef *module, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001658{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001659 PyObject *return_value = NULL;
1660 PyObject *obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 PyObject *name;
1662 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001663
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001664 if (!PyArg_UnpackTuple(args, "setattr",
1665 3, 3,
1666 &obj, &name, &value))
1667 goto exit;
1668 return_value = builtin_setattr_impl(module, obj, name, value);
1669
1670exit:
1671 return return_value;
1672}
1673
1674static PyObject *
1675builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name, PyObject *value)
1676/*[clinic end generated code: output=4336dcbbf7691d2d input=fbe7e53403116b93]*/
1677{
1678 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 return NULL;
1680 Py_INCREF(Py_None);
1681 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001682}
1683
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001684
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001685/*[clinic input]
1686delattr as builtin_delattr
1687
1688 obj: 'O'
1689 name: 'O'
1690 /
1691
1692Deletes the named attribute from the given object.
1693
1694delattr(x, 'y') is equivalent to ``del x.y''
1695[clinic start generated code]*/
1696
1697PyDoc_STRVAR(builtin_delattr__doc__,
1698"delattr($module, obj, name, /)\n"
1699"--\n"
1700"\n"
1701"Deletes the named attribute from the given object.\n"
1702"\n"
1703"delattr(x, \'y\') is equivalent to ``del x.y\'\'");
1704
1705#define BUILTIN_DELATTR_METHODDEF \
1706 {"delattr", (PyCFunction)builtin_delattr, METH_VARARGS, builtin_delattr__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001707
Guido van Rossum79f25d91997-04-29 20:08:16 +00001708static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001709builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name);
1710
1711static PyObject *
1712builtin_delattr(PyModuleDef *module, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001713{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001714 PyObject *return_value = NULL;
1715 PyObject *obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001717
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001718 if (!PyArg_UnpackTuple(args, "delattr",
1719 2, 2,
1720 &obj, &name))
1721 goto exit;
1722 return_value = builtin_delattr_impl(module, obj, name);
1723
1724exit:
1725 return return_value;
1726}
1727
1728static PyObject *
1729builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
1730/*[clinic end generated code: output=319c2d884aa769cf input=647af2ce9183a823]*/
1731{
1732 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return NULL;
1734 Py_INCREF(Py_None);
1735 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001736}
1737
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001738
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001739/*[clinic input]
1740hash as builtin_hash
1741
1742 obj: 'O'
1743 /
1744
1745Return the hash value for the given object.
1746
1747Two objects that compare equal must also have the same hash value, but the
1748reverse is not necessarily true.
1749[clinic start generated code]*/
1750
1751PyDoc_STRVAR(builtin_hash__doc__,
1752"hash($module, obj, /)\n"
1753"--\n"
1754"\n"
1755"Return the hash value for the given object.\n"
1756"\n"
1757"Two objects that compare equal must also have the same hash value, but the\n"
1758"reverse is not necessarily true.");
1759
1760#define BUILTIN_HASH_METHODDEF \
1761 {"hash", (PyCFunction)builtin_hash, METH_O, builtin_hash__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001762
Guido van Rossum79f25d91997-04-29 20:08:16 +00001763static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001764builtin_hash(PyModuleDef *module, PyObject *obj)
1765/*[clinic end generated code: output=1ec467611c13468b input=ccc4d2b9a351df4e]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001766{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001767 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001768
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001769 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (x == -1)
1771 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001772 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001773}
1774
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001775
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001776/*[clinic input]
1777hex as builtin_hex
1778
1779 number: 'O'
1780 /
1781
1782Return the hexadecimal representation of an integer.
1783
1784 >>> hex(12648430)
1785 '0xc0ffee'
1786[clinic start generated code]*/
1787
1788PyDoc_STRVAR(builtin_hex__doc__,
1789"hex($module, number, /)\n"
1790"--\n"
1791"\n"
1792"Return the hexadecimal representation of an integer.\n"
1793"\n"
1794" >>> hex(12648430)\n"
1795" \'0xc0ffee\'");
1796
1797#define BUILTIN_HEX_METHODDEF \
1798 {"hex", (PyCFunction)builtin_hex, METH_O, builtin_hex__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001799
Guido van Rossum79f25d91997-04-29 20:08:16 +00001800static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001801builtin_hex(PyModuleDef *module, PyObject *number)
1802/*[clinic end generated code: output=f18e9439aeaa2c6c input=e816200b0a728ebe]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001803{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001804 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001805}
1806
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001807
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001808/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001809static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001810builtin_iter(PyObject *self, PyObject *args)
1811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1815 return NULL;
1816 if (w == NULL)
1817 return PyObject_GetIter(v);
1818 if (!PyCallable_Check(v)) {
1819 PyErr_SetString(PyExc_TypeError,
1820 "iter(v, w): v must be callable");
1821 return NULL;
1822 }
1823 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001824}
1825
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001826PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001827"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001828iter(callable, sentinel) -> iterator\n\
1829\n\
1830Get an iterator from an object. In the first form, the argument must\n\
1831supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001832In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001833
1834
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001835/*[clinic input]
1836len as builtin_len
1837
1838 obj: 'O'
1839 /
1840
1841Return the number of items in a container.
1842[clinic start generated code]*/
1843
1844PyDoc_STRVAR(builtin_len__doc__,
1845"len($module, obj, /)\n"
1846"--\n"
1847"\n"
1848"Return the number of items in a container.");
1849
1850#define BUILTIN_LEN_METHODDEF \
1851 {"len", (PyCFunction)builtin_len, METH_O, builtin_len__doc__},
1852
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001853static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001854builtin_len(PyModuleDef *module, PyObject *obj)
1855/*[clinic end generated code: output=5a38b0db40761705 input=2e5ff15db9a2de22]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001858
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001859 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (res < 0 && PyErr_Occurred())
1861 return NULL;
1862 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001863}
1864
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001865
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001866/*[clinic input]
1867locals as builtin_locals
1868
1869Return a dictionary containing the current scope's local variables.
1870
1871NOTE: Whether or not updates to this dictionary will affect name lookups in
1872the local scope and vice-versa is *implementation dependent* and not
1873covered by any backwards compatibility guarantees.
1874[clinic start generated code]*/
1875
1876PyDoc_STRVAR(builtin_locals__doc__,
1877"locals($module, /)\n"
1878"--\n"
1879"\n"
1880"Return a dictionary containing the current scope\'s local variables.\n"
1881"\n"
1882"NOTE: Whether or not updates to this dictionary will affect name lookups in\n"
1883"the local scope and vice-versa is *implementation dependent* and not\n"
1884"covered by any backwards compatibility guarantees.");
1885
1886#define BUILTIN_LOCALS_METHODDEF \
1887 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, builtin_locals__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001888
Guido van Rossum79f25d91997-04-29 20:08:16 +00001889static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001890builtin_locals_impl(PyModuleDef *module);
1891
1892static PyObject *
1893builtin_locals(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1894{
1895 return builtin_locals_impl(module);
1896}
1897
1898static PyObject *
1899builtin_locals_impl(PyModuleDef *module)
1900/*[clinic end generated code: output=8ac52522924346e2 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 d = PyEval_GetLocals();
1905 Py_XINCREF(d);
1906 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001907}
1908
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001909
Guido van Rossum79f25d91997-04-29 20:08:16 +00001910static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001911min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001914 PyObject *emptytuple, *defaultval = NULL;
1915 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001917 const int positional = PyTuple_Size(args) > 1;
1918 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001919
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001920 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001922 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001924
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001925 emptytuple = PyTuple_New(0);
1926 if (emptytuple == NULL)
1927 return NULL;
1928 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1929 &keyfunc, &defaultval);
1930 Py_DECREF(emptytuple);
1931 if (!ret)
1932 return NULL;
1933
1934 if (positional && defaultval != NULL) {
1935 PyErr_Format(PyExc_TypeError,
1936 "Cannot specify a default for %s() with multiple "
1937 "positional arguments", name);
1938 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 it = PyObject_GetIter(v);
1942 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 return NULL;
1944 }
Tim Petersc3074532001-05-03 07:00:32 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 maxitem = NULL; /* the result */
1947 maxval = NULL; /* the value associated with the result */
1948 while (( item = PyIter_Next(it) )) {
1949 /* get the value from the key function */
1950 if (keyfunc != NULL) {
1951 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1952 if (val == NULL)
1953 goto Fail_it_item;
1954 }
1955 /* no key function; the value is the item */
1956 else {
1957 val = item;
1958 Py_INCREF(val);
1959 }
Tim Petersc3074532001-05-03 07:00:32 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 /* maximum value and item are unset; set them */
1962 if (maxval == NULL) {
1963 maxitem = item;
1964 maxval = val;
1965 }
1966 /* maximum value and item are set; update them as necessary */
1967 else {
1968 int cmp = PyObject_RichCompareBool(val, maxval, op);
1969 if (cmp < 0)
1970 goto Fail_it_item_and_val;
1971 else if (cmp > 0) {
1972 Py_DECREF(maxval);
1973 Py_DECREF(maxitem);
1974 maxval = val;
1975 maxitem = item;
1976 }
1977 else {
1978 Py_DECREF(item);
1979 Py_DECREF(val);
1980 }
1981 }
1982 }
1983 if (PyErr_Occurred())
1984 goto Fail_it;
1985 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001987 if (defaultval != NULL) {
1988 Py_INCREF(defaultval);
1989 maxitem = defaultval;
1990 } else {
1991 PyErr_Format(PyExc_ValueError,
1992 "%s() arg is an empty sequence", name);
1993 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 }
1995 else
1996 Py_DECREF(maxval);
1997 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001999
2000Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00002002Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00002004Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 Py_XDECREF(maxval);
2006 Py_XDECREF(maxitem);
2007 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002009}
2010
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002011/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002012static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00002013builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002016}
2017
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002018PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01002019"min(iterable, *[, default=obj, key=func]) -> value\n\
2020min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002021\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01002022With a single iterable argument, return its smallest item. The\n\
2023default keyword-only argument specifies an object to return if\n\
2024the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002025With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002026
2027
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002028/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002029static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00002030builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002033}
2034
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002035PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01002036"max(iterable, *[, default=obj, key=func]) -> value\n\
2037max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002038\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01002039With a single iterable argument, return its biggest item. The\n\
2040default keyword-only argument specifies an object to return if\n\
2041the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002042With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002043
2044
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002045/*[clinic input]
2046oct as builtin_oct
2047
2048 number: 'O'
2049 /
2050
2051Return the octal representation of an integer.
2052
2053 >>> oct(342391)
2054 '0o1234567'
2055[clinic start generated code]*/
2056
2057PyDoc_STRVAR(builtin_oct__doc__,
2058"oct($module, number, /)\n"
2059"--\n"
2060"\n"
2061"Return the octal representation of an integer.\n"
2062"\n"
2063" >>> oct(342391)\n"
2064" \'0o1234567\'");
2065
2066#define BUILTIN_OCT_METHODDEF \
2067 {"oct", (PyCFunction)builtin_oct, METH_O, builtin_oct__doc__},
2068
Guido van Rossum79f25d91997-04-29 20:08:16 +00002069static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002070builtin_oct(PyModuleDef *module, PyObject *number)
2071/*[clinic end generated code: output=b99234d1d70a6673 input=a3a372b521b3dd13]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00002072{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002073 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00002074}
2075
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002076
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002077/*[clinic input]
2078ord as builtin_ord
2079
2080 c: 'O'
2081 /
2082
2083Return the Unicode code point for a one-character string.
2084[clinic start generated code]*/
2085
2086PyDoc_STRVAR(builtin_ord__doc__,
2087"ord($module, c, /)\n"
2088"--\n"
2089"\n"
2090"Return the Unicode code point for a one-character string.");
2091
2092#define BUILTIN_ORD_METHODDEF \
2093 {"ord", (PyCFunction)builtin_ord, METH_O, builtin_ord__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002094
Guido van Rossum79f25d91997-04-29 20:08:16 +00002095static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002096builtin_ord(PyModuleDef *module, PyObject *c)
2097/*[clinic end generated code: output=a8466d23bd76db3f input=762355f87451efa3]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00002098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 long ord;
2100 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002101
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002102 if (PyBytes_Check(c)) {
2103 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002105 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 return PyLong_FromLong(ord);
2107 }
2108 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002109 else if (PyUnicode_Check(c)) {
2110 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002111 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002112 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002114 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 return PyLong_FromLong(ord);
2116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002118 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002120 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002122 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 return PyLong_FromLong(ord);
2124 }
2125 }
2126 else {
2127 PyErr_Format(PyExc_TypeError,
2128 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002129 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 return NULL;
2131 }
Guido van Rossum09095f32000-03-10 23:00:52 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 PyErr_Format(PyExc_TypeError,
2134 "ord() expected a character, "
2135 "but string of length %zd found",
2136 size);
2137 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002138}
2139
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002140
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002141/*[clinic input]
2142pow as builtin_pow
2143
2144 x: 'O'
2145 y: 'O'
2146 z: 'O' = None
2147 /
2148
2149Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
2150
2151Some types, such as ints, are able to use a more efficient algorithm when
2152invoked using the three argument form.
2153[clinic start generated code]*/
2154
2155PyDoc_STRVAR(builtin_pow__doc__,
2156"pow($module, x, y, z=None, /)\n"
2157"--\n"
2158"\n"
2159"Equivalent to x**y (with two arguments) or x**y % z (with three arguments)\n"
2160"\n"
2161"Some types, such as ints, are able to use a more efficient algorithm when\n"
2162"invoked using the three argument form.");
2163
2164#define BUILTIN_POW_METHODDEF \
2165 {"pow", (PyCFunction)builtin_pow, METH_VARARGS, builtin_pow__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002166
Guido van Rossum79f25d91997-04-29 20:08:16 +00002167static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002168builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z);
Guido van Rossum6a00cd81995-01-07 12:39:01 +00002169
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002170static PyObject *
2171builtin_pow(PyModuleDef *module, PyObject *args)
2172{
2173 PyObject *return_value = NULL;
2174 PyObject *x;
2175 PyObject *y;
2176 PyObject *z = Py_None;
2177
2178 if (!PyArg_UnpackTuple(args, "pow",
2179 2, 3,
2180 &x, &y, &z))
2181 goto exit;
2182 return_value = builtin_pow_impl(module, x, y, z);
2183
2184exit:
2185 return return_value;
Guido van Rossumd4905451991-05-05 20:00:36 +00002186}
2187
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002188static PyObject *
2189builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z)
2190/*[clinic end generated code: output=d0cdf314311dedba input=561a942d5f5c1899]*/
2191{
2192 return PyNumber_Power(x, y, z);
2193}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002194
2195
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002196/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00002197static PyObject *
2198builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
2199{
Georg Brandlbc3b6822012-01-13 19:41:25 +01002200 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01002202 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00002204
Benjamin Peterson00102562012-01-11 21:00:16 -05002205 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01002206 return NULL;
2207 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
2208 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 return NULL;
2210 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01002211 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02002212 if (file == NULL) {
2213 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
2214 return NULL;
2215 }
2216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 /* sys.stdout may be None when FILE* stdout isn't connected */
2218 if (file == Py_None)
2219 Py_RETURN_NONE;
2220 }
Guido van Rossum34343512006-11-30 22:13:52 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 if (sep == Py_None) {
2223 sep = NULL;
2224 }
2225 else if (sep && !PyUnicode_Check(sep)) {
2226 PyErr_Format(PyExc_TypeError,
2227 "sep must be None or a string, not %.200s",
2228 sep->ob_type->tp_name);
2229 return NULL;
2230 }
2231 if (end == Py_None) {
2232 end = NULL;
2233 }
2234 else if (end && !PyUnicode_Check(end)) {
2235 PyErr_Format(PyExc_TypeError,
2236 "end must be None or a string, not %.200s",
2237 end->ob_type->tp_name);
2238 return NULL;
2239 }
Guido van Rossum34343512006-11-30 22:13:52 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 for (i = 0; i < PyTuple_Size(args); i++) {
2242 if (i > 0) {
2243 if (sep == NULL)
2244 err = PyFile_WriteString(" ", file);
2245 else
2246 err = PyFile_WriteObject(sep, file,
2247 Py_PRINT_RAW);
2248 if (err)
2249 return NULL;
2250 }
2251 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
2252 Py_PRINT_RAW);
2253 if (err)
2254 return NULL;
2255 }
Guido van Rossum34343512006-11-30 22:13:52 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 if (end == NULL)
2258 err = PyFile_WriteString("\n", file);
2259 else
2260 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
2261 if (err)
2262 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00002263
Georg Brandlbc3b6822012-01-13 19:41:25 +01002264 if (flush != NULL) {
2265 PyObject *tmp;
2266 int do_flush = PyObject_IsTrue(flush);
2267 if (do_flush == -1)
2268 return NULL;
2269 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01002270 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01002271 if (tmp == NULL)
2272 return NULL;
2273 else
2274 Py_DECREF(tmp);
2275 }
2276 }
2277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00002279}
2280
2281PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002282"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00002283\n\
2284Prints the values to a stream, or to sys.stdout by default.\n\
2285Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002286file: a file-like object (stream); defaults to the current sys.stdout.\n\
2287sep: string inserted between values, default a space.\n\
2288end: string appended after the last value, default a newline.\n\
2289flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00002290
2291
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002292/*[clinic input]
2293input as builtin_input
2294
2295 prompt: object(c_default="NULL") = None
2296 /
2297
2298Read a string from standard input. The trailing newline is stripped.
2299
2300The prompt string, if given, is printed to standard output without a
2301trailing newline before reading input.
2302
2303If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
2304On *nix systems, readline is used if available.
2305[clinic start generated code]*/
2306
2307PyDoc_STRVAR(builtin_input__doc__,
2308"input($module, prompt=None, /)\n"
2309"--\n"
2310"\n"
2311"Read a string from standard input. The trailing newline is stripped.\n"
2312"\n"
2313"The prompt string, if given, is printed to standard output without a\n"
2314"trailing newline before reading input.\n"
2315"\n"
2316"If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.\n"
2317"On *nix systems, readline is used if available.");
2318
2319#define BUILTIN_INPUT_METHODDEF \
2320 {"input", (PyCFunction)builtin_input, METH_VARARGS, builtin_input__doc__},
2321
Guido van Rossuma88a0332007-02-26 16:59:55 +00002322static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002323builtin_input_impl(PyModuleDef *module, PyObject *prompt);
2324
2325static PyObject *
2326builtin_input(PyModuleDef *module, PyObject *args)
Guido van Rossuma88a0332007-02-26 16:59:55 +00002327{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002328 PyObject *return_value = NULL;
2329 PyObject *prompt = NULL;
2330
2331 if (!PyArg_UnpackTuple(args, "input",
2332 0, 1,
2333 &prompt))
2334 goto exit;
2335 return_value = builtin_input_impl(module, prompt);
2336
2337exit:
2338 return return_value;
2339}
2340
2341static PyObject *
2342builtin_input_impl(PyModuleDef *module, PyObject *prompt)
2343/*[clinic end generated code: output=69323bf5695f7c9c input=5e8bb70c2908fe3c]*/
2344{
Victor Stinnerbd303c12013-11-07 23:07:29 +01002345 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
2346 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
2347 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 PyObject *tmp;
2349 long fd;
2350 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 /* Check that stdin/out/err are intact */
2353 if (fin == NULL || fin == Py_None) {
2354 PyErr_SetString(PyExc_RuntimeError,
2355 "input(): lost sys.stdin");
2356 return NULL;
2357 }
2358 if (fout == NULL || fout == Py_None) {
2359 PyErr_SetString(PyExc_RuntimeError,
2360 "input(): lost sys.stdout");
2361 return NULL;
2362 }
2363 if (ferr == NULL || ferr == Py_None) {
2364 PyErr_SetString(PyExc_RuntimeError,
2365 "input(): lost sys.stderr");
2366 return NULL;
2367 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002370 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 if (tmp == NULL)
2372 PyErr_Clear();
2373 else
2374 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 /* We should only use (GNU) readline if Python's sys.stdin and
2377 sys.stdout are the same as C's stdin and stdout, because we
2378 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002379 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 if (tmp == NULL) {
2381 PyErr_Clear();
2382 tty = 0;
2383 }
2384 else {
2385 fd = PyLong_AsLong(tmp);
2386 Py_DECREF(tmp);
2387 if (fd < 0 && PyErr_Occurred())
2388 return NULL;
2389 tty = fd == fileno(stdin) && isatty(fd);
2390 }
2391 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002392 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 if (tmp == NULL)
2394 PyErr_Clear();
2395 else {
2396 fd = PyLong_AsLong(tmp);
2397 Py_DECREF(tmp);
2398 if (fd < 0 && PyErr_Occurred())
2399 return NULL;
2400 tty = fd == fileno(stdout) && isatty(fd);
2401 }
2402 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* If we're interactive, use (GNU) readline */
2405 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002406 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002407 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002408 char *s = NULL;
2409 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2410 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
2411 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002413 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002414
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002415 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002416 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002417 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 /* stdin is a text stream, so it must have an
2419 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002420 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00002421 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002422 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
2423 if (!stdin_encoding_str || !stdin_errors_str)
2424 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002425 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 if (tmp == NULL)
2427 PyErr_Clear();
2428 else
2429 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002430 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002431 /* We have a prompt, encode it as stdout would */
2432 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002434 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002435 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002436 if (!stdout_encoding || !stdout_errors)
2437 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00002438 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002439 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
2440 if (!stdout_encoding_str || !stdout_errors_str)
2441 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002442 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002443 if (stringpo == NULL)
2444 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002446 stdout_encoding_str, stdout_errors_str);
2447 Py_CLEAR(stdout_encoding);
2448 Py_CLEAR(stdout_errors);
2449 Py_CLEAR(stringpo);
2450 if (po == NULL)
2451 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002452 promptstr = PyBytes_AsString(po);
2453 if (promptstr == NULL)
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002454 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 }
2456 else {
2457 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002458 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002460 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002462 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 if (!PyErr_Occurred())
2464 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002465 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002467
2468 len = strlen(s);
2469 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 PyErr_SetNone(PyExc_EOFError);
2471 result = NULL;
2472 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002473 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 if (len > PY_SSIZE_T_MAX) {
2475 PyErr_SetString(PyExc_OverflowError,
2476 "input: input too long");
2477 result = NULL;
2478 }
2479 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002480 len--; /* strip trailing '\n' */
2481 if (len != 0 && s[len-1] == '\r')
2482 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002483 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2484 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 }
2486 }
2487 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002488 Py_DECREF(stdin_errors);
2489 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 PyMem_FREE(s);
2491 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002492 _readline_errors:
2493 Py_XDECREF(stdin_encoding);
2494 Py_XDECREF(stdout_encoding);
2495 Py_XDECREF(stdin_errors);
2496 Py_XDECREF(stdout_errors);
2497 Py_XDECREF(po);
2498 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002502 if (prompt != NULL) {
2503 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 return NULL;
2505 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002506 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 if (tmp == NULL)
2508 PyErr_Clear();
2509 else
2510 Py_DECREF(tmp);
2511 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002512}
2513
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002514
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002515/*[clinic input]
2516repr as builtin_repr
2517
2518 obj: 'O'
2519 /
2520
2521Return the canonical string representation of the object.
2522
2523For many object types, including most builtins, eval(repr(obj)) == obj.
2524[clinic start generated code]*/
2525
2526PyDoc_STRVAR(builtin_repr__doc__,
2527"repr($module, obj, /)\n"
2528"--\n"
2529"\n"
2530"Return the canonical string representation of the object.\n"
2531"\n"
2532"For many object types, including most builtins, eval(repr(obj)) == obj.");
2533
2534#define BUILTIN_REPR_METHODDEF \
2535 {"repr", (PyCFunction)builtin_repr, METH_O, builtin_repr__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002536
Guido van Rossum79f25d91997-04-29 20:08:16 +00002537static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002538builtin_repr(PyModuleDef *module, PyObject *obj)
2539/*[clinic end generated code: output=988980120f39e2fa input=a2bca0f38a5a924d]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002540{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002541 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002542}
2543
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002544
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002545/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2546 * or a semantic change to accept None for "ndigits"
2547 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002548static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002549builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 PyObject *ndigits = NULL;
2552 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002553 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2556 kwlist, &number, &ndigits))
2557 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 if (Py_TYPE(number)->tp_dict == NULL) {
2560 if (PyType_Ready(Py_TYPE(number)) < 0)
2561 return NULL;
2562 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002563
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002564 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002566 if (!PyErr_Occurred())
2567 PyErr_Format(PyExc_TypeError,
2568 "type %.100s doesn't define __round__ method",
2569 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 return NULL;
2571 }
Alex Martelliae211f92007-08-22 23:21:33 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002574 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002576 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2577 Py_DECREF(round);
2578 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002579}
2580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002581PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002582"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002583\n\
2584Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002585This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002586same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002587
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002588
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002589/*AC: we need to keep the kwds dict intact to easily call into the
2590 * list.sort method, which isn't currently supported in AC. So we just use
2591 * the initially generated signature with a custom implementation.
2592 */
2593/* [disabled clinic input]
2594sorted as builtin_sorted
2595
2596 iterable as seq: 'O'
2597 key as keyfunc: 'O' = None
2598 reverse: 'O' = False
2599
2600Return a new list containing all items from the iterable in ascending order.
2601
2602A custom key function can be supplied to customise the sort order, and the
2603reverse flag can be set to request the result in descending order.
2604[end disabled clinic input]*/
2605
2606PyDoc_STRVAR(builtin_sorted__doc__,
2607"sorted($module, iterable, key=None, reverse=False)\n"
2608"--\n"
2609"\n"
2610"Return a new list containing all items from the iterable in ascending order.\n"
2611"\n"
2612"A custom key function can be supplied to customise the sort order, and the\n"
2613"reverse flag can be set to request the result in descending order.");
2614
2615#define BUILTIN_SORTED_METHODDEF \
2616 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
2617
Raymond Hettinger64958a12003-12-17 20:43:33 +00002618static PyObject *
2619builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
2622 PyObject *callable;
2623 static char *kwlist[] = {"iterable", "key", "reverse", 0};
2624 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 /* args 1-3 should match listsort in Objects/listobject.c */
2627 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
2628 kwlist, &seq, &keyfunc, &reverse))
2629 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 newlist = PySequence_List(seq);
2632 if (newlist == NULL)
2633 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002634
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002635 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 if (callable == NULL) {
2637 Py_DECREF(newlist);
2638 return NULL;
2639 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 newargs = PyTuple_GetSlice(args, 1, 4);
2642 if (newargs == NULL) {
2643 Py_DECREF(newlist);
2644 Py_DECREF(callable);
2645 return NULL;
2646 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 v = PyObject_Call(callable, newargs, kwds);
2649 Py_DECREF(newargs);
2650 Py_DECREF(callable);
2651 if (v == NULL) {
2652 Py_DECREF(newlist);
2653 return NULL;
2654 }
2655 Py_DECREF(v);
2656 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002657}
2658
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002659
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002660/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002661static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002662builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 PyObject *v = NULL;
2665 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2668 return NULL;
2669 if (v == NULL) {
2670 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002671 if (d == NULL)
2672 return NULL;
2673 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 }
2675 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002676 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 if (d == NULL) {
2678 PyErr_SetString(PyExc_TypeError,
2679 "vars() argument must have __dict__ attribute");
2680 return NULL;
2681 }
2682 }
2683 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002684}
2685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002686PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002687"vars([object]) -> dictionary\n\
2688\n\
2689Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002690With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002691
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002692
2693/*[clinic input]
2694sum as builtin_sum
2695
2696 iterable: 'O'
2697 start: object(c_default="NULL") = 0
2698 /
2699
2700Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2701
2702When the iterable is empty, return the start value.
2703This function is intended specifically for use with numeric values and may
2704reject non-numeric types.
2705[clinic start generated code]*/
2706
2707PyDoc_STRVAR(builtin_sum__doc__,
2708"sum($module, iterable, start=0, /)\n"
2709"--\n"
2710"\n"
2711"Return the sum of a \'start\' value (default: 0) plus an iterable of numbers\n"
2712"\n"
2713"When the iterable is empty, return the start value.\n"
2714"This function is intended specifically for use with numeric values and may\n"
2715"reject non-numeric types.");
2716
2717#define BUILTIN_SUM_METHODDEF \
2718 {"sum", (PyCFunction)builtin_sum, METH_VARARGS, builtin_sum__doc__},
2719
2720static PyObject *
2721builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start);
2722
2723static PyObject *
2724builtin_sum(PyModuleDef *module, PyObject *args)
Alex Martellia70b1912003-04-22 08:12:33 +00002725{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002726 PyObject *return_value = NULL;
2727 PyObject *iterable;
2728 PyObject *start = NULL;
2729
2730 if (!PyArg_UnpackTuple(args, "sum",
2731 1, 2,
2732 &iterable, &start))
2733 goto exit;
2734 return_value = builtin_sum_impl(module, iterable, start);
2735
2736exit:
2737 return return_value;
2738}
2739
2740static PyObject *
2741builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start)
2742/*[clinic end generated code: output=b42652a0d5f64f6b input=90ae7a242cfcf025]*/
2743{
2744 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002746
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002747 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 if (iter == NULL)
2749 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 if (result == NULL) {
2752 result = PyLong_FromLong(0);
2753 if (result == NULL) {
2754 Py_DECREF(iter);
2755 return NULL;
2756 }
2757 } else {
2758 /* reject string values for 'start' parameter */
2759 if (PyUnicode_Check(result)) {
2760 PyErr_SetString(PyExc_TypeError,
2761 "sum() can't sum strings [use ''.join(seq) instead]");
2762 Py_DECREF(iter);
2763 return NULL;
2764 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002765 if (PyBytes_Check(result)) {
2766 PyErr_SetString(PyExc_TypeError,
2767 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002768 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002769 return NULL;
2770 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 if (PyByteArray_Check(result)) {
2772 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002773 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 Py_DECREF(iter);
2775 return NULL;
2776 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 Py_INCREF(result);
2778 }
Alex Martellia70b1912003-04-22 08:12:33 +00002779
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002780#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2782 Assumes all inputs are the same type. If the assumption fails, default
2783 to the more general routine.
2784 */
2785 if (PyLong_CheckExact(result)) {
2786 int overflow;
2787 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2788 /* If this already overflowed, don't even enter the loop. */
2789 if (overflow == 0) {
2790 Py_DECREF(result);
2791 result = NULL;
2792 }
2793 while(result == NULL) {
2794 item = PyIter_Next(iter);
2795 if (item == NULL) {
2796 Py_DECREF(iter);
2797 if (PyErr_Occurred())
2798 return NULL;
2799 return PyLong_FromLong(i_result);
2800 }
2801 if (PyLong_CheckExact(item)) {
2802 long b = PyLong_AsLongAndOverflow(item, &overflow);
2803 long x = i_result + b;
2804 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2805 i_result = x;
2806 Py_DECREF(item);
2807 continue;
2808 }
2809 }
2810 /* Either overflowed or is not an int. Restore real objects and process normally */
2811 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002812 if (result == NULL) {
2813 Py_DECREF(item);
2814 Py_DECREF(iter);
2815 return NULL;
2816 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 temp = PyNumber_Add(result, item);
2818 Py_DECREF(result);
2819 Py_DECREF(item);
2820 result = temp;
2821 if (result == NULL) {
2822 Py_DECREF(iter);
2823 return NULL;
2824 }
2825 }
2826 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 if (PyFloat_CheckExact(result)) {
2829 double f_result = PyFloat_AS_DOUBLE(result);
2830 Py_DECREF(result);
2831 result = NULL;
2832 while(result == NULL) {
2833 item = PyIter_Next(iter);
2834 if (item == NULL) {
2835 Py_DECREF(iter);
2836 if (PyErr_Occurred())
2837 return NULL;
2838 return PyFloat_FromDouble(f_result);
2839 }
2840 if (PyFloat_CheckExact(item)) {
2841 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2842 f_result += PyFloat_AS_DOUBLE(item);
2843 PyFPE_END_PROTECT(f_result)
2844 Py_DECREF(item);
2845 continue;
2846 }
2847 if (PyLong_CheckExact(item)) {
2848 long value;
2849 int overflow;
2850 value = PyLong_AsLongAndOverflow(item, &overflow);
2851 if (!overflow) {
2852 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2853 f_result += (double)value;
2854 PyFPE_END_PROTECT(f_result)
2855 Py_DECREF(item);
2856 continue;
2857 }
2858 }
2859 result = PyFloat_FromDouble(f_result);
2860 temp = PyNumber_Add(result, item);
2861 Py_DECREF(result);
2862 Py_DECREF(item);
2863 result = temp;
2864 if (result == NULL) {
2865 Py_DECREF(iter);
2866 return NULL;
2867 }
2868 }
2869 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002870#endif
2871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 for(;;) {
2873 item = PyIter_Next(iter);
2874 if (item == NULL) {
2875 /* error, or end-of-sequence */
2876 if (PyErr_Occurred()) {
2877 Py_DECREF(result);
2878 result = NULL;
2879 }
2880 break;
2881 }
2882 /* It's tempting to use PyNumber_InPlaceAdd instead of
2883 PyNumber_Add here, to avoid quadratic running time
2884 when doing 'sum(list_of_lists, [])'. However, this
2885 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 empty = []
2888 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 would change the value of empty. */
2891 temp = PyNumber_Add(result, item);
2892 Py_DECREF(result);
2893 Py_DECREF(item);
2894 result = temp;
2895 if (result == NULL)
2896 break;
2897 }
2898 Py_DECREF(iter);
2899 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002900}
2901
Alex Martellia70b1912003-04-22 08:12:33 +00002902
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002903/*[clinic input]
2904isinstance as builtin_isinstance
2905
2906 obj: 'O'
2907 class_or_tuple: 'O'
2908 /
2909
2910Return whether an object is an instance of a class or of a subclass thereof.
2911
2912A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2913check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2914or ...`` etc.
2915[clinic start generated code]*/
2916
2917PyDoc_STRVAR(builtin_isinstance__doc__,
2918"isinstance($module, obj, class_or_tuple, /)\n"
2919"--\n"
2920"\n"
2921"Return whether an object is an instance of a class or of a subclass thereof.\n"
2922"\n"
2923"A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to\n"
2924"check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)\n"
2925"or ...`` etc.");
2926
2927#define BUILTIN_ISINSTANCE_METHODDEF \
2928 {"isinstance", (PyCFunction)builtin_isinstance, METH_VARARGS, builtin_isinstance__doc__},
Alex Martellia70b1912003-04-22 08:12:33 +00002929
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002930static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002931builtin_isinstance_impl(PyModuleDef *module, PyObject *obj, PyObject *class_or_tuple);
2932
2933static PyObject *
2934builtin_isinstance(PyModuleDef *module, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002935{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002936 PyObject *return_value = NULL;
2937 PyObject *obj;
2938 PyObject *class_or_tuple;
2939
2940 if (!PyArg_UnpackTuple(args, "isinstance",
2941 2, 2,
2942 &obj, &class_or_tuple))
2943 goto exit;
2944 return_value = builtin_isinstance_impl(module, obj, class_or_tuple);
2945
2946exit:
2947 return return_value;
2948}
2949
2950static PyObject *
2951builtin_isinstance_impl(PyModuleDef *module, PyObject *obj, PyObject *class_or_tuple)
2952/*[clinic end generated code: output=847df57fef8ddea7 input=cf9eb0ad6bb9bad6]*/
2953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002955
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002956 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 if (retval < 0)
2958 return NULL;
2959 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002960}
2961
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002962
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002963/*[clinic input]
2964issubclass as builtin_issubclass
2965
2966 cls: 'O'
2967 class_or_tuple: 'O'
2968 /
2969
2970Return whether 'cls' is a derived from another class or is the same class.
2971
2972A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2973check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2974or ...`` etc.
2975[clinic start generated code]*/
2976
2977PyDoc_STRVAR(builtin_issubclass__doc__,
2978"issubclass($module, cls, class_or_tuple, /)\n"
2979"--\n"
2980"\n"
2981"Return whether \'cls\' is a derived from another class or is the same class.\n"
2982"\n"
2983"A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to\n"
2984"check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)\n"
2985"or ...`` etc.");
2986
2987#define BUILTIN_ISSUBCLASS_METHODDEF \
2988 {"issubclass", (PyCFunction)builtin_issubclass, METH_VARARGS, builtin_issubclass__doc__},
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002989
2990static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002991builtin_issubclass_impl(PyModuleDef *module, PyObject *cls, PyObject *class_or_tuple);
2992
2993static PyObject *
2994builtin_issubclass(PyModuleDef *module, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002995{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002996 PyObject *return_value = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 PyObject *cls;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002998 PyObject *class_or_tuple;
2999
3000 if (!PyArg_UnpackTuple(args, "issubclass",
3001 2, 2,
3002 &cls, &class_or_tuple))
3003 goto exit;
3004 return_value = builtin_issubclass_impl(module, cls, class_or_tuple);
3005
3006exit:
3007 return return_value;
3008}
3009
3010static PyObject *
3011builtin_issubclass_impl(PyModuleDef *module, PyObject *cls, PyObject *class_or_tuple)
3012/*[clinic end generated code: output=a0f8c03692e35474 input=923d03fa41fc352a]*/
3013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00003015
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003016 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 if (retval < 0)
3018 return NULL;
3019 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00003020}
3021
3022
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003023typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 PyObject_HEAD
3025 Py_ssize_t tuplesize;
3026 PyObject *ittuple; /* tuple of iterators */
3027 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003028} zipobject;
3029
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003030static PyObject *
3031zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00003032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 zipobject *lz;
3034 Py_ssize_t i;
3035 PyObject *ittuple; /* tuple of iterators */
3036 PyObject *result;
3037 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
3040 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 /* args must be a tuple */
3043 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 /* obtain iterators */
3046 ittuple = PyTuple_New(tuplesize);
3047 if (ittuple == NULL)
3048 return NULL;
3049 for (i=0; i < tuplesize; ++i) {
3050 PyObject *item = PyTuple_GET_ITEM(args, i);
3051 PyObject *it = PyObject_GetIter(item);
3052 if (it == NULL) {
3053 if (PyErr_ExceptionMatches(PyExc_TypeError))
3054 PyErr_Format(PyExc_TypeError,
3055 "zip argument #%zd must support iteration",
3056 i+1);
3057 Py_DECREF(ittuple);
3058 return NULL;
3059 }
3060 PyTuple_SET_ITEM(ittuple, i, it);
3061 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 /* create a result holder */
3064 result = PyTuple_New(tuplesize);
3065 if (result == NULL) {
3066 Py_DECREF(ittuple);
3067 return NULL;
3068 }
3069 for (i=0 ; i < tuplesize ; i++) {
3070 Py_INCREF(Py_None);
3071 PyTuple_SET_ITEM(result, i, Py_None);
3072 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 /* create zipobject structure */
3075 lz = (zipobject *)type->tp_alloc(type, 0);
3076 if (lz == NULL) {
3077 Py_DECREF(ittuple);
3078 Py_DECREF(result);
3079 return NULL;
3080 }
3081 lz->ittuple = ittuple;
3082 lz->tuplesize = tuplesize;
3083 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00003086}
3087
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003088static void
3089zip_dealloc(zipobject *lz)
3090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 PyObject_GC_UnTrack(lz);
3092 Py_XDECREF(lz->ittuple);
3093 Py_XDECREF(lz->result);
3094 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003095}
3096
3097static int
3098zip_traverse(zipobject *lz, visitproc visit, void *arg)
3099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 Py_VISIT(lz->ittuple);
3101 Py_VISIT(lz->result);
3102 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003103}
3104
3105static PyObject *
3106zip_next(zipobject *lz)
3107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 Py_ssize_t i;
3109 Py_ssize_t tuplesize = lz->tuplesize;
3110 PyObject *result = lz->result;
3111 PyObject *it;
3112 PyObject *item;
3113 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 if (tuplesize == 0)
3116 return NULL;
3117 if (Py_REFCNT(result) == 1) {
3118 Py_INCREF(result);
3119 for (i=0 ; i < tuplesize ; i++) {
3120 it = PyTuple_GET_ITEM(lz->ittuple, i);
3121 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03003122 if (item == NULL) {
3123 Py_DECREF(result);
3124 return NULL;
3125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 olditem = PyTuple_GET_ITEM(result, i);
3127 PyTuple_SET_ITEM(result, i, item);
3128 Py_DECREF(olditem);
3129 }
3130 } else {
3131 result = PyTuple_New(tuplesize);
3132 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03003133 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 for (i=0 ; i < tuplesize ; i++) {
3135 it = PyTuple_GET_ITEM(lz->ittuple, i);
3136 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03003137 if (item == NULL) {
3138 Py_DECREF(result);
3139 return NULL;
3140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 PyTuple_SET_ITEM(result, i, item);
3142 }
3143 }
3144 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003145}
Barry Warsawbd599b52000-08-03 15:45:29 +00003146
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003147static PyObject *
3148zip_reduce(zipobject *lz)
3149{
3150 /* Just recreate the zip with the internal iterator tuple */
3151 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
3152}
3153
3154static PyMethodDef zip_methods[] = {
3155 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
3156 {NULL, NULL} /* sentinel */
3157};
3158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003159PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003160"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00003161\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003162Return a zip object whose .__next__() method returns a tuple where\n\
3163the i-th element comes from the i-th iterable argument. The .__next__()\n\
3164method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00003165is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003166
3167PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3169 "zip", /* tp_name */
3170 sizeof(zipobject), /* tp_basicsize */
3171 0, /* tp_itemsize */
3172 /* methods */
3173 (destructor)zip_dealloc, /* tp_dealloc */
3174 0, /* tp_print */
3175 0, /* tp_getattr */
3176 0, /* tp_setattr */
3177 0, /* tp_reserved */
3178 0, /* tp_repr */
3179 0, /* tp_as_number */
3180 0, /* tp_as_sequence */
3181 0, /* tp_as_mapping */
3182 0, /* tp_hash */
3183 0, /* tp_call */
3184 0, /* tp_str */
3185 PyObject_GenericGetAttr, /* tp_getattro */
3186 0, /* tp_setattro */
3187 0, /* tp_as_buffer */
3188 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3189 Py_TPFLAGS_BASETYPE, /* tp_flags */
3190 zip_doc, /* tp_doc */
3191 (traverseproc)zip_traverse, /* tp_traverse */
3192 0, /* tp_clear */
3193 0, /* tp_richcompare */
3194 0, /* tp_weaklistoffset */
3195 PyObject_SelfIter, /* tp_iter */
3196 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003197 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 0, /* tp_members */
3199 0, /* tp_getset */
3200 0, /* tp_base */
3201 0, /* tp_dict */
3202 0, /* tp_descr_get */
3203 0, /* tp_descr_set */
3204 0, /* tp_dictoffset */
3205 0, /* tp_init */
3206 PyType_GenericAlloc, /* tp_alloc */
3207 zip_new, /* tp_new */
3208 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003209};
Barry Warsawbd599b52000-08-03 15:45:29 +00003210
3211
Guido van Rossum79f25d91997-04-29 20:08:16 +00003212static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 {"__build_class__", (PyCFunction)builtin___build_class__,
3214 METH_VARARGS | METH_KEYWORDS, build_class_doc},
3215 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003216 BUILTIN_ABS_METHODDEF
3217 BUILTIN_ALL_METHODDEF
3218 BUILTIN_ANY_METHODDEF
3219 BUILTIN_ASCII_METHODDEF
3220 BUILTIN_BIN_METHODDEF
3221 BUILTIN_CALLABLE_METHODDEF
3222 BUILTIN_CHR_METHODDEF
3223 BUILTIN_COMPILE_METHODDEF
3224 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003226 BUILTIN_DIVMOD_METHODDEF
3227 BUILTIN_EVAL_METHODDEF
3228 BUILTIN_EXEC_METHODDEF
3229 BUILTIN_FORMAT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003231 BUILTIN_GLOBALS_METHODDEF
3232 BUILTIN_HASATTR_METHODDEF
3233 BUILTIN_HASH_METHODDEF
3234 BUILTIN_HEX_METHODDEF
3235 BUILTIN_ID_METHODDEF
3236 BUILTIN_INPUT_METHODDEF
3237 BUILTIN_ISINSTANCE_METHODDEF
3238 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003240 BUILTIN_LEN_METHODDEF
3241 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
3243 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
3244 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003245 BUILTIN_OCT_METHODDEF
3246 BUILTIN_ORD_METHODDEF
3247 BUILTIN_POW_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003249 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003251 BUILTIN_SETATTR_METHODDEF
3252 BUILTIN_SORTED_METHODDEF
3253 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 {"vars", builtin_vars, METH_VARARGS, vars_doc},
3255 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00003256};
3257
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003258PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00003259"Built-in functions, exceptions, and other objects.\n\
3260\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003261Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00003262
Martin v. Löwis1a214512008-06-11 05:26:20 +00003263static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 PyModuleDef_HEAD_INIT,
3265 "builtins",
3266 builtin_doc,
3267 -1, /* multiple "initialization" just copies the module dict. */
3268 builtin_methods,
3269 NULL,
3270 NULL,
3271 NULL,
3272 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003273};
3274
3275
Guido van Rossum25ce5661997-08-02 03:10:38 +00003276PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003277_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00003278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04003280
3281 if (PyType_Ready(&PyFilter_Type) < 0 ||
3282 PyType_Ready(&PyMap_Type) < 0 ||
3283 PyType_Ready(&PyZip_Type) < 0)
3284 return NULL;
3285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 mod = PyModule_Create(&builtinsmodule);
3287 if (mod == NULL)
3288 return NULL;
3289 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00003290
Tim Peters7571a0f2003-03-23 17:52:28 +00003291#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 /* "builtins" exposes a number of statically allocated objects
3293 * that, before this code was added in 2.3, never showed up in
3294 * the list of "all objects" maintained by Py_TRACE_REFS. As a
3295 * result, programs leaking references to None and False (etc)
3296 * couldn't be diagnosed by examining sys.getobjects(0).
3297 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003298#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
3299#else
3300#define ADD_TO_ALL(OBJECT) (void)0
3301#endif
3302
Tim Peters4b7625e2001-09-13 21:37:17 +00003303#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
3305 return NULL; \
3306 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 SETBUILTIN("None", Py_None);
3309 SETBUILTIN("Ellipsis", Py_Ellipsis);
3310 SETBUILTIN("NotImplemented", Py_NotImplemented);
3311 SETBUILTIN("False", Py_False);
3312 SETBUILTIN("True", Py_True);
3313 SETBUILTIN("bool", &PyBool_Type);
3314 SETBUILTIN("memoryview", &PyMemoryView_Type);
3315 SETBUILTIN("bytearray", &PyByteArray_Type);
3316 SETBUILTIN("bytes", &PyBytes_Type);
3317 SETBUILTIN("classmethod", &PyClassMethod_Type);
3318 SETBUILTIN("complex", &PyComplex_Type);
3319 SETBUILTIN("dict", &PyDict_Type);
3320 SETBUILTIN("enumerate", &PyEnum_Type);
3321 SETBUILTIN("filter", &PyFilter_Type);
3322 SETBUILTIN("float", &PyFloat_Type);
3323 SETBUILTIN("frozenset", &PyFrozenSet_Type);
3324 SETBUILTIN("property", &PyProperty_Type);
3325 SETBUILTIN("int", &PyLong_Type);
3326 SETBUILTIN("list", &PyList_Type);
3327 SETBUILTIN("map", &PyMap_Type);
3328 SETBUILTIN("object", &PyBaseObject_Type);
3329 SETBUILTIN("range", &PyRange_Type);
3330 SETBUILTIN("reversed", &PyReversed_Type);
3331 SETBUILTIN("set", &PySet_Type);
3332 SETBUILTIN("slice", &PySlice_Type);
3333 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
3334 SETBUILTIN("str", &PyUnicode_Type);
3335 SETBUILTIN("super", &PySuper_Type);
3336 SETBUILTIN("tuple", &PyTuple_Type);
3337 SETBUILTIN("type", &PyType_Type);
3338 SETBUILTIN("zip", &PyZip_Type);
3339 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
3340 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
3341 Py_XDECREF(debug);
3342 return NULL;
3343 }
3344 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00003347#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00003348#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00003349}