blob: 2f22209e9d68618dd7a53ee052701f2a472cf936 [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
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030049#include "clinic/bltinmodule.c.h"
50
Nick Coghlanf9e227e2014-08-17 14:01:19 +100051/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000052static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000053builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
54{
Nick Coghlande31b192011-10-23 22:04:16 +100055 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020057 Py_ssize_t nargs;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010058 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 assert(args != NULL);
61 if (!PyTuple_Check(args)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: args is not a tuple");
64 return NULL;
65 }
66 nargs = PyTuple_GET_SIZE(args);
67 if (nargs < 2) {
68 PyErr_SetString(PyExc_TypeError,
69 "__build_class__: not enough arguments");
70 return NULL;
71 }
72 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050073 if (!PyFunction_Check(func)) {
74 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050075 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050076 return NULL;
77 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 name = PyTuple_GET_ITEM(args, 1);
79 if (!PyUnicode_Check(name)) {
80 PyErr_SetString(PyExc_TypeError,
81 "__build_class__: name is not a string");
82 return NULL;
83 }
84 bases = PyTuple_GetSlice(args, 2, nargs);
85 if (bases == NULL)
86 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 if (kwds == NULL) {
89 meta = NULL;
90 mkw = NULL;
91 }
92 else {
93 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
94 if (mkw == NULL) {
95 Py_DECREF(bases);
96 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000097 }
Victor Stinnerae9f1612013-11-06 22:46:51 +010098 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 if (meta != NULL) {
100 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100101 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 Py_DECREF(meta);
103 Py_DECREF(mkw);
104 Py_DECREF(bases);
105 return NULL;
106 }
Nick Coghlande31b192011-10-23 22:04:16 +1000107 /* metaclass is explicitly given, check if it's indeed a class */
108 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 }
110 }
111 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000112 /* if there are no bases, use type: */
113 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000115 }
116 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 else {
118 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
119 meta = (PyObject *) (base0->ob_type);
120 }
121 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000122 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000124
Nick Coghlande31b192011-10-23 22:04:16 +1000125 if (isclass) {
126 /* meta is really a class, so check for a more derived
127 metaclass, or possible metaclass conflicts: */
128 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
129 bases);
130 if (winner == NULL) {
131 Py_DECREF(meta);
132 Py_XDECREF(mkw);
133 Py_DECREF(bases);
134 return NULL;
135 }
136 if (winner != meta) {
137 Py_DECREF(meta);
138 meta = winner;
139 Py_INCREF(meta);
140 }
141 }
142 /* else: meta is not a class, so we cannot do the metaclass
143 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200144 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 if (prep == NULL) {
146 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
147 PyErr_Clear();
148 ns = PyDict_New();
149 }
150 else {
151 Py_DECREF(meta);
152 Py_XDECREF(mkw);
153 Py_DECREF(bases);
154 return NULL;
155 }
156 }
157 else {
158 PyObject *pargs = PyTuple_Pack(2, name, bases);
159 if (pargs == NULL) {
160 Py_DECREF(prep);
161 Py_DECREF(meta);
162 Py_XDECREF(mkw);
163 Py_DECREF(bases);
164 return NULL;
165 }
166 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
167 Py_DECREF(pargs);
168 Py_DECREF(prep);
169 }
170 if (ns == NULL) {
171 Py_DECREF(meta);
172 Py_XDECREF(mkw);
173 Py_DECREF(bases);
174 return NULL;
175 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500176 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
177 NULL, 0, NULL, 0, NULL, 0, NULL,
178 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (cell != NULL) {
180 PyObject *margs;
181 margs = PyTuple_Pack(3, name, bases, ns);
182 if (margs != NULL) {
183 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
184 Py_DECREF(margs);
185 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700186 if (cls != NULL && PyCell_Check(cell))
187 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 Py_DECREF(cell);
189 }
190 Py_DECREF(ns);
191 Py_DECREF(meta);
192 Py_XDECREF(mkw);
193 Py_DECREF(bases);
194 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000195}
196
197PyDoc_STRVAR(build_class_doc,
198"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
199\n\
200Internal helper function used by the class statement.");
201
202static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000203builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
206 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400207 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400208 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000209
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400210 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 kwlist, &name, &globals, &locals, &fromlist, &level))
212 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400213 return PyImport_ImportModuleLevelObject(name, globals, locals,
214 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000215}
216
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000217PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400218"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000219\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000220Import a module. Because this function is meant for use by the Python\n\
221interpreter and not for general use it is better to use\n\
222importlib.import_module() to programmatically import a module.\n\
223\n\
224The globals argument is only used to determine the context;\n\
225they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000226should be a list of names to emulate ``from name import ...'', or an\n\
227empty list to emulate ``import name''.\n\
228When importing a module from a package, note that __import__('A.B', ...)\n\
229returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000230fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400231absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000232is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000233
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000234
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000235/*[clinic input]
236abs as builtin_abs
237
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300238 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000239 /
240
241Return the absolute value of the argument.
242[clinic start generated code]*/
243
Guido van Rossum79f25d91997-04-29 20:08:16 +0000244static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000245builtin_abs(PyModuleDef *module, PyObject *x)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300246/*[clinic end generated code: output=6833047c493ecea2 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000247{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000248 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000249}
250
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000251/*[clinic input]
252all as builtin_all
253
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300254 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000255 /
256
257Return True if bool(x) is True for all values x in the iterable.
258
259If the iterable is empty, return True.
260[clinic start generated code]*/
261
Raymond Hettinger96229b12005-03-11 06:49:40 +0000262static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000263builtin_all(PyModuleDef *module, PyObject *iterable)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300264/*[clinic end generated code: output=089e6d1b7bde27b1 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 PyObject *it, *item;
267 PyObject *(*iternext)(PyObject *);
268 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000269
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000270 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (it == NULL)
272 return NULL;
273 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 for (;;) {
276 item = iternext(it);
277 if (item == NULL)
278 break;
279 cmp = PyObject_IsTrue(item);
280 Py_DECREF(item);
281 if (cmp < 0) {
282 Py_DECREF(it);
283 return NULL;
284 }
285 if (cmp == 0) {
286 Py_DECREF(it);
287 Py_RETURN_FALSE;
288 }
289 }
290 Py_DECREF(it);
291 if (PyErr_Occurred()) {
292 if (PyErr_ExceptionMatches(PyExc_StopIteration))
293 PyErr_Clear();
294 else
295 return NULL;
296 }
297 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000298}
299
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000300/*[clinic input]
301any as builtin_any
302
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300303 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000304 /
305
306Return True if bool(x) is True for any x in the iterable.
307
308If the iterable is empty, return False.
309[clinic start generated code]*/
310
Raymond Hettinger96229b12005-03-11 06:49:40 +0000311static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000312builtin_any(PyModuleDef *module, PyObject *iterable)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300313/*[clinic end generated code: output=1be994b2c2307492 input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyObject *it, *item;
316 PyObject *(*iternext)(PyObject *);
317 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000318
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000319 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (it == NULL)
321 return NULL;
322 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 for (;;) {
325 item = iternext(it);
326 if (item == NULL)
327 break;
328 cmp = PyObject_IsTrue(item);
329 Py_DECREF(item);
330 if (cmp < 0) {
331 Py_DECREF(it);
332 return NULL;
333 }
334 if (cmp == 1) {
335 Py_DECREF(it);
336 Py_RETURN_TRUE;
337 }
338 }
339 Py_DECREF(it);
340 if (PyErr_Occurred()) {
341 if (PyErr_ExceptionMatches(PyExc_StopIteration))
342 PyErr_Clear();
343 else
344 return NULL;
345 }
346 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000347}
348
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000349/*[clinic input]
350ascii as builtin_ascii
351
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300352 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000353 /
354
355Return an ASCII-only representation of an object.
356
357As repr(), return a string containing a printable representation of an
358object, but escape the non-ASCII characters in the string returned by
359repr() using \\x, \\u or \\U escapes. This generates a string similar
360to that returned by repr() in Python 2.
361[clinic start generated code]*/
362
Georg Brandl559e5d72008-06-11 18:37:52 +0000363static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000364builtin_ascii(PyModuleDef *module, PyObject *obj)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300365/*[clinic end generated code: output=d4e862c48af2a933 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000366{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000367 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000368}
369
Georg Brandl559e5d72008-06-11 18:37:52 +0000370
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000371/*[clinic input]
372bin as builtin_bin
373
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300374 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000375 /
376
377Return the binary representation of an integer.
378
379 >>> bin(2796202)
380 '0b1010101010101010101010'
381[clinic start generated code]*/
382
Guido van Rossum79f25d91997-04-29 20:08:16 +0000383static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000384builtin_bin(PyModuleDef *module, PyObject *number)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300385/*[clinic end generated code: output=25ee26c6cf3bbb54 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000386{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000387 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000388}
389
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000390
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000391/*[clinic input]
392callable as builtin_callable
393
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300394 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000395 /
396
397Return whether the object is callable (i.e., some kind of function).
398
399Note that classes are callable, as are instances of classes with a
400__call__() method.
401[clinic start generated code]*/
402
Antoine Pitroue71362d2010-11-27 22:00:11 +0000403static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000404builtin_callable(PyModuleDef *module, PyObject *obj)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300405/*[clinic end generated code: output=f4df2ce92364b656 input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000406{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000407 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000408}
409
Antoine Pitroue71362d2010-11-27 22:00:11 +0000410
Raymond Hettinger17301e92008-03-13 00:19:26 +0000411typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 PyObject_HEAD
413 PyObject *func;
414 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000415} filterobject;
416
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000417static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject *func, *seq;
421 PyObject *it;
422 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
425 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
428 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 /* Get iterator. */
431 it = PyObject_GetIter(seq);
432 if (it == NULL)
433 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* create filterobject structure */
436 lz = (filterobject *)type->tp_alloc(type, 0);
437 if (lz == NULL) {
438 Py_DECREF(it);
439 return NULL;
440 }
441 Py_INCREF(func);
442 lz->func = func;
443 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000446}
447
448static void
449filter_dealloc(filterobject *lz)
450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 PyObject_GC_UnTrack(lz);
452 Py_XDECREF(lz->func);
453 Py_XDECREF(lz->it);
454 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000455}
456
457static int
458filter_traverse(filterobject *lz, visitproc visit, void *arg)
459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 Py_VISIT(lz->it);
461 Py_VISIT(lz->func);
462 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000463}
464
465static PyObject *
466filter_next(filterobject *lz)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 PyObject *item;
469 PyObject *it = lz->it;
470 long ok;
471 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 iternext = *Py_TYPE(it)->tp_iternext;
474 for (;;) {
475 item = iternext(it);
476 if (item == NULL)
477 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
480 ok = PyObject_IsTrue(item);
481 } else {
482 PyObject *good;
483 good = PyObject_CallFunctionObjArgs(lz->func,
484 item, NULL);
485 if (good == NULL) {
486 Py_DECREF(item);
487 return NULL;
488 }
489 ok = PyObject_IsTrue(good);
490 Py_DECREF(good);
491 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200492 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return item;
494 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200495 if (ok < 0)
496 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000498}
499
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000500static PyObject *
501filter_reduce(filterobject *lz)
502{
503 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
504}
505
506PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
507
508static PyMethodDef filter_methods[] = {
509 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
510 {NULL, NULL} /* sentinel */
511};
512
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000513PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000514"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000515\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000516Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000517is true. If function is None, return the items that are true.");
518
519PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 PyVarObject_HEAD_INIT(&PyType_Type, 0)
521 "filter", /* tp_name */
522 sizeof(filterobject), /* tp_basicsize */
523 0, /* tp_itemsize */
524 /* methods */
525 (destructor)filter_dealloc, /* tp_dealloc */
526 0, /* tp_print */
527 0, /* tp_getattr */
528 0, /* tp_setattr */
529 0, /* tp_reserved */
530 0, /* tp_repr */
531 0, /* tp_as_number */
532 0, /* tp_as_sequence */
533 0, /* tp_as_mapping */
534 0, /* tp_hash */
535 0, /* tp_call */
536 0, /* tp_str */
537 PyObject_GenericGetAttr, /* tp_getattro */
538 0, /* tp_setattro */
539 0, /* tp_as_buffer */
540 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
541 Py_TPFLAGS_BASETYPE, /* tp_flags */
542 filter_doc, /* tp_doc */
543 (traverseproc)filter_traverse, /* tp_traverse */
544 0, /* tp_clear */
545 0, /* tp_richcompare */
546 0, /* tp_weaklistoffset */
547 PyObject_SelfIter, /* tp_iter */
548 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000549 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 0, /* tp_members */
551 0, /* tp_getset */
552 0, /* tp_base */
553 0, /* tp_dict */
554 0, /* tp_descr_get */
555 0, /* tp_descr_set */
556 0, /* tp_dictoffset */
557 0, /* tp_init */
558 PyType_GenericAlloc, /* tp_alloc */
559 filter_new, /* tp_new */
560 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000561};
562
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000563
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000564/*[clinic input]
565format as builtin_format
566
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300567 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000568 format_spec: unicode(c_default="NULL") = ''
569 /
570
571Return value.__format__(format_spec)
572
573format_spec defaults to the empty string
574[clinic start generated code]*/
575
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000576static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -0400577builtin_format_impl(PyModuleDef *module, PyObject *value,
578 PyObject *format_spec)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300579/*[clinic end generated code: output=4341fd78a5f01764 input=6325e751a1b29b86]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000580{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000581 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000582}
583
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000584/*[clinic input]
585chr as builtin_chr
586
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300587 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000588 /
589
590Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
591[clinic start generated code]*/
592
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000593static PyObject *
594builtin_chr_impl(PyModuleDef *module, int i)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300595/*[clinic end generated code: output=67fe4d87e690f373 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000596{
597 return PyUnicode_FromOrdinal(i);
598}
Guido van Rossum09095f32000-03-10 23:00:52 +0000599
600
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200601static const char *
602source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, Py_buffer *view)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000603{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200604 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (PyUnicode_Check(cmd)) {
608 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200609 str = PyUnicode_AsUTF8AndSize(cmd, &size);
610 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return NULL;
612 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200613 else if (PyObject_GetBuffer(cmd, view, PyBUF_SIMPLE) == 0) {
614 str = (const char *)view->buf;
615 size = view->len;
616 }
617 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 PyErr_Format(PyExc_TypeError,
619 "%s() arg 1 must be a %s object",
620 funcname, what);
621 return NULL;
622 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200623
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200624 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300625 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 "source code string cannot contain null bytes");
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200627 PyBuffer_Release(view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 return NULL;
629 }
630 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000631}
632
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000633/*[clinic input]
634compile as builtin_compile
635
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300636 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000637 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300638 mode: str
639 flags: int = 0
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300640 dont_inherit: int(c_default="0") = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300641 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000642
643Compile source into a code object that can be executed by exec() or eval().
644
645The source code may represent a Python module, statement or expression.
646The filename will be used for run-time error messages.
647The mode must be 'exec' to compile a module, 'single' to compile a
648single (interactive) statement, or 'eval' to compile an expression.
649The flags argument, if present, controls which future statements influence
650the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300651The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000652the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300653compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000654in addition to any features explicitly specified.
655[clinic start generated code]*/
656
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000657static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -0400658builtin_compile_impl(PyModuleDef *module, PyObject *source,
659 PyObject *filename, const char *mode, int flags,
660 int dont_inherit, int optimize)
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300661/*[clinic end generated code: output=31881762c1bb90c4 input=9d53e8cfb3c86414]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000662{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200663 Py_buffer view = {NULL, NULL};
664 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000665 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 int is_ast;
667 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000669 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000670
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000671 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000672
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000673 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
675 {
676 PyErr_SetString(PyExc_ValueError,
677 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000678 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
680 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000681
Georg Brandl8334fd92010-12-04 10:26:46 +0000682 if (optimize < -1 || optimize > 2) {
683 PyErr_SetString(PyExc_ValueError,
684 "compile(): invalid optimize value");
685 goto error;
686 }
687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (!dont_inherit) {
689 PyEval_MergeCompilerFlags(&cf);
690 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000691
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000692 if (strcmp(mode, "exec") == 0)
693 compile_mode = 0;
694 else if (strcmp(mode, "eval") == 0)
695 compile_mode = 1;
696 else if (strcmp(mode, "single") == 0)
697 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 else {
699 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000700 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000701 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000703
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000704 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000706 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000708 if (flags & PyCF_ONLY_AST) {
709 Py_INCREF(source);
710 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 }
712 else {
713 PyArena *arena;
714 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200717 if (arena == NULL)
718 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000719 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (mod == NULL) {
721 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000722 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500724 if (!PyAST_Validate(mod)) {
725 PyArena_Free(arena);
726 goto error;
727 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200728 result = (PyObject*)PyAST_CompileObject(mod, filename,
729 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 PyArena_Free(arena);
731 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000732 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000734
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200735 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000737 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000738
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000739 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200740 PyBuffer_Release(&view);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000741 goto finally;
742
743error:
744 result = NULL;
745finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200746 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000747 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000748}
749
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000750/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000751static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000752builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
757 return NULL;
758 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000759}
760
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000761PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000762"dir([object]) -> list of strings\n"
763"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000764"If called without an argument, return the names in the current scope.\n"
765"Else, return an alphabetized list of names comprising (some of) the attributes\n"
766"of the given object, and of attributes reachable from it.\n"
767"If the object supplies a method named __dir__, it will be used; otherwise\n"
768"the default dir() logic is used and returns:\n"
769" for a module object: the module's attributes.\n"
770" for a class object: its attributes, and recursively the attributes\n"
771" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000772" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000773" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000774
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000775/*[clinic input]
776divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000777
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300778 x: object
779 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000780 /
781
782Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.
783[clinic start generated code]*/
784
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000785static PyObject *
786builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300787/*[clinic end generated code: output=9ad0076120ebf9ac input=7fdb15f8a97a5fe7]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000788{
789 return PyNumber_Divmod(x, y);
790}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000791
792
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000793/*[clinic input]
794eval as builtin_eval
795
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300796 source: object
797 globals: object = None
798 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000799 /
800
801Evaluate the given source in the context of globals and locals.
802
803The source may be a string representing a Python expression
804or a code object as returned by compile().
805The globals must be a dictionary and locals can be any mapping,
806defaulting to the current globals and locals.
807If only globals is given, locals defaults to it.
808[clinic start generated code]*/
809
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000810static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -0400811builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals,
812 PyObject *locals)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300813/*[clinic end generated code: output=7284501fb7b4d666 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000814{
815 PyObject *result, *tmp = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200816 Py_buffer view = {NULL, NULL};
817 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (locals != Py_None && !PyMapping_Check(locals)) {
821 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
822 return NULL;
823 }
824 if (globals != Py_None && !PyDict_Check(globals)) {
825 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
826 "globals must be a real dict; try eval(expr, {}, mapping)"
827 : "globals must be a dict");
828 return NULL;
829 }
830 if (globals == Py_None) {
831 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100832 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100834 if (locals == NULL)
835 return NULL;
836 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 }
838 else if (locals == Py_None)
839 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (globals == NULL || locals == NULL) {
842 PyErr_SetString(PyExc_TypeError,
843 "eval must be given globals and locals "
844 "when called without a frame");
845 return NULL;
846 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000847
Victor Stinnerb44562b2013-11-06 19:03:11 +0100848 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
849 if (_PyDict_SetItemId(globals, &PyId___builtins__,
850 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 return NULL;
852 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000853
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000854 if (PyCode_Check(source)) {
855 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyErr_SetString(PyExc_TypeError,
857 "code object passed to eval() may not contain free variables");
858 return NULL;
859 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000860 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200864 str = source_as_string(source, "eval", "string, bytes or code", &cf, &view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (str == NULL)
866 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 while (*str == ' ' || *str == '\t')
869 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 (void)PyEval_MergeCompilerFlags(&cf);
872 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200873 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 Py_XDECREF(tmp);
875 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000876}
877
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000878/*[clinic input]
879exec as builtin_exec
880
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300881 source: object
882 globals: object = None
883 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000884 /
885
886Execute the given source in the context of globals and locals.
887
888The source may be a string representing one or more Python statements
889or a code object as returned by compile().
890The globals must be a dictionary and locals can be any mapping,
891defaulting to the current globals and locals.
892If only globals is given, locals defaults to it.
893[clinic start generated code]*/
894
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000895static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -0400896builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals,
897 PyObject *locals)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300898/*[clinic end generated code: output=83d574ef9d5d0b46 input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (globals == Py_None) {
903 globals = PyEval_GetGlobals();
904 if (locals == Py_None) {
905 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100906 if (locals == NULL)
907 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
909 if (!globals || !locals) {
910 PyErr_SetString(PyExc_SystemError,
911 "globals and locals cannot be NULL");
912 return NULL;
913 }
914 }
915 else if (locals == Py_None)
916 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000919 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 globals->ob_type->tp_name);
921 return NULL;
922 }
923 if (!PyMapping_Check(locals)) {
924 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000925 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 locals->ob_type->tp_name);
927 return NULL;
928 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100929 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
930 if (_PyDict_SetItemId(globals, &PyId___builtins__,
931 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 return NULL;
933 }
934
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000935 if (PyCode_Check(source)) {
936 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 PyErr_SetString(PyExc_TypeError,
938 "code object passed to exec() may not "
939 "contain free variables");
940 return NULL;
941 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000942 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 }
944 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200945 Py_buffer view = {NULL, NULL};
946 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 PyCompilerFlags cf;
948 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000949 str = source_as_string(source, "exec",
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200950 "string, bytes or code", &cf, &view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 if (str == NULL)
952 return NULL;
953 if (PyEval_MergeCompilerFlags(&cf))
954 v = PyRun_StringFlags(str, Py_file_input, globals,
955 locals, &cf);
956 else
957 v = PyRun_String(str, Py_file_input, globals, locals);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200958 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 }
960 if (v == NULL)
961 return NULL;
962 Py_DECREF(v);
963 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000964}
965
Georg Brandl7cae87c2006-09-06 06:51:57 +0000966
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000967/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000968static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000969builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 PyObject *v, *result, *dflt = NULL;
972 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
975 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (!PyUnicode_Check(name)) {
978 PyErr_SetString(PyExc_TypeError,
979 "getattr(): attribute name must be string");
980 return NULL;
981 }
982 result = PyObject_GetAttr(v, name);
983 if (result == NULL && dflt != NULL &&
984 PyErr_ExceptionMatches(PyExc_AttributeError))
985 {
986 PyErr_Clear();
987 Py_INCREF(dflt);
988 result = dflt;
989 }
990 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000991}
992
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000993PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000994"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000995\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000996Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
997When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000998exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000999
1000
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001001/*[clinic input]
1002globals as builtin_globals
1003
1004Return the dictionary containing the current scope's global variables.
1005
1006NOTE: Updates to this dictionary *will* affect name lookups in the current
1007global scope and vice-versa.
1008[clinic start generated code]*/
1009
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001010static PyObject *
1011builtin_globals_impl(PyModuleDef *module)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001012/*[clinic end generated code: output=4958645e96dd8138 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 d = PyEval_GetGlobals();
1017 Py_XINCREF(d);
1018 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001019}
1020
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001021
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001022/*[clinic input]
1023hasattr as builtin_hasattr
1024
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001025 obj: object
1026 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001027 /
1028
1029Return whether the object has an attribute with the given name.
1030
1031This is done by calling getattr(obj, name) and catching AttributeError.
1032[clinic start generated code]*/
1033
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001034static PyObject *
1035builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001036/*[clinic end generated code: output=81154fdd63634696 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001037{
1038 PyObject *v;
1039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (!PyUnicode_Check(name)) {
1041 PyErr_SetString(PyExc_TypeError,
1042 "hasattr(): attribute name must be string");
1043 return NULL;
1044 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001045 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001047 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001049 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001051 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 }
1053 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001054 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001055}
1056
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001057
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001058/* AC: gdb's integration with CPython relies on builtin_id having
1059 * the *exact* parameter names of "self" and "v", so we ensure we
1060 * preserve those name rather than using the AC defaults.
1061 */
1062/*[clinic input]
1063id as builtin_id
1064
1065 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001066 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001067 /
1068
1069Return the identity of an object.
1070
1071This is guaranteed to be unique among simultaneously existing objects.
1072(CPython uses the object's memory address.)
1073[clinic start generated code]*/
1074
Guido van Rossum79f25d91997-04-29 20:08:16 +00001075static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001076builtin_id(PyModuleDef *self, PyObject *v)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001077/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001080}
1081
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001082
Raymond Hettingera6c60372008-03-13 01:26:19 +00001083/* map object ************************************************************/
1084
1085typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 PyObject_HEAD
1087 PyObject *iters;
1088 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001089} mapobject;
1090
Guido van Rossum79f25d91997-04-29 20:08:16 +00001091static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001092map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyObject *it, *iters, *func;
1095 mapobject *lz;
1096 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1099 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 numargs = PyTuple_Size(args);
1102 if (numargs < 2) {
1103 PyErr_SetString(PyExc_TypeError,
1104 "map() must have at least two arguments.");
1105 return NULL;
1106 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 iters = PyTuple_New(numargs-1);
1109 if (iters == NULL)
1110 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 for (i=1 ; i<numargs ; i++) {
1113 /* Get iterator. */
1114 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1115 if (it == NULL) {
1116 Py_DECREF(iters);
1117 return NULL;
1118 }
1119 PyTuple_SET_ITEM(iters, i-1, it);
1120 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 /* create mapobject structure */
1123 lz = (mapobject *)type->tp_alloc(type, 0);
1124 if (lz == NULL) {
1125 Py_DECREF(iters);
1126 return NULL;
1127 }
1128 lz->iters = iters;
1129 func = PyTuple_GET_ITEM(args, 0);
1130 Py_INCREF(func);
1131 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001134}
1135
1136static void
1137map_dealloc(mapobject *lz)
1138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyObject_GC_UnTrack(lz);
1140 Py_XDECREF(lz->iters);
1141 Py_XDECREF(lz->func);
1142 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001143}
1144
1145static int
1146map_traverse(mapobject *lz, visitproc visit, void *arg)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 Py_VISIT(lz->iters);
1149 Py_VISIT(lz->func);
1150 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001151}
1152
1153static PyObject *
1154map_next(mapobject *lz)
1155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 PyObject *val;
1157 PyObject *argtuple;
1158 PyObject *result;
1159 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 numargs = PyTuple_Size(lz->iters);
1162 argtuple = PyTuple_New(numargs);
1163 if (argtuple == NULL)
1164 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 for (i=0 ; i<numargs ; i++) {
1167 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1168 if (val == NULL) {
1169 Py_DECREF(argtuple);
1170 return NULL;
1171 }
1172 PyTuple_SET_ITEM(argtuple, i, val);
1173 }
1174 result = PyObject_Call(lz->func, argtuple, NULL);
1175 Py_DECREF(argtuple);
1176 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001177}
1178
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001179static PyObject *
1180map_reduce(mapobject *lz)
1181{
1182 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1183 PyObject *args = PyTuple_New(numargs+1);
1184 Py_ssize_t i;
1185 if (args == NULL)
1186 return NULL;
1187 Py_INCREF(lz->func);
1188 PyTuple_SET_ITEM(args, 0, lz->func);
1189 for (i = 0; i<numargs; i++){
1190 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1191 Py_INCREF(it);
1192 PyTuple_SET_ITEM(args, i+1, it);
1193 }
1194
1195 return Py_BuildValue("ON", Py_TYPE(lz), args);
1196}
1197
1198static PyMethodDef map_methods[] = {
1199 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1200 {NULL, NULL} /* sentinel */
1201};
1202
1203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001204PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001205"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001206\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001207Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001209
Raymond Hettingera6c60372008-03-13 01:26:19 +00001210PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1212 "map", /* tp_name */
1213 sizeof(mapobject), /* tp_basicsize */
1214 0, /* tp_itemsize */
1215 /* methods */
1216 (destructor)map_dealloc, /* tp_dealloc */
1217 0, /* tp_print */
1218 0, /* tp_getattr */
1219 0, /* tp_setattr */
1220 0, /* tp_reserved */
1221 0, /* tp_repr */
1222 0, /* tp_as_number */
1223 0, /* tp_as_sequence */
1224 0, /* tp_as_mapping */
1225 0, /* tp_hash */
1226 0, /* tp_call */
1227 0, /* tp_str */
1228 PyObject_GenericGetAttr, /* tp_getattro */
1229 0, /* tp_setattro */
1230 0, /* tp_as_buffer */
1231 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1232 Py_TPFLAGS_BASETYPE, /* tp_flags */
1233 map_doc, /* tp_doc */
1234 (traverseproc)map_traverse, /* tp_traverse */
1235 0, /* tp_clear */
1236 0, /* tp_richcompare */
1237 0, /* tp_weaklistoffset */
1238 PyObject_SelfIter, /* tp_iter */
1239 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001240 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 0, /* tp_members */
1242 0, /* tp_getset */
1243 0, /* tp_base */
1244 0, /* tp_dict */
1245 0, /* tp_descr_get */
1246 0, /* tp_descr_set */
1247 0, /* tp_dictoffset */
1248 0, /* tp_init */
1249 PyType_GenericAlloc, /* tp_alloc */
1250 map_new, /* tp_new */
1251 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001252};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001253
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001254
1255/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001256static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001257builtin_next(PyObject *self, PyObject *args)
1258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 PyObject *it, *res;
1260 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1263 return NULL;
1264 if (!PyIter_Check(it)) {
1265 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001266 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 it->ob_type->tp_name);
1268 return NULL;
1269 }
1270
1271 res = (*it->ob_type->tp_iternext)(it);
1272 if (res != NULL) {
1273 return res;
1274 } else if (def != NULL) {
1275 if (PyErr_Occurred()) {
1276 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1277 return NULL;
1278 PyErr_Clear();
1279 }
1280 Py_INCREF(def);
1281 return def;
1282 } else if (PyErr_Occurred()) {
1283 return NULL;
1284 } else {
1285 PyErr_SetNone(PyExc_StopIteration);
1286 return NULL;
1287 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001288}
1289
1290PyDoc_STRVAR(next_doc,
1291"next(iterator[, default])\n\
1292\n\
1293Return the next item from the iterator. If default is given and the iterator\n\
1294is exhausted, it is returned instead of raising StopIteration.");
1295
1296
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001297/*[clinic input]
1298setattr as builtin_setattr
1299
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001300 obj: object
1301 name: object
1302 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001303 /
1304
1305Sets the named attribute on the given object to the specified value.
1306
1307setattr(x, 'y', v) is equivalent to ``x.y = v''
1308[clinic start generated code]*/
1309
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001310static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001311builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name,
1312 PyObject *value)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001313/*[clinic end generated code: output=d881c655c0f7e34f input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001314{
1315 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 return NULL;
1317 Py_INCREF(Py_None);
1318 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001319}
1320
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001321
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001322/*[clinic input]
1323delattr as builtin_delattr
1324
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001325 obj: object
1326 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001327 /
1328
1329Deletes the named attribute from the given object.
1330
1331delattr(x, 'y') is equivalent to ``del x.y''
1332[clinic start generated code]*/
1333
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001334static PyObject *
1335builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001336/*[clinic end generated code: output=ef653e698a0b4187 input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001337{
1338 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 return NULL;
1340 Py_INCREF(Py_None);
1341 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001342}
1343
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001344
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001345/*[clinic input]
1346hash as builtin_hash
1347
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001348 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001349 /
1350
1351Return the hash value for the given object.
1352
1353Two objects that compare equal must also have the same hash value, but the
1354reverse is not necessarily true.
1355[clinic start generated code]*/
1356
Guido van Rossum79f25d91997-04-29 20:08:16 +00001357static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001358builtin_hash(PyModuleDef *module, PyObject *obj)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001359/*[clinic end generated code: output=1f32ff154c1f751a input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001360{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001361 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001362
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001363 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 if (x == -1)
1365 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001366 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001367}
1368
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001369
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001370/*[clinic input]
1371hex as builtin_hex
1372
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001373 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001374 /
1375
1376Return the hexadecimal representation of an integer.
1377
1378 >>> hex(12648430)
1379 '0xc0ffee'
1380[clinic start generated code]*/
1381
Guido van Rossum79f25d91997-04-29 20:08:16 +00001382static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001383builtin_hex(PyModuleDef *module, PyObject *number)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001384/*[clinic end generated code: output=618489ce3cbc5858 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001385{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001386 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001387}
1388
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001389
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001390/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001391static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001392builtin_iter(PyObject *self, PyObject *args)
1393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1397 return NULL;
1398 if (w == NULL)
1399 return PyObject_GetIter(v);
1400 if (!PyCallable_Check(v)) {
1401 PyErr_SetString(PyExc_TypeError,
1402 "iter(v, w): v must be callable");
1403 return NULL;
1404 }
1405 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001406}
1407
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001408PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001409"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001410iter(callable, sentinel) -> iterator\n\
1411\n\
1412Get an iterator from an object. In the first form, the argument must\n\
1413supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001414In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001415
1416
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001417/*[clinic input]
1418len as builtin_len
1419
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001420 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001421 /
1422
1423Return the number of items in a container.
1424[clinic start generated code]*/
1425
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001426static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001427builtin_len(PyModuleDef *module, PyObject *obj)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001428/*[clinic end generated code: output=8e5837b6f81d915b input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001431
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001432 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (res < 0 && PyErr_Occurred())
1434 return NULL;
1435 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001436}
1437
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001438
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001439/*[clinic input]
1440locals as builtin_locals
1441
1442Return a dictionary containing the current scope's local variables.
1443
1444NOTE: Whether or not updates to this dictionary will affect name lookups in
1445the local scope and vice-versa is *implementation dependent* and not
1446covered by any backwards compatibility guarantees.
1447[clinic start generated code]*/
1448
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001449static PyObject *
1450builtin_locals_impl(PyModuleDef *module)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001451/*[clinic end generated code: output=8b5a41f12e19d13a input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 d = PyEval_GetLocals();
1456 Py_XINCREF(d);
1457 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001458}
1459
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001460
Guido van Rossum79f25d91997-04-29 20:08:16 +00001461static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001462min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001465 PyObject *emptytuple, *defaultval = NULL;
1466 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001468 const int positional = PyTuple_Size(args) > 1;
1469 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001470
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001471 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001473 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001475
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001476 emptytuple = PyTuple_New(0);
1477 if (emptytuple == NULL)
1478 return NULL;
1479 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1480 &keyfunc, &defaultval);
1481 Py_DECREF(emptytuple);
1482 if (!ret)
1483 return NULL;
1484
1485 if (positional && defaultval != NULL) {
1486 PyErr_Format(PyExc_TypeError,
1487 "Cannot specify a default for %s() with multiple "
1488 "positional arguments", name);
1489 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 it = PyObject_GetIter(v);
1493 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 return NULL;
1495 }
Tim Petersc3074532001-05-03 07:00:32 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 maxitem = NULL; /* the result */
1498 maxval = NULL; /* the value associated with the result */
1499 while (( item = PyIter_Next(it) )) {
1500 /* get the value from the key function */
1501 if (keyfunc != NULL) {
1502 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1503 if (val == NULL)
1504 goto Fail_it_item;
1505 }
1506 /* no key function; the value is the item */
1507 else {
1508 val = item;
1509 Py_INCREF(val);
1510 }
Tim Petersc3074532001-05-03 07:00:32 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 /* maximum value and item are unset; set them */
1513 if (maxval == NULL) {
1514 maxitem = item;
1515 maxval = val;
1516 }
1517 /* maximum value and item are set; update them as necessary */
1518 else {
1519 int cmp = PyObject_RichCompareBool(val, maxval, op);
1520 if (cmp < 0)
1521 goto Fail_it_item_and_val;
1522 else if (cmp > 0) {
1523 Py_DECREF(maxval);
1524 Py_DECREF(maxitem);
1525 maxval = val;
1526 maxitem = item;
1527 }
1528 else {
1529 Py_DECREF(item);
1530 Py_DECREF(val);
1531 }
1532 }
1533 }
1534 if (PyErr_Occurred())
1535 goto Fail_it;
1536 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001538 if (defaultval != NULL) {
1539 Py_INCREF(defaultval);
1540 maxitem = defaultval;
1541 } else {
1542 PyErr_Format(PyExc_ValueError,
1543 "%s() arg is an empty sequence", name);
1544 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 }
1546 else
1547 Py_DECREF(maxval);
1548 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001550
1551Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001553Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001555Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 Py_XDECREF(maxval);
1557 Py_XDECREF(maxitem);
1558 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001560}
1561
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001562/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001563static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001564builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001567}
1568
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001569PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001570"min(iterable, *[, default=obj, key=func]) -> value\n\
1571min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001572\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001573With a single iterable argument, return its smallest item. The\n\
1574default keyword-only argument specifies an object to return if\n\
1575the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001576With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001577
1578
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001579/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001580static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001581builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001584}
1585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001586PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001587"max(iterable, *[, default=obj, key=func]) -> value\n\
1588max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001589\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001590With a single iterable argument, return its biggest item. The\n\
1591default keyword-only argument specifies an object to return if\n\
1592the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001593With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001594
1595
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001596/*[clinic input]
1597oct as builtin_oct
1598
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001599 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001600 /
1601
1602Return the octal representation of an integer.
1603
1604 >>> oct(342391)
1605 '0o1234567'
1606[clinic start generated code]*/
1607
Guido van Rossum79f25d91997-04-29 20:08:16 +00001608static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001609builtin_oct(PyModuleDef *module, PyObject *number)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001610/*[clinic end generated code: output=18f701bc6d8f804a input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001611{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001612 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001613}
1614
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001615
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001616/*[clinic input]
1617ord as builtin_ord
1618
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001619 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001620 /
1621
1622Return the Unicode code point for a one-character string.
1623[clinic start generated code]*/
1624
Guido van Rossum79f25d91997-04-29 20:08:16 +00001625static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001626builtin_ord(PyModuleDef *module, PyObject *c)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001627/*[clinic end generated code: output=04fd27272d9462f6 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 long ord;
1630 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001631
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001632 if (PyBytes_Check(c)) {
1633 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001635 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 return PyLong_FromLong(ord);
1637 }
1638 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001639 else if (PyUnicode_Check(c)) {
1640 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001641 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001642 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001644 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 return PyLong_FromLong(ord);
1646 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001648 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001650 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001652 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 return PyLong_FromLong(ord);
1654 }
1655 }
1656 else {
1657 PyErr_Format(PyExc_TypeError,
1658 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001659 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 return NULL;
1661 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyErr_Format(PyExc_TypeError,
1664 "ord() expected a character, "
1665 "but string of length %zd found",
1666 size);
1667 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001668}
1669
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001670
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001671/*[clinic input]
1672pow as builtin_pow
1673
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001674 x: object
1675 y: object
1676 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001677 /
1678
1679Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1680
1681Some types, such as ints, are able to use a more efficient algorithm when
1682invoked using the three argument form.
1683[clinic start generated code]*/
1684
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001685static PyObject *
1686builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001687/*[clinic end generated code: output=1fba268adba9b45f input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001688{
1689 return PyNumber_Power(x, y, z);
1690}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001691
1692
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001693/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001694static PyObject *
1695builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1696{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001697 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001699 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001701
Benjamin Peterson00102562012-01-11 21:00:16 -05001702 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001703 return NULL;
1704 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1705 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 return NULL;
1707 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001708 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001709 if (file == NULL) {
1710 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1711 return NULL;
1712 }
1713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 /* sys.stdout may be None when FILE* stdout isn't connected */
1715 if (file == Py_None)
1716 Py_RETURN_NONE;
1717 }
Guido van Rossum34343512006-11-30 22:13:52 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 if (sep == Py_None) {
1720 sep = NULL;
1721 }
1722 else if (sep && !PyUnicode_Check(sep)) {
1723 PyErr_Format(PyExc_TypeError,
1724 "sep must be None or a string, not %.200s",
1725 sep->ob_type->tp_name);
1726 return NULL;
1727 }
1728 if (end == Py_None) {
1729 end = NULL;
1730 }
1731 else if (end && !PyUnicode_Check(end)) {
1732 PyErr_Format(PyExc_TypeError,
1733 "end must be None or a string, not %.200s",
1734 end->ob_type->tp_name);
1735 return NULL;
1736 }
Guido van Rossum34343512006-11-30 22:13:52 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 for (i = 0; i < PyTuple_Size(args); i++) {
1739 if (i > 0) {
1740 if (sep == NULL)
1741 err = PyFile_WriteString(" ", file);
1742 else
1743 err = PyFile_WriteObject(sep, file,
1744 Py_PRINT_RAW);
1745 if (err)
1746 return NULL;
1747 }
1748 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1749 Py_PRINT_RAW);
1750 if (err)
1751 return NULL;
1752 }
Guido van Rossum34343512006-11-30 22:13:52 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (end == NULL)
1755 err = PyFile_WriteString("\n", file);
1756 else
1757 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1758 if (err)
1759 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001760
Georg Brandlbc3b6822012-01-13 19:41:25 +01001761 if (flush != NULL) {
1762 PyObject *tmp;
1763 int do_flush = PyObject_IsTrue(flush);
1764 if (do_flush == -1)
1765 return NULL;
1766 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001767 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001768 if (tmp == NULL)
1769 return NULL;
1770 else
1771 Py_DECREF(tmp);
1772 }
1773 }
1774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001776}
1777
1778PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001779"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001780\n\
1781Prints the values to a stream, or to sys.stdout by default.\n\
1782Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001783file: a file-like object (stream); defaults to the current sys.stdout.\n\
1784sep: string inserted between values, default a space.\n\
1785end: string appended after the last value, default a newline.\n\
1786flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001787
1788
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001789/*[clinic input]
1790input as builtin_input
1791
1792 prompt: object(c_default="NULL") = None
1793 /
1794
1795Read a string from standard input. The trailing newline is stripped.
1796
1797The prompt string, if given, is printed to standard output without a
1798trailing newline before reading input.
1799
1800If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1801On *nix systems, readline is used if available.
1802[clinic start generated code]*/
1803
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001804static PyObject *
1805builtin_input_impl(PyModuleDef *module, PyObject *prompt)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03001806/*[clinic end generated code: output=b77731f59e1515c4 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001807{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001808 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1809 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1810 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 PyObject *tmp;
1812 long fd;
1813 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 /* Check that stdin/out/err are intact */
1816 if (fin == NULL || fin == Py_None) {
1817 PyErr_SetString(PyExc_RuntimeError,
1818 "input(): lost sys.stdin");
1819 return NULL;
1820 }
1821 if (fout == NULL || fout == Py_None) {
1822 PyErr_SetString(PyExc_RuntimeError,
1823 "input(): lost sys.stdout");
1824 return NULL;
1825 }
1826 if (ferr == NULL || ferr == Py_None) {
1827 PyErr_SetString(PyExc_RuntimeError,
1828 "input(): lost sys.stderr");
1829 return NULL;
1830 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001833 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (tmp == NULL)
1835 PyErr_Clear();
1836 else
1837 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 /* We should only use (GNU) readline if Python's sys.stdin and
1840 sys.stdout are the same as C's stdin and stdout, because we
1841 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001842 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (tmp == NULL) {
1844 PyErr_Clear();
1845 tty = 0;
1846 }
1847 else {
1848 fd = PyLong_AsLong(tmp);
1849 Py_DECREF(tmp);
1850 if (fd < 0 && PyErr_Occurred())
1851 return NULL;
1852 tty = fd == fileno(stdin) && isatty(fd);
1853 }
1854 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001855 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 if (tmp == NULL)
1857 PyErr_Clear();
1858 else {
1859 fd = PyLong_AsLong(tmp);
1860 Py_DECREF(tmp);
1861 if (fd < 0 && PyErr_Occurred())
1862 return NULL;
1863 tty = fd == fileno(stdout) && isatty(fd);
1864 }
1865 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 /* If we're interactive, use (GNU) readline */
1868 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001869 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001870 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001871 char *s = NULL;
1872 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1873 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1874 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001876 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001877
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001878 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001879 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001880 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* stdin is a text stream, so it must have an
1882 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001883 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001884 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001885 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1886 if (!stdin_encoding_str || !stdin_errors_str)
1887 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001888 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (tmp == NULL)
1890 PyErr_Clear();
1891 else
1892 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001893 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001894 /* We have a prompt, encode it as stdout would */
1895 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001897 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001898 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001899 if (!stdout_encoding || !stdout_errors)
1900 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001901 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001902 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1903 if (!stdout_encoding_str || !stdout_errors_str)
1904 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001905 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001906 if (stringpo == NULL)
1907 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001909 stdout_encoding_str, stdout_errors_str);
1910 Py_CLEAR(stdout_encoding);
1911 Py_CLEAR(stdout_errors);
1912 Py_CLEAR(stringpo);
1913 if (po == NULL)
1914 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001915 promptstr = PyBytes_AsString(po);
1916 if (promptstr == NULL)
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001917 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 }
1919 else {
1920 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001921 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001923 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001925 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 if (!PyErr_Occurred())
1927 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001928 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001930
1931 len = strlen(s);
1932 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 PyErr_SetNone(PyExc_EOFError);
1934 result = NULL;
1935 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001936 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 if (len > PY_SSIZE_T_MAX) {
1938 PyErr_SetString(PyExc_OverflowError,
1939 "input: input too long");
1940 result = NULL;
1941 }
1942 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001943 len--; /* strip trailing '\n' */
1944 if (len != 0 && s[len-1] == '\r')
1945 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001946 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1947 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 }
1949 }
1950 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001951 Py_DECREF(stdin_errors);
1952 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 PyMem_FREE(s);
1954 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001955 _readline_errors:
1956 Py_XDECREF(stdin_encoding);
1957 Py_XDECREF(stdout_encoding);
1958 Py_XDECREF(stdin_errors);
1959 Py_XDECREF(stdout_errors);
1960 Py_XDECREF(po);
1961 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001965 if (prompt != NULL) {
1966 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 return NULL;
1968 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001969 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (tmp == NULL)
1971 PyErr_Clear();
1972 else
1973 Py_DECREF(tmp);
1974 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001975}
1976
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001977
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001978/*[clinic input]
1979repr as builtin_repr
1980
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001981 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001982 /
1983
1984Return the canonical string representation of the object.
1985
1986For many object types, including most builtins, eval(repr(obj)) == obj.
1987[clinic start generated code]*/
1988
Guido van Rossum79f25d91997-04-29 20:08:16 +00001989static PyObject *
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001990builtin_repr(PyModuleDef *module, PyObject *obj)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001991/*[clinic end generated code: output=dc41784fa4341834 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00001992{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001993 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001994}
1995
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001996
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001997/* AC: cannot convert yet, as needs PEP 457 group support in inspect
1998 * or a semantic change to accept None for "ndigits"
1999 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002000static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002001builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 PyObject *ndigits = NULL;
2004 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002005 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2008 kwlist, &number, &ndigits))
2009 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (Py_TYPE(number)->tp_dict == NULL) {
2012 if (PyType_Ready(Py_TYPE(number)) < 0)
2013 return NULL;
2014 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002015
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002016 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002018 if (!PyErr_Occurred())
2019 PyErr_Format(PyExc_TypeError,
2020 "type %.100s doesn't define __round__ method",
2021 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 return NULL;
2023 }
Alex Martelliae211f92007-08-22 23:21:33 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002026 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002028 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2029 Py_DECREF(round);
2030 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002031}
2032
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002033PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002034"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002035\n\
2036Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002037This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002038same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002039
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002040
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002041/*AC: we need to keep the kwds dict intact to easily call into the
2042 * list.sort method, which isn't currently supported in AC. So we just use
2043 * the initially generated signature with a custom implementation.
2044 */
2045/* [disabled clinic input]
2046sorted as builtin_sorted
2047
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002048 iterable as seq: object
2049 key as keyfunc: object = None
2050 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002051
2052Return a new list containing all items from the iterable in ascending order.
2053
2054A custom key function can be supplied to customise the sort order, and the
2055reverse flag can be set to request the result in descending order.
2056[end disabled clinic input]*/
2057
2058PyDoc_STRVAR(builtin_sorted__doc__,
2059"sorted($module, iterable, key=None, reverse=False)\n"
2060"--\n"
2061"\n"
2062"Return a new list containing all items from the iterable in ascending order.\n"
2063"\n"
2064"A custom key function can be supplied to customise the sort order, and the\n"
2065"reverse flag can be set to request the result in descending order.");
2066
2067#define BUILTIN_SORTED_METHODDEF \
2068 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
2069
Raymond Hettinger64958a12003-12-17 20:43:33 +00002070static PyObject *
2071builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
2074 PyObject *callable;
2075 static char *kwlist[] = {"iterable", "key", "reverse", 0};
2076 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 /* args 1-3 should match listsort in Objects/listobject.c */
2079 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
2080 kwlist, &seq, &keyfunc, &reverse))
2081 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 newlist = PySequence_List(seq);
2084 if (newlist == NULL)
2085 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002086
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002087 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (callable == NULL) {
2089 Py_DECREF(newlist);
2090 return NULL;
2091 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 newargs = PyTuple_GetSlice(args, 1, 4);
2094 if (newargs == NULL) {
2095 Py_DECREF(newlist);
2096 Py_DECREF(callable);
2097 return NULL;
2098 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 v = PyObject_Call(callable, newargs, kwds);
2101 Py_DECREF(newargs);
2102 Py_DECREF(callable);
2103 if (v == NULL) {
2104 Py_DECREF(newlist);
2105 return NULL;
2106 }
2107 Py_DECREF(v);
2108 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002109}
2110
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002111
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002112/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002113static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002114builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 PyObject *v = NULL;
2117 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2120 return NULL;
2121 if (v == NULL) {
2122 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002123 if (d == NULL)
2124 return NULL;
2125 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 }
2127 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002128 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 if (d == NULL) {
2130 PyErr_SetString(PyExc_TypeError,
2131 "vars() argument must have __dict__ attribute");
2132 return NULL;
2133 }
2134 }
2135 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002136}
2137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002138PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002139"vars([object]) -> dictionary\n\
2140\n\
2141Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002142With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002143
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002144
2145/*[clinic input]
2146sum as builtin_sum
2147
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002148 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002149 start: object(c_default="NULL") = 0
2150 /
2151
2152Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2153
2154When the iterable is empty, return the start value.
2155This function is intended specifically for use with numeric values and may
2156reject non-numeric types.
2157[clinic start generated code]*/
2158
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002159static PyObject *
2160builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002161/*[clinic end generated code: output=33655b248b21d581 input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002162{
2163 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002165
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002166 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (iter == NULL)
2168 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (result == NULL) {
2171 result = PyLong_FromLong(0);
2172 if (result == NULL) {
2173 Py_DECREF(iter);
2174 return NULL;
2175 }
2176 } else {
2177 /* reject string values for 'start' parameter */
2178 if (PyUnicode_Check(result)) {
2179 PyErr_SetString(PyExc_TypeError,
2180 "sum() can't sum strings [use ''.join(seq) instead]");
2181 Py_DECREF(iter);
2182 return NULL;
2183 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002184 if (PyBytes_Check(result)) {
2185 PyErr_SetString(PyExc_TypeError,
2186 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002187 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002188 return NULL;
2189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (PyByteArray_Check(result)) {
2191 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002192 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 Py_DECREF(iter);
2194 return NULL;
2195 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 Py_INCREF(result);
2197 }
Alex Martellia70b1912003-04-22 08:12:33 +00002198
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002199#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2201 Assumes all inputs are the same type. If the assumption fails, default
2202 to the more general routine.
2203 */
2204 if (PyLong_CheckExact(result)) {
2205 int overflow;
2206 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2207 /* If this already overflowed, don't even enter the loop. */
2208 if (overflow == 0) {
2209 Py_DECREF(result);
2210 result = NULL;
2211 }
2212 while(result == NULL) {
2213 item = PyIter_Next(iter);
2214 if (item == NULL) {
2215 Py_DECREF(iter);
2216 if (PyErr_Occurred())
2217 return NULL;
2218 return PyLong_FromLong(i_result);
2219 }
2220 if (PyLong_CheckExact(item)) {
2221 long b = PyLong_AsLongAndOverflow(item, &overflow);
2222 long x = i_result + b;
2223 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2224 i_result = x;
2225 Py_DECREF(item);
2226 continue;
2227 }
2228 }
2229 /* Either overflowed or is not an int. Restore real objects and process normally */
2230 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002231 if (result == NULL) {
2232 Py_DECREF(item);
2233 Py_DECREF(iter);
2234 return NULL;
2235 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 temp = PyNumber_Add(result, item);
2237 Py_DECREF(result);
2238 Py_DECREF(item);
2239 result = temp;
2240 if (result == NULL) {
2241 Py_DECREF(iter);
2242 return NULL;
2243 }
2244 }
2245 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (PyFloat_CheckExact(result)) {
2248 double f_result = PyFloat_AS_DOUBLE(result);
2249 Py_DECREF(result);
2250 result = NULL;
2251 while(result == NULL) {
2252 item = PyIter_Next(iter);
2253 if (item == NULL) {
2254 Py_DECREF(iter);
2255 if (PyErr_Occurred())
2256 return NULL;
2257 return PyFloat_FromDouble(f_result);
2258 }
2259 if (PyFloat_CheckExact(item)) {
2260 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2261 f_result += PyFloat_AS_DOUBLE(item);
2262 PyFPE_END_PROTECT(f_result)
2263 Py_DECREF(item);
2264 continue;
2265 }
2266 if (PyLong_CheckExact(item)) {
2267 long value;
2268 int overflow;
2269 value = PyLong_AsLongAndOverflow(item, &overflow);
2270 if (!overflow) {
2271 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2272 f_result += (double)value;
2273 PyFPE_END_PROTECT(f_result)
2274 Py_DECREF(item);
2275 continue;
2276 }
2277 }
2278 result = PyFloat_FromDouble(f_result);
2279 temp = PyNumber_Add(result, item);
2280 Py_DECREF(result);
2281 Py_DECREF(item);
2282 result = temp;
2283 if (result == NULL) {
2284 Py_DECREF(iter);
2285 return NULL;
2286 }
2287 }
2288 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002289#endif
2290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 for(;;) {
2292 item = PyIter_Next(iter);
2293 if (item == NULL) {
2294 /* error, or end-of-sequence */
2295 if (PyErr_Occurred()) {
2296 Py_DECREF(result);
2297 result = NULL;
2298 }
2299 break;
2300 }
2301 /* It's tempting to use PyNumber_InPlaceAdd instead of
2302 PyNumber_Add here, to avoid quadratic running time
2303 when doing 'sum(list_of_lists, [])'. However, this
2304 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 empty = []
2307 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 would change the value of empty. */
2310 temp = PyNumber_Add(result, item);
2311 Py_DECREF(result);
2312 Py_DECREF(item);
2313 result = temp;
2314 if (result == NULL)
2315 break;
2316 }
2317 Py_DECREF(iter);
2318 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002319}
2320
Alex Martellia70b1912003-04-22 08:12:33 +00002321
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002322/*[clinic input]
2323isinstance as builtin_isinstance
2324
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002325 obj: object
2326 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002327 /
2328
2329Return whether an object is an instance of a class or of a subclass thereof.
2330
2331A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2332check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2333or ...`` etc.
2334[clinic start generated code]*/
2335
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002336static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002337builtin_isinstance_impl(PyModuleDef *module, PyObject *obj,
2338 PyObject *class_or_tuple)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002339/*[clinic end generated code: output=f960b7c12dbbeda0 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002342
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002343 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (retval < 0)
2345 return NULL;
2346 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002347}
2348
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002349
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002350/*[clinic input]
2351issubclass as builtin_issubclass
2352
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002353 cls: object
2354 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002355 /
2356
2357Return whether 'cls' is a derived from another class or is the same class.
2358
2359A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2360check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2361or ...`` etc.
2362[clinic start generated code]*/
2363
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002364static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04002365builtin_issubclass_impl(PyModuleDef *module, PyObject *cls,
2366 PyObject *class_or_tuple)
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002367/*[clinic end generated code: output=8b012a151940bbf2 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002370
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002371 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 if (retval < 0)
2373 return NULL;
2374 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002375}
2376
2377
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002378typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyObject_HEAD
2380 Py_ssize_t tuplesize;
2381 PyObject *ittuple; /* tuple of iterators */
2382 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002383} zipobject;
2384
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002385static PyObject *
2386zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 zipobject *lz;
2389 Py_ssize_t i;
2390 PyObject *ittuple; /* tuple of iterators */
2391 PyObject *result;
2392 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2395 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* args must be a tuple */
2398 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* obtain iterators */
2401 ittuple = PyTuple_New(tuplesize);
2402 if (ittuple == NULL)
2403 return NULL;
2404 for (i=0; i < tuplesize; ++i) {
2405 PyObject *item = PyTuple_GET_ITEM(args, i);
2406 PyObject *it = PyObject_GetIter(item);
2407 if (it == NULL) {
2408 if (PyErr_ExceptionMatches(PyExc_TypeError))
2409 PyErr_Format(PyExc_TypeError,
2410 "zip argument #%zd must support iteration",
2411 i+1);
2412 Py_DECREF(ittuple);
2413 return NULL;
2414 }
2415 PyTuple_SET_ITEM(ittuple, i, it);
2416 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 /* create a result holder */
2419 result = PyTuple_New(tuplesize);
2420 if (result == NULL) {
2421 Py_DECREF(ittuple);
2422 return NULL;
2423 }
2424 for (i=0 ; i < tuplesize ; i++) {
2425 Py_INCREF(Py_None);
2426 PyTuple_SET_ITEM(result, i, Py_None);
2427 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* create zipobject structure */
2430 lz = (zipobject *)type->tp_alloc(type, 0);
2431 if (lz == NULL) {
2432 Py_DECREF(ittuple);
2433 Py_DECREF(result);
2434 return NULL;
2435 }
2436 lz->ittuple = ittuple;
2437 lz->tuplesize = tuplesize;
2438 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002441}
2442
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002443static void
2444zip_dealloc(zipobject *lz)
2445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 PyObject_GC_UnTrack(lz);
2447 Py_XDECREF(lz->ittuple);
2448 Py_XDECREF(lz->result);
2449 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002450}
2451
2452static int
2453zip_traverse(zipobject *lz, visitproc visit, void *arg)
2454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 Py_VISIT(lz->ittuple);
2456 Py_VISIT(lz->result);
2457 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002458}
2459
2460static PyObject *
2461zip_next(zipobject *lz)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 Py_ssize_t i;
2464 Py_ssize_t tuplesize = lz->tuplesize;
2465 PyObject *result = lz->result;
2466 PyObject *it;
2467 PyObject *item;
2468 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (tuplesize == 0)
2471 return NULL;
2472 if (Py_REFCNT(result) == 1) {
2473 Py_INCREF(result);
2474 for (i=0 ; i < tuplesize ; i++) {
2475 it = PyTuple_GET_ITEM(lz->ittuple, i);
2476 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002477 if (item == NULL) {
2478 Py_DECREF(result);
2479 return NULL;
2480 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 olditem = PyTuple_GET_ITEM(result, i);
2482 PyTuple_SET_ITEM(result, i, item);
2483 Py_DECREF(olditem);
2484 }
2485 } else {
2486 result = PyTuple_New(tuplesize);
2487 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002488 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 for (i=0 ; i < tuplesize ; i++) {
2490 it = PyTuple_GET_ITEM(lz->ittuple, i);
2491 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002492 if (item == NULL) {
2493 Py_DECREF(result);
2494 return NULL;
2495 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 PyTuple_SET_ITEM(result, i, item);
2497 }
2498 }
2499 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002500}
Barry Warsawbd599b52000-08-03 15:45:29 +00002501
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002502static PyObject *
2503zip_reduce(zipobject *lz)
2504{
2505 /* Just recreate the zip with the internal iterator tuple */
2506 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2507}
2508
2509static PyMethodDef zip_methods[] = {
2510 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2511 {NULL, NULL} /* sentinel */
2512};
2513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002514PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002515"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002516\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002517Return a zip object whose .__next__() method returns a tuple where\n\
2518the i-th element comes from the i-th iterable argument. The .__next__()\n\
2519method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002520is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002521
2522PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2524 "zip", /* tp_name */
2525 sizeof(zipobject), /* tp_basicsize */
2526 0, /* tp_itemsize */
2527 /* methods */
2528 (destructor)zip_dealloc, /* tp_dealloc */
2529 0, /* tp_print */
2530 0, /* tp_getattr */
2531 0, /* tp_setattr */
2532 0, /* tp_reserved */
2533 0, /* tp_repr */
2534 0, /* tp_as_number */
2535 0, /* tp_as_sequence */
2536 0, /* tp_as_mapping */
2537 0, /* tp_hash */
2538 0, /* tp_call */
2539 0, /* tp_str */
2540 PyObject_GenericGetAttr, /* tp_getattro */
2541 0, /* tp_setattro */
2542 0, /* tp_as_buffer */
2543 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2544 Py_TPFLAGS_BASETYPE, /* tp_flags */
2545 zip_doc, /* tp_doc */
2546 (traverseproc)zip_traverse, /* tp_traverse */
2547 0, /* tp_clear */
2548 0, /* tp_richcompare */
2549 0, /* tp_weaklistoffset */
2550 PyObject_SelfIter, /* tp_iter */
2551 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002552 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 0, /* tp_members */
2554 0, /* tp_getset */
2555 0, /* tp_base */
2556 0, /* tp_dict */
2557 0, /* tp_descr_get */
2558 0, /* tp_descr_set */
2559 0, /* tp_dictoffset */
2560 0, /* tp_init */
2561 PyType_GenericAlloc, /* tp_alloc */
2562 zip_new, /* tp_new */
2563 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002564};
Barry Warsawbd599b52000-08-03 15:45:29 +00002565
2566
Guido van Rossum79f25d91997-04-29 20:08:16 +00002567static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 {"__build_class__", (PyCFunction)builtin___build_class__,
2569 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2570 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002571 BUILTIN_ABS_METHODDEF
2572 BUILTIN_ALL_METHODDEF
2573 BUILTIN_ANY_METHODDEF
2574 BUILTIN_ASCII_METHODDEF
2575 BUILTIN_BIN_METHODDEF
2576 BUILTIN_CALLABLE_METHODDEF
2577 BUILTIN_CHR_METHODDEF
2578 BUILTIN_COMPILE_METHODDEF
2579 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002581 BUILTIN_DIVMOD_METHODDEF
2582 BUILTIN_EVAL_METHODDEF
2583 BUILTIN_EXEC_METHODDEF
2584 BUILTIN_FORMAT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002586 BUILTIN_GLOBALS_METHODDEF
2587 BUILTIN_HASATTR_METHODDEF
2588 BUILTIN_HASH_METHODDEF
2589 BUILTIN_HEX_METHODDEF
2590 BUILTIN_ID_METHODDEF
2591 BUILTIN_INPUT_METHODDEF
2592 BUILTIN_ISINSTANCE_METHODDEF
2593 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002595 BUILTIN_LEN_METHODDEF
2596 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2598 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2599 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002600 BUILTIN_OCT_METHODDEF
2601 BUILTIN_ORD_METHODDEF
2602 BUILTIN_POW_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002604 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002606 BUILTIN_SETATTR_METHODDEF
2607 BUILTIN_SORTED_METHODDEF
2608 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2610 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002611};
2612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002613PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002614"Built-in functions, exceptions, and other objects.\n\
2615\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002616Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002617
Martin v. Löwis1a214512008-06-11 05:26:20 +00002618static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 PyModuleDef_HEAD_INIT,
2620 "builtins",
2621 builtin_doc,
2622 -1, /* multiple "initialization" just copies the module dict. */
2623 builtin_methods,
2624 NULL,
2625 NULL,
2626 NULL,
2627 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002628};
2629
2630
Guido van Rossum25ce5661997-08-02 03:10:38 +00002631PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002632_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002635
2636 if (PyType_Ready(&PyFilter_Type) < 0 ||
2637 PyType_Ready(&PyMap_Type) < 0 ||
2638 PyType_Ready(&PyZip_Type) < 0)
2639 return NULL;
2640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 mod = PyModule_Create(&builtinsmodule);
2642 if (mod == NULL)
2643 return NULL;
2644 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002645
Tim Peters7571a0f2003-03-23 17:52:28 +00002646#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 /* "builtins" exposes a number of statically allocated objects
2648 * that, before this code was added in 2.3, never showed up in
2649 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2650 * result, programs leaking references to None and False (etc)
2651 * couldn't be diagnosed by examining sys.getobjects(0).
2652 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002653#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2654#else
2655#define ADD_TO_ALL(OBJECT) (void)0
2656#endif
2657
Tim Peters4b7625e2001-09-13 21:37:17 +00002658#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2660 return NULL; \
2661 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 SETBUILTIN("None", Py_None);
2664 SETBUILTIN("Ellipsis", Py_Ellipsis);
2665 SETBUILTIN("NotImplemented", Py_NotImplemented);
2666 SETBUILTIN("False", Py_False);
2667 SETBUILTIN("True", Py_True);
2668 SETBUILTIN("bool", &PyBool_Type);
2669 SETBUILTIN("memoryview", &PyMemoryView_Type);
2670 SETBUILTIN("bytearray", &PyByteArray_Type);
2671 SETBUILTIN("bytes", &PyBytes_Type);
2672 SETBUILTIN("classmethod", &PyClassMethod_Type);
2673 SETBUILTIN("complex", &PyComplex_Type);
2674 SETBUILTIN("dict", &PyDict_Type);
2675 SETBUILTIN("enumerate", &PyEnum_Type);
2676 SETBUILTIN("filter", &PyFilter_Type);
2677 SETBUILTIN("float", &PyFloat_Type);
2678 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2679 SETBUILTIN("property", &PyProperty_Type);
2680 SETBUILTIN("int", &PyLong_Type);
2681 SETBUILTIN("list", &PyList_Type);
2682 SETBUILTIN("map", &PyMap_Type);
2683 SETBUILTIN("object", &PyBaseObject_Type);
2684 SETBUILTIN("range", &PyRange_Type);
2685 SETBUILTIN("reversed", &PyReversed_Type);
2686 SETBUILTIN("set", &PySet_Type);
2687 SETBUILTIN("slice", &PySlice_Type);
2688 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2689 SETBUILTIN("str", &PyUnicode_Type);
2690 SETBUILTIN("super", &PySuper_Type);
2691 SETBUILTIN("tuple", &PyTuple_Type);
2692 SETBUILTIN("type", &PyType_Type);
2693 SETBUILTIN("zip", &PyZip_Type);
2694 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2695 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2696 Py_XDECREF(debug);
2697 return NULL;
2698 }
2699 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002702#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002703#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002704}