blob: 068398fb9b8a7ed4edfbbeeba30358ac91433940 [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;
Nick Coghlande31b192011-10-23 22:04:16 +100056 int isclass;
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
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000726static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000727source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 char *str;
730 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 }
738 else if (!PyObject_CheckReadBuffer(cmd)) {
739 PyErr_Format(PyExc_TypeError,
740 "%s() arg 1 must be a %s object",
741 funcname, what);
742 return NULL;
743 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200744 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return NULL;
746 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200747
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300748 if (strlen(str) != (size_t)size) {
749 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 "source code string cannot contain null bytes");
751 return NULL;
752 }
753 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000754}
755
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000756/*[clinic input]
757compile as builtin_compile
758
759 source: 'O'
760 filename: object(converter="PyUnicode_FSDecoder")
761 mode: 's'
762 flags: 'i' = 0
763 dont_inherit: 'i' = 0
764 optimize: 'i' = -1
765
766Compile source into a code object that can be executed by exec() or eval().
767
768The source code may represent a Python module, statement or expression.
769The filename will be used for run-time error messages.
770The mode must be 'exec' to compile a module, 'single' to compile a
771single (interactive) statement, or 'eval' to compile an expression.
772The flags argument, if present, controls which future statements influence
773the compilation of the code.
774The dont_inherit argument, if non-zero, stops the compilation inheriting
775the effects of any future statements in effect in the code calling
776compile; if absent or zero these statements do influence the compilation,
777in addition to any features explicitly specified.
778[clinic start generated code]*/
779
780PyDoc_STRVAR(builtin_compile__doc__,
781"compile($module, /, source, filename, mode, flags=0, dont_inherit=0,\n"
782" optimize=-1)\n"
783"--\n"
784"\n"
785"Compile source into a code object that can be executed by exec() or eval().\n"
786"\n"
787"The source code may represent a Python module, statement or expression.\n"
788"The filename will be used for run-time error messages.\n"
789"The mode must be \'exec\' to compile a module, \'single\' to compile a\n"
790"single (interactive) statement, or \'eval\' to compile an expression.\n"
791"The flags argument, if present, controls which future statements influence\n"
792"the compilation of the code.\n"
793"The dont_inherit argument, if non-zero, stops the compilation inheriting\n"
794"the effects of any future statements in effect in the code calling\n"
795"compile; if absent or zero these statements do influence the compilation,\n"
796"in addition to any features explicitly specified.");
797
798#define BUILTIN_COMPILE_METHODDEF \
799 {"compile", (PyCFunction)builtin_compile, METH_VARARGS|METH_KEYWORDS, builtin_compile__doc__},
800
Guido van Rossum79f25d91997-04-29 20:08:16 +0000801static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000802builtin_compile_impl(PyModuleDef *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize);
803
804static PyObject *
805builtin_compile(PyModuleDef *module, PyObject *args, PyObject *kwargs)
806{
807 PyObject *return_value = NULL;
808 static char *_keywords[] = {"source", "filename", "mode", "flags", "dont_inherit", "optimize", NULL};
809 PyObject *source;
810 PyObject *filename;
811 const char *mode;
812 int flags = 0;
813 int dont_inherit = 0;
814 int optimize = -1;
815
816 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
817 "OO&s|iii:compile", _keywords,
818 &source, PyUnicode_FSDecoder, &filename, &mode, &flags, &dont_inherit, &optimize))
819 goto exit;
820 return_value = builtin_compile_impl(module, source, filename, mode, flags, dont_inherit, optimize);
821
822exit:
823 return return_value;
824}
825
826static PyObject *
827builtin_compile_impl(PyModuleDef *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize)
828/*[clinic end generated code: output=c72d197809d178fc input=c6212a9d21472f7e]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000831 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 int is_ast;
833 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000835 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000836
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000837 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000838
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000839 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
841 {
842 PyErr_SetString(PyExc_ValueError,
843 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000844 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 }
846 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000847
Georg Brandl8334fd92010-12-04 10:26:46 +0000848 if (optimize < -1 || optimize > 2) {
849 PyErr_SetString(PyExc_ValueError,
850 "compile(): invalid optimize value");
851 goto error;
852 }
853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 if (!dont_inherit) {
855 PyEval_MergeCompilerFlags(&cf);
856 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000857
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000858 if (strcmp(mode, "exec") == 0)
859 compile_mode = 0;
860 else if (strcmp(mode, "eval") == 0)
861 compile_mode = 1;
862 else if (strcmp(mode, "single") == 0)
863 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 else {
865 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000866 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000867 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000869
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000870 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000872 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000874 if (flags & PyCF_ONLY_AST) {
875 Py_INCREF(source);
876 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 }
878 else {
879 PyArena *arena;
880 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200883 if (arena == NULL)
884 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000885 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (mod == NULL) {
887 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000888 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500890 if (!PyAST_Validate(mod)) {
891 PyArena_Free(arena);
892 goto error;
893 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200894 result = (PyObject*)PyAST_CompileObject(mod, filename,
895 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyArena_Free(arena);
897 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000898 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000900
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000901 str = source_as_string(source, "compile", "string, bytes or AST", &cf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000903 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000904
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000905 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000906 goto finally;
907
908error:
909 result = NULL;
910finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200911 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000912 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000913}
914
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000915/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000916static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000917builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
922 return NULL;
923 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000924}
925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000926PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000927"dir([object]) -> list of strings\n"
928"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000929"If called without an argument, return the names in the current scope.\n"
930"Else, return an alphabetized list of names comprising (some of) the attributes\n"
931"of the given object, and of attributes reachable from it.\n"
932"If the object supplies a method named __dir__, it will be used; otherwise\n"
933"the default dir() logic is used and returns:\n"
934" for a module object: the module's attributes.\n"
935" for a class object: its attributes, and recursively the attributes\n"
936" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000937" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000938" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000939
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000940/*[clinic input]
941divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000942
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000943 x: 'O'
944 y: 'O'
945 /
946
947Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.
948[clinic start generated code]*/
949
950PyDoc_STRVAR(builtin_divmod__doc__,
951"divmod($module, x, y, /)\n"
952"--\n"
953"\n"
954"Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
955
956#define BUILTIN_DIVMOD_METHODDEF \
957 {"divmod", (PyCFunction)builtin_divmod, METH_VARARGS, builtin_divmod__doc__},
958
959static PyObject *
960builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y);
961
962static PyObject *
963builtin_divmod(PyModuleDef *module, PyObject *args)
964{
965 PyObject *return_value = NULL;
966 PyObject *x;
967 PyObject *y;
968
969 if (!PyArg_UnpackTuple(args, "divmod",
970 2, 2,
971 &x, &y))
972 goto exit;
973 return_value = builtin_divmod_impl(module, x, y);
974
975exit:
976 return return_value;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000977}
978
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000979static PyObject *
980builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y)
981/*[clinic end generated code: output=77e8d408b1338886 input=c9c617b7bb74c615]*/
982{
983 return PyNumber_Divmod(x, y);
984}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000985
986
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000987/*[clinic input]
988eval as builtin_eval
989
990 source: 'O'
991 globals: 'O' = None
992 locals: 'O' = None
993 /
994
995Evaluate the given source in the context of globals and locals.
996
997The source may be a string representing a Python expression
998or a code object as returned by compile().
999The globals must be a dictionary and locals can be any mapping,
1000defaulting to the current globals and locals.
1001If only globals is given, locals defaults to it.
1002[clinic start generated code]*/
1003
1004PyDoc_STRVAR(builtin_eval__doc__,
1005"eval($module, source, globals=None, locals=None, /)\n"
1006"--\n"
1007"\n"
1008"Evaluate the given source in the context of globals and locals.\n"
1009"\n"
1010"The source may be a string representing a Python expression\n"
1011"or a code object as returned by compile().\n"
1012"The globals must be a dictionary and locals can be any mapping,\n"
1013"defaulting to the current globals and locals.\n"
1014"If only globals is given, locals defaults to it.");
1015
1016#define BUILTIN_EVAL_METHODDEF \
1017 {"eval", (PyCFunction)builtin_eval, METH_VARARGS, builtin_eval__doc__},
1018
Guido van Rossum79f25d91997-04-29 20:08:16 +00001019static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001020builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals);
1021
1022static PyObject *
1023builtin_eval(PyModuleDef *module, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001024{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001025 PyObject *return_value = NULL;
1026 PyObject *source;
1027 PyObject *globals = Py_None;
1028 PyObject *locals = Py_None;
1029
1030 if (!PyArg_UnpackTuple(args, "eval",
1031 1, 3,
1032 &source, &globals, &locals))
1033 goto exit;
1034 return_value = builtin_eval_impl(module, source, globals, locals);
1035
1036exit:
1037 return return_value;
1038}
1039
1040static PyObject *
1041builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals)
1042/*[clinic end generated code: output=644fd59012538ce6 input=31e42c1d2125b50b]*/
1043{
1044 PyObject *result, *tmp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 char *str;
1046 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (locals != Py_None && !PyMapping_Check(locals)) {
1049 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
1050 return NULL;
1051 }
1052 if (globals != Py_None && !PyDict_Check(globals)) {
1053 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
1054 "globals must be a real dict; try eval(expr, {}, mapping)"
1055 : "globals must be a dict");
1056 return NULL;
1057 }
1058 if (globals == Py_None) {
1059 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001060 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001062 if (locals == NULL)
1063 return NULL;
1064 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 }
1066 else if (locals == Py_None)
1067 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 if (globals == NULL || locals == NULL) {
1070 PyErr_SetString(PyExc_TypeError,
1071 "eval must be given globals and locals "
1072 "when called without a frame");
1073 return NULL;
1074 }
Georg Brandl77c85e62005-09-15 10:46:13 +00001075
Victor Stinnerb44562b2013-11-06 19:03:11 +01001076 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
1077 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1078 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 return NULL;
1080 }
Tim Peters9fa96be2001-08-17 23:04:59 +00001081
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001082 if (PyCode_Check(source)) {
1083 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyErr_SetString(PyExc_TypeError,
1085 "code object passed to eval() may not contain free variables");
1086 return NULL;
1087 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001088 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 }
Tim Peters9fa96be2001-08-17 23:04:59 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001092 str = source_as_string(source, "eval", "string, bytes or code", &cf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (str == NULL)
1094 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 while (*str == ' ' || *str == '\t')
1097 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 (void)PyEval_MergeCompilerFlags(&cf);
1100 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1101 Py_XDECREF(tmp);
1102 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001103}
1104
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001105/*[clinic input]
1106exec as builtin_exec
1107
1108 source: 'O'
1109 globals: 'O' = None
1110 locals: 'O' = None
1111 /
1112
1113Execute the given source in the context of globals and locals.
1114
1115The source may be a string representing one or more Python statements
1116or a code object as returned by compile().
1117The globals must be a dictionary and locals can be any mapping,
1118defaulting to the current globals and locals.
1119If only globals is given, locals defaults to it.
1120[clinic start generated code]*/
1121
1122PyDoc_STRVAR(builtin_exec__doc__,
1123"exec($module, source, globals=None, locals=None, /)\n"
1124"--\n"
1125"\n"
1126"Execute the given source in the context of globals and locals.\n"
1127"\n"
1128"The source may be a string representing one or more Python statements\n"
1129"or a code object as returned by compile().\n"
1130"The globals must be a dictionary and locals can be any mapping,\n"
1131"defaulting to the current globals and locals.\n"
1132"If only globals is given, locals defaults to it.");
1133
1134#define BUILTIN_EXEC_METHODDEF \
1135 {"exec", (PyCFunction)builtin_exec, METH_VARARGS, builtin_exec__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001136
Georg Brandl7cae87c2006-09-06 06:51:57 +00001137static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001138builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals);
1139
1140static PyObject *
1141builtin_exec(PyModuleDef *module, PyObject *args)
1142{
1143 PyObject *return_value = NULL;
1144 PyObject *source;
1145 PyObject *globals = Py_None;
1146 PyObject *locals = Py_None;
1147
1148 if (!PyArg_UnpackTuple(args, "exec",
1149 1, 3,
1150 &source, &globals, &locals))
1151 goto exit;
1152 return_value = builtin_exec_impl(module, source, globals, locals);
1153
1154exit:
1155 return return_value;
1156}
1157
1158static PyObject *
1159builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals, PyObject *locals)
1160/*[clinic end generated code: output=0281b48bfa8e3c87 input=536e057b5e00d89e]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (globals == Py_None) {
1165 globals = PyEval_GetGlobals();
1166 if (locals == Py_None) {
1167 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001168 if (locals == NULL)
1169 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 }
1171 if (!globals || !locals) {
1172 PyErr_SetString(PyExc_SystemError,
1173 "globals and locals cannot be NULL");
1174 return NULL;
1175 }
1176 }
1177 else if (locals == Py_None)
1178 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001181 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 globals->ob_type->tp_name);
1183 return NULL;
1184 }
1185 if (!PyMapping_Check(locals)) {
1186 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001187 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 locals->ob_type->tp_name);
1189 return NULL;
1190 }
Victor Stinnerb44562b2013-11-06 19:03:11 +01001191 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
1192 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1193 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 return NULL;
1195 }
1196
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001197 if (PyCode_Check(source)) {
1198 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyErr_SetString(PyExc_TypeError,
1200 "code object passed to exec() may not "
1201 "contain free variables");
1202 return NULL;
1203 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001204 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 }
1206 else {
1207 char *str;
1208 PyCompilerFlags cf;
1209 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001210 str = source_as_string(source, "exec",
1211 "string, bytes or code", &cf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (str == NULL)
1213 return NULL;
1214 if (PyEval_MergeCompilerFlags(&cf))
1215 v = PyRun_StringFlags(str, Py_file_input, globals,
1216 locals, &cf);
1217 else
1218 v = PyRun_String(str, Py_file_input, globals, locals);
1219 }
1220 if (v == NULL)
1221 return NULL;
1222 Py_DECREF(v);
1223 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001224}
1225
Georg Brandl7cae87c2006-09-06 06:51:57 +00001226
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001227/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001228static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001229builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 PyObject *v, *result, *dflt = NULL;
1232 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
1235 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!PyUnicode_Check(name)) {
1238 PyErr_SetString(PyExc_TypeError,
1239 "getattr(): attribute name must be string");
1240 return NULL;
1241 }
1242 result = PyObject_GetAttr(v, name);
1243 if (result == NULL && dflt != NULL &&
1244 PyErr_ExceptionMatches(PyExc_AttributeError))
1245 {
1246 PyErr_Clear();
1247 Py_INCREF(dflt);
1248 result = dflt;
1249 }
1250 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001251}
1252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001254"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001255\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001256Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1257When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001258exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001259
1260
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001261/*[clinic input]
1262globals as builtin_globals
1263
1264Return the dictionary containing the current scope's global variables.
1265
1266NOTE: Updates to this dictionary *will* affect name lookups in the current
1267global scope and vice-versa.
1268[clinic start generated code]*/
1269
1270PyDoc_STRVAR(builtin_globals__doc__,
1271"globals($module, /)\n"
1272"--\n"
1273"\n"
1274"Return the dictionary containing the current scope\'s global variables.\n"
1275"\n"
1276"NOTE: Updates to this dictionary *will* affect name lookups in the current\n"
1277"global scope and vice-versa.");
1278
1279#define BUILTIN_GLOBALS_METHODDEF \
1280 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, builtin_globals__doc__},
1281
Guido van Rossum79f25d91997-04-29 20:08:16 +00001282static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001283builtin_globals_impl(PyModuleDef *module);
1284
1285static PyObject *
1286builtin_globals(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1287{
1288 return builtin_globals_impl(module);
1289}
1290
1291static PyObject *
1292builtin_globals_impl(PyModuleDef *module)
1293/*[clinic end generated code: output=048640f58b1f20ad input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 d = PyEval_GetGlobals();
1298 Py_XINCREF(d);
1299 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001300}
1301
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001302
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001303/*[clinic input]
1304hasattr as builtin_hasattr
1305
1306 obj: 'O'
1307 name: 'O'
1308 /
1309
1310Return whether the object has an attribute with the given name.
1311
1312This is done by calling getattr(obj, name) and catching AttributeError.
1313[clinic start generated code]*/
1314
1315PyDoc_STRVAR(builtin_hasattr__doc__,
1316"hasattr($module, obj, name, /)\n"
1317"--\n"
1318"\n"
1319"Return whether the object has an attribute with the given name.\n"
1320"\n"
1321"This is done by calling getattr(obj, name) and catching AttributeError.");
1322
1323#define BUILTIN_HASATTR_METHODDEF \
1324 {"hasattr", (PyCFunction)builtin_hasattr, METH_VARARGS, builtin_hasattr__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001325
Guido van Rossum79f25d91997-04-29 20:08:16 +00001326static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001327builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name);
1328
1329static PyObject *
1330builtin_hasattr(PyModuleDef *module, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001331{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001332 PyObject *return_value = NULL;
1333 PyObject *obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001335
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001336 if (!PyArg_UnpackTuple(args, "hasattr",
1337 2, 2,
1338 &obj, &name))
1339 goto exit;
1340 return_value = builtin_hasattr_impl(module, obj, name);
1341
1342exit:
1343 return return_value;
1344}
1345
1346static PyObject *
1347builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
1348/*[clinic end generated code: output=e0bd996ef73d1217 input=b50bad5f739ea10d]*/
1349{
1350 PyObject *v;
1351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if (!PyUnicode_Check(name)) {
1353 PyErr_SetString(PyExc_TypeError,
1354 "hasattr(): attribute name must be string");
1355 return NULL;
1356 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001357 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001359 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001361 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001363 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 }
1365 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001366 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001367}
1368
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001369
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001370/* AC: gdb's integration with CPython relies on builtin_id having
1371 * the *exact* parameter names of "self" and "v", so we ensure we
1372 * preserve those name rather than using the AC defaults.
1373 */
1374/*[clinic input]
1375id as builtin_id
1376
1377 self: self(type="PyModuleDef *")
1378 obj as v: 'O'
1379 /
1380
1381Return the identity of an object.
1382
1383This is guaranteed to be unique among simultaneously existing objects.
1384(CPython uses the object's memory address.)
1385[clinic start generated code]*/
1386
1387PyDoc_STRVAR(builtin_id__doc__,
1388"id($module, obj, /)\n"
1389"--\n"
1390"\n"
1391"Return the identity of an object.\n"
1392"\n"
1393"This is guaranteed to be unique among simultaneously existing objects.\n"
1394"(CPython uses the object\'s memory address.)");
1395
1396#define BUILTIN_ID_METHODDEF \
1397 {"id", (PyCFunction)builtin_id, METH_O, builtin_id__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001398
Guido van Rossum79f25d91997-04-29 20:08:16 +00001399static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001400builtin_id(PyModuleDef *self, PyObject *v)
1401/*[clinic end generated code: output=f54da09c91992e63 input=a1f988d98357341d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001404}
1405
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001406
Raymond Hettingera6c60372008-03-13 01:26:19 +00001407/* map object ************************************************************/
1408
1409typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyObject_HEAD
1411 PyObject *iters;
1412 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001413} mapobject;
1414
Guido van Rossum79f25d91997-04-29 20:08:16 +00001415static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001416map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 PyObject *it, *iters, *func;
1419 mapobject *lz;
1420 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1423 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 numargs = PyTuple_Size(args);
1426 if (numargs < 2) {
1427 PyErr_SetString(PyExc_TypeError,
1428 "map() must have at least two arguments.");
1429 return NULL;
1430 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 iters = PyTuple_New(numargs-1);
1433 if (iters == NULL)
1434 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 for (i=1 ; i<numargs ; i++) {
1437 /* Get iterator. */
1438 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1439 if (it == NULL) {
1440 Py_DECREF(iters);
1441 return NULL;
1442 }
1443 PyTuple_SET_ITEM(iters, i-1, it);
1444 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 /* create mapobject structure */
1447 lz = (mapobject *)type->tp_alloc(type, 0);
1448 if (lz == NULL) {
1449 Py_DECREF(iters);
1450 return NULL;
1451 }
1452 lz->iters = iters;
1453 func = PyTuple_GET_ITEM(args, 0);
1454 Py_INCREF(func);
1455 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001458}
1459
1460static void
1461map_dealloc(mapobject *lz)
1462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 PyObject_GC_UnTrack(lz);
1464 Py_XDECREF(lz->iters);
1465 Py_XDECREF(lz->func);
1466 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001467}
1468
1469static int
1470map_traverse(mapobject *lz, visitproc visit, void *arg)
1471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 Py_VISIT(lz->iters);
1473 Py_VISIT(lz->func);
1474 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001475}
1476
1477static PyObject *
1478map_next(mapobject *lz)
1479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyObject *val;
1481 PyObject *argtuple;
1482 PyObject *result;
1483 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 numargs = PyTuple_Size(lz->iters);
1486 argtuple = PyTuple_New(numargs);
1487 if (argtuple == NULL)
1488 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 for (i=0 ; i<numargs ; i++) {
1491 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1492 if (val == NULL) {
1493 Py_DECREF(argtuple);
1494 return NULL;
1495 }
1496 PyTuple_SET_ITEM(argtuple, i, val);
1497 }
1498 result = PyObject_Call(lz->func, argtuple, NULL);
1499 Py_DECREF(argtuple);
1500 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001501}
1502
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001503static PyObject *
1504map_reduce(mapobject *lz)
1505{
1506 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1507 PyObject *args = PyTuple_New(numargs+1);
1508 Py_ssize_t i;
1509 if (args == NULL)
1510 return NULL;
1511 Py_INCREF(lz->func);
1512 PyTuple_SET_ITEM(args, 0, lz->func);
1513 for (i = 0; i<numargs; i++){
1514 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1515 Py_INCREF(it);
1516 PyTuple_SET_ITEM(args, i+1, it);
1517 }
1518
1519 return Py_BuildValue("ON", Py_TYPE(lz), args);
1520}
1521
1522static PyMethodDef map_methods[] = {
1523 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1524 {NULL, NULL} /* sentinel */
1525};
1526
1527
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001528PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001529"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001530\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001531Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001533
Raymond Hettingera6c60372008-03-13 01:26:19 +00001534PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1536 "map", /* tp_name */
1537 sizeof(mapobject), /* tp_basicsize */
1538 0, /* tp_itemsize */
1539 /* methods */
1540 (destructor)map_dealloc, /* tp_dealloc */
1541 0, /* tp_print */
1542 0, /* tp_getattr */
1543 0, /* tp_setattr */
1544 0, /* tp_reserved */
1545 0, /* tp_repr */
1546 0, /* tp_as_number */
1547 0, /* tp_as_sequence */
1548 0, /* tp_as_mapping */
1549 0, /* tp_hash */
1550 0, /* tp_call */
1551 0, /* tp_str */
1552 PyObject_GenericGetAttr, /* tp_getattro */
1553 0, /* tp_setattro */
1554 0, /* tp_as_buffer */
1555 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1556 Py_TPFLAGS_BASETYPE, /* tp_flags */
1557 map_doc, /* tp_doc */
1558 (traverseproc)map_traverse, /* tp_traverse */
1559 0, /* tp_clear */
1560 0, /* tp_richcompare */
1561 0, /* tp_weaklistoffset */
1562 PyObject_SelfIter, /* tp_iter */
1563 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001564 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 0, /* tp_members */
1566 0, /* tp_getset */
1567 0, /* tp_base */
1568 0, /* tp_dict */
1569 0, /* tp_descr_get */
1570 0, /* tp_descr_set */
1571 0, /* tp_dictoffset */
1572 0, /* tp_init */
1573 PyType_GenericAlloc, /* tp_alloc */
1574 map_new, /* tp_new */
1575 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001576};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001577
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001578
1579/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001580static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001581builtin_next(PyObject *self, PyObject *args)
1582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 PyObject *it, *res;
1584 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1587 return NULL;
1588 if (!PyIter_Check(it)) {
1589 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001590 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 it->ob_type->tp_name);
1592 return NULL;
1593 }
1594
1595 res = (*it->ob_type->tp_iternext)(it);
1596 if (res != NULL) {
1597 return res;
1598 } else if (def != NULL) {
1599 if (PyErr_Occurred()) {
1600 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1601 return NULL;
1602 PyErr_Clear();
1603 }
1604 Py_INCREF(def);
1605 return def;
1606 } else if (PyErr_Occurred()) {
1607 return NULL;
1608 } else {
1609 PyErr_SetNone(PyExc_StopIteration);
1610 return NULL;
1611 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001612}
1613
1614PyDoc_STRVAR(next_doc,
1615"next(iterator[, default])\n\
1616\n\
1617Return the next item from the iterator. If default is given and the iterator\n\
1618is exhausted, it is returned instead of raising StopIteration.");
1619
1620
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001621/*[clinic input]
1622setattr as builtin_setattr
1623
1624 obj: 'O'
1625 name: 'O'
1626 value: 'O'
1627 /
1628
1629Sets the named attribute on the given object to the specified value.
1630
1631setattr(x, 'y', v) is equivalent to ``x.y = v''
1632[clinic start generated code]*/
1633
1634PyDoc_STRVAR(builtin_setattr__doc__,
1635"setattr($module, obj, name, value, /)\n"
1636"--\n"
1637"\n"
1638"Sets the named attribute on the given object to the specified value.\n"
1639"\n"
1640"setattr(x, \'y\', v) is equivalent to ``x.y = v\'\'");
1641
1642#define BUILTIN_SETATTR_METHODDEF \
1643 {"setattr", (PyCFunction)builtin_setattr, METH_VARARGS, builtin_setattr__doc__},
1644
Georg Brandla18af4e2007-04-21 15:47:16 +00001645static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001646builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name, PyObject *value);
1647
1648static PyObject *
1649builtin_setattr(PyModuleDef *module, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001650{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001651 PyObject *return_value = NULL;
1652 PyObject *obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 PyObject *name;
1654 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001655
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001656 if (!PyArg_UnpackTuple(args, "setattr",
1657 3, 3,
1658 &obj, &name, &value))
1659 goto exit;
1660 return_value = builtin_setattr_impl(module, obj, name, value);
1661
1662exit:
1663 return return_value;
1664}
1665
1666static PyObject *
1667builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name, PyObject *value)
1668/*[clinic end generated code: output=4336dcbbf7691d2d input=fbe7e53403116b93]*/
1669{
1670 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 return NULL;
1672 Py_INCREF(Py_None);
1673 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001674}
1675
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001676
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001677/*[clinic input]
1678delattr as builtin_delattr
1679
1680 obj: 'O'
1681 name: 'O'
1682 /
1683
1684Deletes the named attribute from the given object.
1685
1686delattr(x, 'y') is equivalent to ``del x.y''
1687[clinic start generated code]*/
1688
1689PyDoc_STRVAR(builtin_delattr__doc__,
1690"delattr($module, obj, name, /)\n"
1691"--\n"
1692"\n"
1693"Deletes the named attribute from the given object.\n"
1694"\n"
1695"delattr(x, \'y\') is equivalent to ``del x.y\'\'");
1696
1697#define BUILTIN_DELATTR_METHODDEF \
1698 {"delattr", (PyCFunction)builtin_delattr, METH_VARARGS, builtin_delattr__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001699
Guido van Rossum79f25d91997-04-29 20:08:16 +00001700static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001701builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name);
1702
1703static PyObject *
1704builtin_delattr(PyModuleDef *module, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001705{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001706 PyObject *return_value = NULL;
1707 PyObject *obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001709
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001710 if (!PyArg_UnpackTuple(args, "delattr",
1711 2, 2,
1712 &obj, &name))
1713 goto exit;
1714 return_value = builtin_delattr_impl(module, obj, name);
1715
1716exit:
1717 return return_value;
1718}
1719
1720static PyObject *
1721builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
1722/*[clinic end generated code: output=319c2d884aa769cf input=647af2ce9183a823]*/
1723{
1724 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 return NULL;
1726 Py_INCREF(Py_None);
1727 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001728}
1729
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001730
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001731/*[clinic input]
1732hash as builtin_hash
1733
1734 obj: 'O'
1735 /
1736
1737Return the hash value for the given object.
1738
1739Two objects that compare equal must also have the same hash value, but the
1740reverse is not necessarily true.
1741[clinic start generated code]*/
1742
1743PyDoc_STRVAR(builtin_hash__doc__,
1744"hash($module, obj, /)\n"
1745"--\n"
1746"\n"
1747"Return the hash value for the given object.\n"
1748"\n"
1749"Two objects that compare equal must also have the same hash value, but the\n"
1750"reverse is not necessarily true.");
1751
1752#define BUILTIN_HASH_METHODDEF \
1753 {"hash", (PyCFunction)builtin_hash, METH_O, builtin_hash__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001754
Guido van Rossum79f25d91997-04-29 20:08:16 +00001755static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001756builtin_hash(PyModuleDef *module, PyObject *obj)
1757/*[clinic end generated code: output=1ec467611c13468b input=ccc4d2b9a351df4e]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001758{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001759 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001760
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001761 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (x == -1)
1763 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001764 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001765}
1766
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001767
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001768/*[clinic input]
1769hex as builtin_hex
1770
1771 number: 'O'
1772 /
1773
1774Return the hexadecimal representation of an integer.
1775
1776 >>> hex(12648430)
1777 '0xc0ffee'
1778[clinic start generated code]*/
1779
1780PyDoc_STRVAR(builtin_hex__doc__,
1781"hex($module, number, /)\n"
1782"--\n"
1783"\n"
1784"Return the hexadecimal representation of an integer.\n"
1785"\n"
1786" >>> hex(12648430)\n"
1787" \'0xc0ffee\'");
1788
1789#define BUILTIN_HEX_METHODDEF \
1790 {"hex", (PyCFunction)builtin_hex, METH_O, builtin_hex__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001791
Guido van Rossum79f25d91997-04-29 20:08:16 +00001792static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001793builtin_hex(PyModuleDef *module, PyObject *number)
1794/*[clinic end generated code: output=f18e9439aeaa2c6c input=e816200b0a728ebe]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001795{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001796 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001797}
1798
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001799
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001800/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001801static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001802builtin_iter(PyObject *self, PyObject *args)
1803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1807 return NULL;
1808 if (w == NULL)
1809 return PyObject_GetIter(v);
1810 if (!PyCallable_Check(v)) {
1811 PyErr_SetString(PyExc_TypeError,
1812 "iter(v, w): v must be callable");
1813 return NULL;
1814 }
1815 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001816}
1817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001818PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001819"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001820iter(callable, sentinel) -> iterator\n\
1821\n\
1822Get an iterator from an object. In the first form, the argument must\n\
1823supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001824In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001825
1826
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001827/*[clinic input]
1828len as builtin_len
1829
1830 obj: 'O'
1831 /
1832
1833Return the number of items in a container.
1834[clinic start generated code]*/
1835
1836PyDoc_STRVAR(builtin_len__doc__,
1837"len($module, obj, /)\n"
1838"--\n"
1839"\n"
1840"Return the number of items in a container.");
1841
1842#define BUILTIN_LEN_METHODDEF \
1843 {"len", (PyCFunction)builtin_len, METH_O, builtin_len__doc__},
1844
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001845static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001846builtin_len(PyModuleDef *module, PyObject *obj)
1847/*[clinic end generated code: output=5a38b0db40761705 input=2e5ff15db9a2de22]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001850
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001851 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (res < 0 && PyErr_Occurred())
1853 return NULL;
1854 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001855}
1856
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001857
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001858/*[clinic input]
1859locals as builtin_locals
1860
1861Return a dictionary containing the current scope's local variables.
1862
1863NOTE: Whether or not updates to this dictionary will affect name lookups in
1864the local scope and vice-versa is *implementation dependent* and not
1865covered by any backwards compatibility guarantees.
1866[clinic start generated code]*/
1867
1868PyDoc_STRVAR(builtin_locals__doc__,
1869"locals($module, /)\n"
1870"--\n"
1871"\n"
1872"Return a dictionary containing the current scope\'s local variables.\n"
1873"\n"
1874"NOTE: Whether or not updates to this dictionary will affect name lookups in\n"
1875"the local scope and vice-versa is *implementation dependent* and not\n"
1876"covered by any backwards compatibility guarantees.");
1877
1878#define BUILTIN_LOCALS_METHODDEF \
1879 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, builtin_locals__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001880
Guido van Rossum79f25d91997-04-29 20:08:16 +00001881static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001882builtin_locals_impl(PyModuleDef *module);
1883
1884static PyObject *
1885builtin_locals(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1886{
1887 return builtin_locals_impl(module);
1888}
1889
1890static PyObject *
1891builtin_locals_impl(PyModuleDef *module)
1892/*[clinic end generated code: output=8ac52522924346e2 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 d = PyEval_GetLocals();
1897 Py_XINCREF(d);
1898 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001899}
1900
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001901
Guido van Rossum79f25d91997-04-29 20:08:16 +00001902static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001903min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001906 PyObject *emptytuple, *defaultval = NULL;
1907 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001909 const int positional = PyTuple_Size(args) > 1;
1910 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001911
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001912 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001914 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001916
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001917 emptytuple = PyTuple_New(0);
1918 if (emptytuple == NULL)
1919 return NULL;
1920 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1921 &keyfunc, &defaultval);
1922 Py_DECREF(emptytuple);
1923 if (!ret)
1924 return NULL;
1925
1926 if (positional && defaultval != NULL) {
1927 PyErr_Format(PyExc_TypeError,
1928 "Cannot specify a default for %s() with multiple "
1929 "positional arguments", name);
1930 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 it = PyObject_GetIter(v);
1934 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 return NULL;
1936 }
Tim Petersc3074532001-05-03 07:00:32 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 maxitem = NULL; /* the result */
1939 maxval = NULL; /* the value associated with the result */
1940 while (( item = PyIter_Next(it) )) {
1941 /* get the value from the key function */
1942 if (keyfunc != NULL) {
1943 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1944 if (val == NULL)
1945 goto Fail_it_item;
1946 }
1947 /* no key function; the value is the item */
1948 else {
1949 val = item;
1950 Py_INCREF(val);
1951 }
Tim Petersc3074532001-05-03 07:00:32 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 /* maximum value and item are unset; set them */
1954 if (maxval == NULL) {
1955 maxitem = item;
1956 maxval = val;
1957 }
1958 /* maximum value and item are set; update them as necessary */
1959 else {
1960 int cmp = PyObject_RichCompareBool(val, maxval, op);
1961 if (cmp < 0)
1962 goto Fail_it_item_and_val;
1963 else if (cmp > 0) {
1964 Py_DECREF(maxval);
1965 Py_DECREF(maxitem);
1966 maxval = val;
1967 maxitem = item;
1968 }
1969 else {
1970 Py_DECREF(item);
1971 Py_DECREF(val);
1972 }
1973 }
1974 }
1975 if (PyErr_Occurred())
1976 goto Fail_it;
1977 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001979 if (defaultval != NULL) {
1980 Py_INCREF(defaultval);
1981 maxitem = defaultval;
1982 } else {
1983 PyErr_Format(PyExc_ValueError,
1984 "%s() arg is an empty sequence", name);
1985 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 }
1987 else
1988 Py_DECREF(maxval);
1989 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001991
1992Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001994Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001996Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 Py_XDECREF(maxval);
1998 Py_XDECREF(maxitem);
1999 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002001}
2002
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002003/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002004static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00002005builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002008}
2009
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002010PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01002011"min(iterable, *[, default=obj, key=func]) -> value\n\
2012min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002013\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01002014With a single iterable argument, return its smallest item. The\n\
2015default keyword-only argument specifies an object to return if\n\
2016the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002017With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002018
2019
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002020/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002021static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00002022builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002025}
2026
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002027PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01002028"max(iterable, *[, default=obj, key=func]) -> value\n\
2029max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002030\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01002031With a single iterable argument, return its biggest item. The\n\
2032default keyword-only argument specifies an object to return if\n\
2033the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002034With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002035
2036
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002037/*[clinic input]
2038oct as builtin_oct
2039
2040 number: 'O'
2041 /
2042
2043Return the octal representation of an integer.
2044
2045 >>> oct(342391)
2046 '0o1234567'
2047[clinic start generated code]*/
2048
2049PyDoc_STRVAR(builtin_oct__doc__,
2050"oct($module, number, /)\n"
2051"--\n"
2052"\n"
2053"Return the octal representation of an integer.\n"
2054"\n"
2055" >>> oct(342391)\n"
2056" \'0o1234567\'");
2057
2058#define BUILTIN_OCT_METHODDEF \
2059 {"oct", (PyCFunction)builtin_oct, METH_O, builtin_oct__doc__},
2060
Guido van Rossum79f25d91997-04-29 20:08:16 +00002061static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002062builtin_oct(PyModuleDef *module, PyObject *number)
2063/*[clinic end generated code: output=b99234d1d70a6673 input=a3a372b521b3dd13]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00002064{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002065 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00002066}
2067
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002068
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002069/*[clinic input]
2070ord as builtin_ord
2071
2072 c: 'O'
2073 /
2074
2075Return the Unicode code point for a one-character string.
2076[clinic start generated code]*/
2077
2078PyDoc_STRVAR(builtin_ord__doc__,
2079"ord($module, c, /)\n"
2080"--\n"
2081"\n"
2082"Return the Unicode code point for a one-character string.");
2083
2084#define BUILTIN_ORD_METHODDEF \
2085 {"ord", (PyCFunction)builtin_ord, METH_O, builtin_ord__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002086
Guido van Rossum79f25d91997-04-29 20:08:16 +00002087static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002088builtin_ord(PyModuleDef *module, PyObject *c)
2089/*[clinic end generated code: output=a8466d23bd76db3f input=762355f87451efa3]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00002090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 long ord;
2092 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002093
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002094 if (PyBytes_Check(c)) {
2095 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002097 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 return PyLong_FromLong(ord);
2099 }
2100 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002101 else if (PyUnicode_Check(c)) {
2102 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002103 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002104 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002106 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 return PyLong_FromLong(ord);
2108 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002110 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002112 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002114 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 return PyLong_FromLong(ord);
2116 }
2117 }
2118 else {
2119 PyErr_Format(PyExc_TypeError,
2120 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002121 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 return NULL;
2123 }
Guido van Rossum09095f32000-03-10 23:00:52 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 PyErr_Format(PyExc_TypeError,
2126 "ord() expected a character, "
2127 "but string of length %zd found",
2128 size);
2129 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002130}
2131
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002132
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002133/*[clinic input]
2134pow as builtin_pow
2135
2136 x: 'O'
2137 y: 'O'
2138 z: 'O' = None
2139 /
2140
2141Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
2142
2143Some types, such as ints, are able to use a more efficient algorithm when
2144invoked using the three argument form.
2145[clinic start generated code]*/
2146
2147PyDoc_STRVAR(builtin_pow__doc__,
2148"pow($module, x, y, z=None, /)\n"
2149"--\n"
2150"\n"
2151"Equivalent to x**y (with two arguments) or x**y % z (with three arguments)\n"
2152"\n"
2153"Some types, such as ints, are able to use a more efficient algorithm when\n"
2154"invoked using the three argument form.");
2155
2156#define BUILTIN_POW_METHODDEF \
2157 {"pow", (PyCFunction)builtin_pow, METH_VARARGS, builtin_pow__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002158
Guido van Rossum79f25d91997-04-29 20:08:16 +00002159static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002160builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z);
Guido van Rossum6a00cd81995-01-07 12:39:01 +00002161
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002162static PyObject *
2163builtin_pow(PyModuleDef *module, PyObject *args)
2164{
2165 PyObject *return_value = NULL;
2166 PyObject *x;
2167 PyObject *y;
2168 PyObject *z = Py_None;
2169
2170 if (!PyArg_UnpackTuple(args, "pow",
2171 2, 3,
2172 &x, &y, &z))
2173 goto exit;
2174 return_value = builtin_pow_impl(module, x, y, z);
2175
2176exit:
2177 return return_value;
Guido van Rossumd4905451991-05-05 20:00:36 +00002178}
2179
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002180static PyObject *
2181builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z)
2182/*[clinic end generated code: output=d0cdf314311dedba input=561a942d5f5c1899]*/
2183{
2184 return PyNumber_Power(x, y, z);
2185}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002186
2187
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002188/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00002189static PyObject *
2190builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
2191{
Georg Brandlbc3b6822012-01-13 19:41:25 +01002192 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01002194 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00002196
Benjamin Peterson00102562012-01-11 21:00:16 -05002197 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01002198 return NULL;
2199 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
2200 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 return NULL;
2202 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01002203 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02002204 if (file == NULL) {
2205 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
2206 return NULL;
2207 }
2208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 /* sys.stdout may be None when FILE* stdout isn't connected */
2210 if (file == Py_None)
2211 Py_RETURN_NONE;
2212 }
Guido van Rossum34343512006-11-30 22:13:52 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (sep == Py_None) {
2215 sep = NULL;
2216 }
2217 else if (sep && !PyUnicode_Check(sep)) {
2218 PyErr_Format(PyExc_TypeError,
2219 "sep must be None or a string, not %.200s",
2220 sep->ob_type->tp_name);
2221 return NULL;
2222 }
2223 if (end == Py_None) {
2224 end = NULL;
2225 }
2226 else if (end && !PyUnicode_Check(end)) {
2227 PyErr_Format(PyExc_TypeError,
2228 "end must be None or a string, not %.200s",
2229 end->ob_type->tp_name);
2230 return NULL;
2231 }
Guido van Rossum34343512006-11-30 22:13:52 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 for (i = 0; i < PyTuple_Size(args); i++) {
2234 if (i > 0) {
2235 if (sep == NULL)
2236 err = PyFile_WriteString(" ", file);
2237 else
2238 err = PyFile_WriteObject(sep, file,
2239 Py_PRINT_RAW);
2240 if (err)
2241 return NULL;
2242 }
2243 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
2244 Py_PRINT_RAW);
2245 if (err)
2246 return NULL;
2247 }
Guido van Rossum34343512006-11-30 22:13:52 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 if (end == NULL)
2250 err = PyFile_WriteString("\n", file);
2251 else
2252 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
2253 if (err)
2254 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00002255
Georg Brandlbc3b6822012-01-13 19:41:25 +01002256 if (flush != NULL) {
2257 PyObject *tmp;
2258 int do_flush = PyObject_IsTrue(flush);
2259 if (do_flush == -1)
2260 return NULL;
2261 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01002262 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01002263 if (tmp == NULL)
2264 return NULL;
2265 else
2266 Py_DECREF(tmp);
2267 }
2268 }
2269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00002271}
2272
2273PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002274"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00002275\n\
2276Prints the values to a stream, or to sys.stdout by default.\n\
2277Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002278file: a file-like object (stream); defaults to the current sys.stdout.\n\
2279sep: string inserted between values, default a space.\n\
2280end: string appended after the last value, default a newline.\n\
2281flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00002282
2283
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002284/*[clinic input]
2285input as builtin_input
2286
2287 prompt: object(c_default="NULL") = None
2288 /
2289
2290Read a string from standard input. The trailing newline is stripped.
2291
2292The prompt string, if given, is printed to standard output without a
2293trailing newline before reading input.
2294
2295If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
2296On *nix systems, readline is used if available.
2297[clinic start generated code]*/
2298
2299PyDoc_STRVAR(builtin_input__doc__,
2300"input($module, prompt=None, /)\n"
2301"--\n"
2302"\n"
2303"Read a string from standard input. The trailing newline is stripped.\n"
2304"\n"
2305"The prompt string, if given, is printed to standard output without a\n"
2306"trailing newline before reading input.\n"
2307"\n"
2308"If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.\n"
2309"On *nix systems, readline is used if available.");
2310
2311#define BUILTIN_INPUT_METHODDEF \
2312 {"input", (PyCFunction)builtin_input, METH_VARARGS, builtin_input__doc__},
2313
Guido van Rossuma88a0332007-02-26 16:59:55 +00002314static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002315builtin_input_impl(PyModuleDef *module, PyObject *prompt);
2316
2317static PyObject *
2318builtin_input(PyModuleDef *module, PyObject *args)
Guido van Rossuma88a0332007-02-26 16:59:55 +00002319{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002320 PyObject *return_value = NULL;
2321 PyObject *prompt = NULL;
2322
2323 if (!PyArg_UnpackTuple(args, "input",
2324 0, 1,
2325 &prompt))
2326 goto exit;
2327 return_value = builtin_input_impl(module, prompt);
2328
2329exit:
2330 return return_value;
2331}
2332
2333static PyObject *
2334builtin_input_impl(PyModuleDef *module, PyObject *prompt)
2335/*[clinic end generated code: output=69323bf5695f7c9c input=5e8bb70c2908fe3c]*/
2336{
Victor Stinnerbd303c12013-11-07 23:07:29 +01002337 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
2338 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
2339 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 PyObject *tmp;
2341 long fd;
2342 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 /* Check that stdin/out/err are intact */
2345 if (fin == NULL || fin == Py_None) {
2346 PyErr_SetString(PyExc_RuntimeError,
2347 "input(): lost sys.stdin");
2348 return NULL;
2349 }
2350 if (fout == NULL || fout == Py_None) {
2351 PyErr_SetString(PyExc_RuntimeError,
2352 "input(): lost sys.stdout");
2353 return NULL;
2354 }
2355 if (ferr == NULL || ferr == Py_None) {
2356 PyErr_SetString(PyExc_RuntimeError,
2357 "input(): lost sys.stderr");
2358 return NULL;
2359 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002362 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (tmp == NULL)
2364 PyErr_Clear();
2365 else
2366 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 /* We should only use (GNU) readline if Python's sys.stdin and
2369 sys.stdout are the same as C's stdin and stdout, because we
2370 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002371 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 if (tmp == NULL) {
2373 PyErr_Clear();
2374 tty = 0;
2375 }
2376 else {
2377 fd = PyLong_AsLong(tmp);
2378 Py_DECREF(tmp);
2379 if (fd < 0 && PyErr_Occurred())
2380 return NULL;
2381 tty = fd == fileno(stdin) && isatty(fd);
2382 }
2383 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002384 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 if (tmp == NULL)
2386 PyErr_Clear();
2387 else {
2388 fd = PyLong_AsLong(tmp);
2389 Py_DECREF(tmp);
2390 if (fd < 0 && PyErr_Occurred())
2391 return NULL;
2392 tty = fd == fileno(stdout) && isatty(fd);
2393 }
2394 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* If we're interactive, use (GNU) readline */
2397 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002398 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002399 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002400 char *s = NULL;
2401 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2402 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
2403 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002405 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002406
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002407 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002408 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002409 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* stdin is a text stream, so it must have an
2411 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002412 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00002413 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002414 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
2415 if (!stdin_encoding_str || !stdin_errors_str)
2416 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002417 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (tmp == NULL)
2419 PyErr_Clear();
2420 else
2421 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002422 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002423 /* We have a prompt, encode it as stdout would */
2424 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002426 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002427 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002428 if (!stdout_encoding || !stdout_errors)
2429 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00002430 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002431 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
2432 if (!stdout_encoding_str || !stdout_errors_str)
2433 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002434 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002435 if (stringpo == NULL)
2436 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002438 stdout_encoding_str, stdout_errors_str);
2439 Py_CLEAR(stdout_encoding);
2440 Py_CLEAR(stdout_errors);
2441 Py_CLEAR(stringpo);
2442 if (po == NULL)
2443 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002444 promptstr = PyBytes_AsString(po);
2445 if (promptstr == NULL)
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002446 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 }
2448 else {
2449 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002450 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002452 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002454 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 if (!PyErr_Occurred())
2456 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002457 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002459
2460 len = strlen(s);
2461 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 PyErr_SetNone(PyExc_EOFError);
2463 result = NULL;
2464 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002465 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 if (len > PY_SSIZE_T_MAX) {
2467 PyErr_SetString(PyExc_OverflowError,
2468 "input: input too long");
2469 result = NULL;
2470 }
2471 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002472 len--; /* strip trailing '\n' */
2473 if (len != 0 && s[len-1] == '\r')
2474 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002475 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2476 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 }
2478 }
2479 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002480 Py_DECREF(stdin_errors);
2481 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 PyMem_FREE(s);
2483 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002484 _readline_errors:
2485 Py_XDECREF(stdin_encoding);
2486 Py_XDECREF(stdout_encoding);
2487 Py_XDECREF(stdin_errors);
2488 Py_XDECREF(stdout_errors);
2489 Py_XDECREF(po);
2490 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002494 if (prompt != NULL) {
2495 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 return NULL;
2497 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002498 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 if (tmp == NULL)
2500 PyErr_Clear();
2501 else
2502 Py_DECREF(tmp);
2503 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002504}
2505
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002506
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002507/*[clinic input]
2508repr as builtin_repr
2509
2510 obj: 'O'
2511 /
2512
2513Return the canonical string representation of the object.
2514
2515For many object types, including most builtins, eval(repr(obj)) == obj.
2516[clinic start generated code]*/
2517
2518PyDoc_STRVAR(builtin_repr__doc__,
2519"repr($module, obj, /)\n"
2520"--\n"
2521"\n"
2522"Return the canonical string representation of the object.\n"
2523"\n"
2524"For many object types, including most builtins, eval(repr(obj)) == obj.");
2525
2526#define BUILTIN_REPR_METHODDEF \
2527 {"repr", (PyCFunction)builtin_repr, METH_O, builtin_repr__doc__},
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002528
Guido van Rossum79f25d91997-04-29 20:08:16 +00002529static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002530builtin_repr(PyModuleDef *module, PyObject *obj)
2531/*[clinic end generated code: output=988980120f39e2fa input=a2bca0f38a5a924d]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002532{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002533 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002534}
2535
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002536
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002537/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2538 * or a semantic change to accept None for "ndigits"
2539 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002540static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002541builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 PyObject *ndigits = NULL;
2544 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002545 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2548 kwlist, &number, &ndigits))
2549 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 if (Py_TYPE(number)->tp_dict == NULL) {
2552 if (PyType_Ready(Py_TYPE(number)) < 0)
2553 return NULL;
2554 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002555
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002556 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002558 if (!PyErr_Occurred())
2559 PyErr_Format(PyExc_TypeError,
2560 "type %.100s doesn't define __round__ method",
2561 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 return NULL;
2563 }
Alex Martelliae211f92007-08-22 23:21:33 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002566 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002568 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2569 Py_DECREF(round);
2570 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002571}
2572
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002573PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002574"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002575\n\
2576Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002577This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002578same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002579
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002580
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002581/*AC: we need to keep the kwds dict intact to easily call into the
2582 * list.sort method, which isn't currently supported in AC. So we just use
2583 * the initially generated signature with a custom implementation.
2584 */
2585/* [disabled clinic input]
2586sorted as builtin_sorted
2587
2588 iterable as seq: 'O'
2589 key as keyfunc: 'O' = None
2590 reverse: 'O' = False
2591
2592Return a new list containing all items from the iterable in ascending order.
2593
2594A custom key function can be supplied to customise the sort order, and the
2595reverse flag can be set to request the result in descending order.
2596[end disabled clinic input]*/
2597
2598PyDoc_STRVAR(builtin_sorted__doc__,
2599"sorted($module, iterable, key=None, reverse=False)\n"
2600"--\n"
2601"\n"
2602"Return a new list containing all items from the iterable in ascending order.\n"
2603"\n"
2604"A custom key function can be supplied to customise the sort order, and the\n"
2605"reverse flag can be set to request the result in descending order.");
2606
2607#define BUILTIN_SORTED_METHODDEF \
2608 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
2609
Raymond Hettinger64958a12003-12-17 20:43:33 +00002610static PyObject *
2611builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
2614 PyObject *callable;
2615 static char *kwlist[] = {"iterable", "key", "reverse", 0};
2616 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 /* args 1-3 should match listsort in Objects/listobject.c */
2619 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
2620 kwlist, &seq, &keyfunc, &reverse))
2621 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 newlist = PySequence_List(seq);
2624 if (newlist == NULL)
2625 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002626
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002627 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 if (callable == NULL) {
2629 Py_DECREF(newlist);
2630 return NULL;
2631 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 newargs = PyTuple_GetSlice(args, 1, 4);
2634 if (newargs == NULL) {
2635 Py_DECREF(newlist);
2636 Py_DECREF(callable);
2637 return NULL;
2638 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 v = PyObject_Call(callable, newargs, kwds);
2641 Py_DECREF(newargs);
2642 Py_DECREF(callable);
2643 if (v == NULL) {
2644 Py_DECREF(newlist);
2645 return NULL;
2646 }
2647 Py_DECREF(v);
2648 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002649}
2650
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002651
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002652/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002653static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002654builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 PyObject *v = NULL;
2657 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2660 return NULL;
2661 if (v == NULL) {
2662 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002663 if (d == NULL)
2664 return NULL;
2665 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 }
2667 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002668 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 if (d == NULL) {
2670 PyErr_SetString(PyExc_TypeError,
2671 "vars() argument must have __dict__ attribute");
2672 return NULL;
2673 }
2674 }
2675 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002676}
2677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002678PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002679"vars([object]) -> dictionary\n\
2680\n\
2681Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002682With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002683
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002684
2685/*[clinic input]
2686sum as builtin_sum
2687
2688 iterable: 'O'
2689 start: object(c_default="NULL") = 0
2690 /
2691
2692Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2693
2694When the iterable is empty, return the start value.
2695This function is intended specifically for use with numeric values and may
2696reject non-numeric types.
2697[clinic start generated code]*/
2698
2699PyDoc_STRVAR(builtin_sum__doc__,
2700"sum($module, iterable, start=0, /)\n"
2701"--\n"
2702"\n"
2703"Return the sum of a \'start\' value (default: 0) plus an iterable of numbers\n"
2704"\n"
2705"When the iterable is empty, return the start value.\n"
2706"This function is intended specifically for use with numeric values and may\n"
2707"reject non-numeric types.");
2708
2709#define BUILTIN_SUM_METHODDEF \
2710 {"sum", (PyCFunction)builtin_sum, METH_VARARGS, builtin_sum__doc__},
2711
2712static PyObject *
2713builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start);
2714
2715static PyObject *
2716builtin_sum(PyModuleDef *module, PyObject *args)
Alex Martellia70b1912003-04-22 08:12:33 +00002717{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002718 PyObject *return_value = NULL;
2719 PyObject *iterable;
2720 PyObject *start = NULL;
2721
2722 if (!PyArg_UnpackTuple(args, "sum",
2723 1, 2,
2724 &iterable, &start))
2725 goto exit;
2726 return_value = builtin_sum_impl(module, iterable, start);
2727
2728exit:
2729 return return_value;
2730}
2731
2732static PyObject *
2733builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start)
2734/*[clinic end generated code: output=b42652a0d5f64f6b input=90ae7a242cfcf025]*/
2735{
2736 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002738
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002739 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 if (iter == NULL)
2741 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 if (result == NULL) {
2744 result = PyLong_FromLong(0);
2745 if (result == NULL) {
2746 Py_DECREF(iter);
2747 return NULL;
2748 }
2749 } else {
2750 /* reject string values for 'start' parameter */
2751 if (PyUnicode_Check(result)) {
2752 PyErr_SetString(PyExc_TypeError,
2753 "sum() can't sum strings [use ''.join(seq) instead]");
2754 Py_DECREF(iter);
2755 return NULL;
2756 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002757 if (PyBytes_Check(result)) {
2758 PyErr_SetString(PyExc_TypeError,
2759 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002760 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002761 return NULL;
2762 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 if (PyByteArray_Check(result)) {
2764 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002765 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 Py_DECREF(iter);
2767 return NULL;
2768 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 Py_INCREF(result);
2770 }
Alex Martellia70b1912003-04-22 08:12:33 +00002771
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002772#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2774 Assumes all inputs are the same type. If the assumption fails, default
2775 to the more general routine.
2776 */
2777 if (PyLong_CheckExact(result)) {
2778 int overflow;
2779 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2780 /* If this already overflowed, don't even enter the loop. */
2781 if (overflow == 0) {
2782 Py_DECREF(result);
2783 result = NULL;
2784 }
2785 while(result == NULL) {
2786 item = PyIter_Next(iter);
2787 if (item == NULL) {
2788 Py_DECREF(iter);
2789 if (PyErr_Occurred())
2790 return NULL;
2791 return PyLong_FromLong(i_result);
2792 }
2793 if (PyLong_CheckExact(item)) {
2794 long b = PyLong_AsLongAndOverflow(item, &overflow);
2795 long x = i_result + b;
2796 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2797 i_result = x;
2798 Py_DECREF(item);
2799 continue;
2800 }
2801 }
2802 /* Either overflowed or is not an int. Restore real objects and process normally */
2803 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002804 if (result == NULL) {
2805 Py_DECREF(item);
2806 Py_DECREF(iter);
2807 return NULL;
2808 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 temp = PyNumber_Add(result, item);
2810 Py_DECREF(result);
2811 Py_DECREF(item);
2812 result = temp;
2813 if (result == NULL) {
2814 Py_DECREF(iter);
2815 return NULL;
2816 }
2817 }
2818 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 if (PyFloat_CheckExact(result)) {
2821 double f_result = PyFloat_AS_DOUBLE(result);
2822 Py_DECREF(result);
2823 result = NULL;
2824 while(result == NULL) {
2825 item = PyIter_Next(iter);
2826 if (item == NULL) {
2827 Py_DECREF(iter);
2828 if (PyErr_Occurred())
2829 return NULL;
2830 return PyFloat_FromDouble(f_result);
2831 }
2832 if (PyFloat_CheckExact(item)) {
2833 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2834 f_result += PyFloat_AS_DOUBLE(item);
2835 PyFPE_END_PROTECT(f_result)
2836 Py_DECREF(item);
2837 continue;
2838 }
2839 if (PyLong_CheckExact(item)) {
2840 long value;
2841 int overflow;
2842 value = PyLong_AsLongAndOverflow(item, &overflow);
2843 if (!overflow) {
2844 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2845 f_result += (double)value;
2846 PyFPE_END_PROTECT(f_result)
2847 Py_DECREF(item);
2848 continue;
2849 }
2850 }
2851 result = PyFloat_FromDouble(f_result);
2852 temp = PyNumber_Add(result, item);
2853 Py_DECREF(result);
2854 Py_DECREF(item);
2855 result = temp;
2856 if (result == NULL) {
2857 Py_DECREF(iter);
2858 return NULL;
2859 }
2860 }
2861 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002862#endif
2863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 for(;;) {
2865 item = PyIter_Next(iter);
2866 if (item == NULL) {
2867 /* error, or end-of-sequence */
2868 if (PyErr_Occurred()) {
2869 Py_DECREF(result);
2870 result = NULL;
2871 }
2872 break;
2873 }
2874 /* It's tempting to use PyNumber_InPlaceAdd instead of
2875 PyNumber_Add here, to avoid quadratic running time
2876 when doing 'sum(list_of_lists, [])'. However, this
2877 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 empty = []
2880 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 would change the value of empty. */
2883 temp = PyNumber_Add(result, item);
2884 Py_DECREF(result);
2885 Py_DECREF(item);
2886 result = temp;
2887 if (result == NULL)
2888 break;
2889 }
2890 Py_DECREF(iter);
2891 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002892}
2893
Alex Martellia70b1912003-04-22 08:12:33 +00002894
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002895/*[clinic input]
2896isinstance as builtin_isinstance
2897
2898 obj: 'O'
2899 class_or_tuple: 'O'
2900 /
2901
2902Return whether an object is an instance of a class or of a subclass thereof.
2903
2904A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2905check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2906or ...`` etc.
2907[clinic start generated code]*/
2908
2909PyDoc_STRVAR(builtin_isinstance__doc__,
2910"isinstance($module, obj, class_or_tuple, /)\n"
2911"--\n"
2912"\n"
2913"Return whether an object is an instance of a class or of a subclass thereof.\n"
2914"\n"
2915"A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to\n"
2916"check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)\n"
2917"or ...`` etc.");
2918
2919#define BUILTIN_ISINSTANCE_METHODDEF \
2920 {"isinstance", (PyCFunction)builtin_isinstance, METH_VARARGS, builtin_isinstance__doc__},
Alex Martellia70b1912003-04-22 08:12:33 +00002921
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002922static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002923builtin_isinstance_impl(PyModuleDef *module, PyObject *obj, PyObject *class_or_tuple);
2924
2925static PyObject *
2926builtin_isinstance(PyModuleDef *module, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002927{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002928 PyObject *return_value = NULL;
2929 PyObject *obj;
2930 PyObject *class_or_tuple;
2931
2932 if (!PyArg_UnpackTuple(args, "isinstance",
2933 2, 2,
2934 &obj, &class_or_tuple))
2935 goto exit;
2936 return_value = builtin_isinstance_impl(module, obj, class_or_tuple);
2937
2938exit:
2939 return return_value;
2940}
2941
2942static PyObject *
2943builtin_isinstance_impl(PyModuleDef *module, PyObject *obj, PyObject *class_or_tuple)
2944/*[clinic end generated code: output=847df57fef8ddea7 input=cf9eb0ad6bb9bad6]*/
2945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002947
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002948 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 if (retval < 0)
2950 return NULL;
2951 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002952}
2953
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002954
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002955/*[clinic input]
2956issubclass as builtin_issubclass
2957
2958 cls: 'O'
2959 class_or_tuple: 'O'
2960 /
2961
2962Return whether 'cls' is a derived from another class or is the same class.
2963
2964A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2965check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2966or ...`` etc.
2967[clinic start generated code]*/
2968
2969PyDoc_STRVAR(builtin_issubclass__doc__,
2970"issubclass($module, cls, class_or_tuple, /)\n"
2971"--\n"
2972"\n"
2973"Return whether \'cls\' is a derived from another class or is the same class.\n"
2974"\n"
2975"A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to\n"
2976"check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)\n"
2977"or ...`` etc.");
2978
2979#define BUILTIN_ISSUBCLASS_METHODDEF \
2980 {"issubclass", (PyCFunction)builtin_issubclass, METH_VARARGS, builtin_issubclass__doc__},
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002981
2982static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002983builtin_issubclass_impl(PyModuleDef *module, PyObject *cls, PyObject *class_or_tuple);
2984
2985static PyObject *
2986builtin_issubclass(PyModuleDef *module, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002987{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002988 PyObject *return_value = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 PyObject *cls;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002990 PyObject *class_or_tuple;
2991
2992 if (!PyArg_UnpackTuple(args, "issubclass",
2993 2, 2,
2994 &cls, &class_or_tuple))
2995 goto exit;
2996 return_value = builtin_issubclass_impl(module, cls, class_or_tuple);
2997
2998exit:
2999 return return_value;
3000}
3001
3002static PyObject *
3003builtin_issubclass_impl(PyModuleDef *module, PyObject *cls, PyObject *class_or_tuple)
3004/*[clinic end generated code: output=a0f8c03692e35474 input=923d03fa41fc352a]*/
3005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00003007
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003008 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 if (retval < 0)
3010 return NULL;
3011 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00003012}
3013
3014
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003015typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 PyObject_HEAD
3017 Py_ssize_t tuplesize;
3018 PyObject *ittuple; /* tuple of iterators */
3019 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003020} zipobject;
3021
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003022static PyObject *
3023zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00003024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 zipobject *lz;
3026 Py_ssize_t i;
3027 PyObject *ittuple; /* tuple of iterators */
3028 PyObject *result;
3029 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
3032 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 /* args must be a tuple */
3035 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 /* obtain iterators */
3038 ittuple = PyTuple_New(tuplesize);
3039 if (ittuple == NULL)
3040 return NULL;
3041 for (i=0; i < tuplesize; ++i) {
3042 PyObject *item = PyTuple_GET_ITEM(args, i);
3043 PyObject *it = PyObject_GetIter(item);
3044 if (it == NULL) {
3045 if (PyErr_ExceptionMatches(PyExc_TypeError))
3046 PyErr_Format(PyExc_TypeError,
3047 "zip argument #%zd must support iteration",
3048 i+1);
3049 Py_DECREF(ittuple);
3050 return NULL;
3051 }
3052 PyTuple_SET_ITEM(ittuple, i, it);
3053 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 /* create a result holder */
3056 result = PyTuple_New(tuplesize);
3057 if (result == NULL) {
3058 Py_DECREF(ittuple);
3059 return NULL;
3060 }
3061 for (i=0 ; i < tuplesize ; i++) {
3062 Py_INCREF(Py_None);
3063 PyTuple_SET_ITEM(result, i, Py_None);
3064 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 /* create zipobject structure */
3067 lz = (zipobject *)type->tp_alloc(type, 0);
3068 if (lz == NULL) {
3069 Py_DECREF(ittuple);
3070 Py_DECREF(result);
3071 return NULL;
3072 }
3073 lz->ittuple = ittuple;
3074 lz->tuplesize = tuplesize;
3075 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00003078}
3079
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003080static void
3081zip_dealloc(zipobject *lz)
3082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 PyObject_GC_UnTrack(lz);
3084 Py_XDECREF(lz->ittuple);
3085 Py_XDECREF(lz->result);
3086 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003087}
3088
3089static int
3090zip_traverse(zipobject *lz, visitproc visit, void *arg)
3091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 Py_VISIT(lz->ittuple);
3093 Py_VISIT(lz->result);
3094 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003095}
3096
3097static PyObject *
3098zip_next(zipobject *lz)
3099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 Py_ssize_t i;
3101 Py_ssize_t tuplesize = lz->tuplesize;
3102 PyObject *result = lz->result;
3103 PyObject *it;
3104 PyObject *item;
3105 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 if (tuplesize == 0)
3108 return NULL;
3109 if (Py_REFCNT(result) == 1) {
3110 Py_INCREF(result);
3111 for (i=0 ; i < tuplesize ; i++) {
3112 it = PyTuple_GET_ITEM(lz->ittuple, i);
3113 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03003114 if (item == NULL) {
3115 Py_DECREF(result);
3116 return NULL;
3117 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 olditem = PyTuple_GET_ITEM(result, i);
3119 PyTuple_SET_ITEM(result, i, item);
3120 Py_DECREF(olditem);
3121 }
3122 } else {
3123 result = PyTuple_New(tuplesize);
3124 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03003125 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 for (i=0 ; i < tuplesize ; i++) {
3127 it = PyTuple_GET_ITEM(lz->ittuple, i);
3128 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03003129 if (item == NULL) {
3130 Py_DECREF(result);
3131 return NULL;
3132 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 PyTuple_SET_ITEM(result, i, item);
3134 }
3135 }
3136 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003137}
Barry Warsawbd599b52000-08-03 15:45:29 +00003138
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003139static PyObject *
3140zip_reduce(zipobject *lz)
3141{
3142 /* Just recreate the zip with the internal iterator tuple */
3143 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
3144}
3145
3146static PyMethodDef zip_methods[] = {
3147 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
3148 {NULL, NULL} /* sentinel */
3149};
3150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003151PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003152"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00003153\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003154Return a zip object whose .__next__() method returns a tuple where\n\
3155the i-th element comes from the i-th iterable argument. The .__next__()\n\
3156method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00003157is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003158
3159PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3161 "zip", /* tp_name */
3162 sizeof(zipobject), /* tp_basicsize */
3163 0, /* tp_itemsize */
3164 /* methods */
3165 (destructor)zip_dealloc, /* tp_dealloc */
3166 0, /* tp_print */
3167 0, /* tp_getattr */
3168 0, /* tp_setattr */
3169 0, /* tp_reserved */
3170 0, /* tp_repr */
3171 0, /* tp_as_number */
3172 0, /* tp_as_sequence */
3173 0, /* tp_as_mapping */
3174 0, /* tp_hash */
3175 0, /* tp_call */
3176 0, /* tp_str */
3177 PyObject_GenericGetAttr, /* tp_getattro */
3178 0, /* tp_setattro */
3179 0, /* tp_as_buffer */
3180 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3181 Py_TPFLAGS_BASETYPE, /* tp_flags */
3182 zip_doc, /* tp_doc */
3183 (traverseproc)zip_traverse, /* tp_traverse */
3184 0, /* tp_clear */
3185 0, /* tp_richcompare */
3186 0, /* tp_weaklistoffset */
3187 PyObject_SelfIter, /* tp_iter */
3188 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003189 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 0, /* tp_members */
3191 0, /* tp_getset */
3192 0, /* tp_base */
3193 0, /* tp_dict */
3194 0, /* tp_descr_get */
3195 0, /* tp_descr_set */
3196 0, /* tp_dictoffset */
3197 0, /* tp_init */
3198 PyType_GenericAlloc, /* tp_alloc */
3199 zip_new, /* tp_new */
3200 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00003201};
Barry Warsawbd599b52000-08-03 15:45:29 +00003202
3203
Guido van Rossum79f25d91997-04-29 20:08:16 +00003204static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 {"__build_class__", (PyCFunction)builtin___build_class__,
3206 METH_VARARGS | METH_KEYWORDS, build_class_doc},
3207 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003208 BUILTIN_ABS_METHODDEF
3209 BUILTIN_ALL_METHODDEF
3210 BUILTIN_ANY_METHODDEF
3211 BUILTIN_ASCII_METHODDEF
3212 BUILTIN_BIN_METHODDEF
3213 BUILTIN_CALLABLE_METHODDEF
3214 BUILTIN_CHR_METHODDEF
3215 BUILTIN_COMPILE_METHODDEF
3216 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003218 BUILTIN_DIVMOD_METHODDEF
3219 BUILTIN_EVAL_METHODDEF
3220 BUILTIN_EXEC_METHODDEF
3221 BUILTIN_FORMAT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003223 BUILTIN_GLOBALS_METHODDEF
3224 BUILTIN_HASATTR_METHODDEF
3225 BUILTIN_HASH_METHODDEF
3226 BUILTIN_HEX_METHODDEF
3227 BUILTIN_ID_METHODDEF
3228 BUILTIN_INPUT_METHODDEF
3229 BUILTIN_ISINSTANCE_METHODDEF
3230 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003232 BUILTIN_LEN_METHODDEF
3233 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
3235 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
3236 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003237 BUILTIN_OCT_METHODDEF
3238 BUILTIN_ORD_METHODDEF
3239 BUILTIN_POW_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003241 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10003243 BUILTIN_SETATTR_METHODDEF
3244 BUILTIN_SORTED_METHODDEF
3245 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 {"vars", builtin_vars, METH_VARARGS, vars_doc},
3247 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00003248};
3249
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003250PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00003251"Built-in functions, exceptions, and other objects.\n\
3252\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003253Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00003254
Martin v. Löwis1a214512008-06-11 05:26:20 +00003255static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 PyModuleDef_HEAD_INIT,
3257 "builtins",
3258 builtin_doc,
3259 -1, /* multiple "initialization" just copies the module dict. */
3260 builtin_methods,
3261 NULL,
3262 NULL,
3263 NULL,
3264 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003265};
3266
3267
Guido van Rossum25ce5661997-08-02 03:10:38 +00003268PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003269_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00003270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04003272
3273 if (PyType_Ready(&PyFilter_Type) < 0 ||
3274 PyType_Ready(&PyMap_Type) < 0 ||
3275 PyType_Ready(&PyZip_Type) < 0)
3276 return NULL;
3277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 mod = PyModule_Create(&builtinsmodule);
3279 if (mod == NULL)
3280 return NULL;
3281 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00003282
Tim Peters7571a0f2003-03-23 17:52:28 +00003283#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 /* "builtins" exposes a number of statically allocated objects
3285 * that, before this code was added in 2.3, never showed up in
3286 * the list of "all objects" maintained by Py_TRACE_REFS. As a
3287 * result, programs leaking references to None and False (etc)
3288 * couldn't be diagnosed by examining sys.getobjects(0).
3289 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003290#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
3291#else
3292#define ADD_TO_ALL(OBJECT) (void)0
3293#endif
3294
Tim Peters4b7625e2001-09-13 21:37:17 +00003295#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
3297 return NULL; \
3298 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 SETBUILTIN("None", Py_None);
3301 SETBUILTIN("Ellipsis", Py_Ellipsis);
3302 SETBUILTIN("NotImplemented", Py_NotImplemented);
3303 SETBUILTIN("False", Py_False);
3304 SETBUILTIN("True", Py_True);
3305 SETBUILTIN("bool", &PyBool_Type);
3306 SETBUILTIN("memoryview", &PyMemoryView_Type);
3307 SETBUILTIN("bytearray", &PyByteArray_Type);
3308 SETBUILTIN("bytes", &PyBytes_Type);
3309 SETBUILTIN("classmethod", &PyClassMethod_Type);
3310 SETBUILTIN("complex", &PyComplex_Type);
3311 SETBUILTIN("dict", &PyDict_Type);
3312 SETBUILTIN("enumerate", &PyEnum_Type);
3313 SETBUILTIN("filter", &PyFilter_Type);
3314 SETBUILTIN("float", &PyFloat_Type);
3315 SETBUILTIN("frozenset", &PyFrozenSet_Type);
3316 SETBUILTIN("property", &PyProperty_Type);
3317 SETBUILTIN("int", &PyLong_Type);
3318 SETBUILTIN("list", &PyList_Type);
3319 SETBUILTIN("map", &PyMap_Type);
3320 SETBUILTIN("object", &PyBaseObject_Type);
3321 SETBUILTIN("range", &PyRange_Type);
3322 SETBUILTIN("reversed", &PyReversed_Type);
3323 SETBUILTIN("set", &PySet_Type);
3324 SETBUILTIN("slice", &PySlice_Type);
3325 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
3326 SETBUILTIN("str", &PyUnicode_Type);
3327 SETBUILTIN("super", &PySuper_Type);
3328 SETBUILTIN("tuple", &PyTuple_Type);
3329 SETBUILTIN("type", &PyType_Type);
3330 SETBUILTIN("zip", &PyZip_Type);
3331 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
3332 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
3333 Py_XDECREF(debug);
3334 return NULL;
3335 }
3336 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00003339#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00003340#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00003341}