blob: 911e2ba79ef7304a23b613299e03ec6057c2ff00 [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*/
Steve Dowercc16be82016-09-08 10:35:16 -070024#if defined(__APPLE__)
25const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Steve Dowercc16be82016-09-08 10:35:16 -070027#elif defined(MS_WINDOWS)
28/* may be changed by initfsencoding(), but should never be free()d */
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000029const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000030int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020031#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000032const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000033int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000034#endif
Steve Dowercc16be82016-09-08 10:35:16 -070035const char *Py_FileSystemDefaultEncodeErrors = "surrogateescape";
Mark Hammondef8b6542001-05-13 08:04:26 +000036
Victor Stinnerbd303c12013-11-07 23:07:29 +010037_Py_IDENTIFIER(__builtins__);
38_Py_IDENTIFIER(__dict__);
39_Py_IDENTIFIER(__prepare__);
40_Py_IDENTIFIER(__round__);
41_Py_IDENTIFIER(encoding);
42_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020043_Py_IDENTIFIER(fileno);
44_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(metaclass);
46_Py_IDENTIFIER(sort);
47_Py_IDENTIFIER(stdin);
48_Py_IDENTIFIER(stdout);
49_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020050
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030051#include "clinic/bltinmodule.c.h"
52
Nick Coghlanf9e227e2014-08-17 14:01:19 +100053/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000054static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000055builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
56{
Nick Coghlan19d24672016-12-05 16:47:55 +100057 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns;
58 PyObject *cls = NULL, *cell = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020059 Py_ssize_t nargs;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010060 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 assert(args != NULL);
63 if (!PyTuple_Check(args)) {
64 PyErr_SetString(PyExc_TypeError,
65 "__build_class__: args is not a tuple");
66 return NULL;
67 }
68 nargs = PyTuple_GET_SIZE(args);
69 if (nargs < 2) {
70 PyErr_SetString(PyExc_TypeError,
71 "__build_class__: not enough arguments");
72 return NULL;
73 }
74 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050075 if (!PyFunction_Check(func)) {
76 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050077 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050078 return NULL;
79 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 name = PyTuple_GET_ITEM(args, 1);
81 if (!PyUnicode_Check(name)) {
82 PyErr_SetString(PyExc_TypeError,
83 "__build_class__: name is not a string");
84 return NULL;
85 }
86 bases = PyTuple_GetSlice(args, 2, nargs);
87 if (bases == NULL)
88 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 if (kwds == NULL) {
91 meta = NULL;
92 mkw = NULL;
93 }
94 else {
95 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
96 if (mkw == NULL) {
97 Py_DECREF(bases);
98 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000099 }
Victor Stinnerae9f1612013-11-06 22:46:51 +0100100 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 if (meta != NULL) {
102 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100103 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 Py_DECREF(meta);
105 Py_DECREF(mkw);
106 Py_DECREF(bases);
107 return NULL;
108 }
Nick Coghlande31b192011-10-23 22:04:16 +1000109 /* metaclass is explicitly given, check if it's indeed a class */
110 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 }
112 }
113 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000114 /* if there are no bases, use type: */
115 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000117 }
118 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 else {
120 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
121 meta = (PyObject *) (base0->ob_type);
122 }
123 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000124 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000126
Nick Coghlande31b192011-10-23 22:04:16 +1000127 if (isclass) {
128 /* meta is really a class, so check for a more derived
129 metaclass, or possible metaclass conflicts: */
130 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
131 bases);
132 if (winner == NULL) {
133 Py_DECREF(meta);
134 Py_XDECREF(mkw);
135 Py_DECREF(bases);
136 return NULL;
137 }
138 if (winner != meta) {
139 Py_DECREF(meta);
140 meta = winner;
141 Py_INCREF(meta);
142 }
143 }
144 /* else: meta is not a class, so we cannot do the metaclass
145 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200146 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (prep == NULL) {
148 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
149 PyErr_Clear();
Eric Snow4f29e752016-09-08 15:11:11 -0700150 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 }
152 else {
153 Py_DECREF(meta);
154 Py_XDECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
158 }
159 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200160 PyObject *pargs[2] = {name, bases};
161 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 Py_DECREF(prep);
163 }
164 if (ns == NULL) {
165 Py_DECREF(meta);
166 Py_XDECREF(mkw);
167 Py_DECREF(bases);
168 return NULL;
169 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000170 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500171 NULL, 0, NULL, 0, NULL, 0, NULL,
172 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000173 if (cell != NULL) {
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200174 PyObject *margs[3] = {name, bases, ns};
175 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000176 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
177 PyObject *cell_cls = PyCell_GET(cell);
178 if (cell_cls != cls) {
179 /* TODO: In 3.7, DeprecationWarning will become RuntimeError.
180 * At that point, cell_error won't be needed.
181 */
182 int cell_error;
183 if (cell_cls == NULL) {
184 const char *msg =
185 "__class__ not set defining %.200R as %.200R. "
186 "Was __classcell__ propagated to type.__new__?";
187 cell_error = PyErr_WarnFormat(
188 PyExc_DeprecationWarning, 1, msg, name, cls);
189 } else {
190 const char *msg =
191 "__class__ set to %.200R defining %.200R as %.200R";
192 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
193 cell_error = 1;
194 }
195 if (cell_error) {
196 Py_DECREF(cls);
197 cls = NULL;
198 goto error;
199 } else {
200 /* Fill in the cell, since type.__new__ didn't do it */
201 PyCell_Set(cell, cls);
202 }
203 }
204 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000206error:
207 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 Py_DECREF(ns);
209 Py_DECREF(meta);
210 Py_XDECREF(mkw);
211 Py_DECREF(bases);
212 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000213}
214
215PyDoc_STRVAR(build_class_doc,
216"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
217\n\
218Internal helper function used by the class statement.");
219
220static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
224 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400225 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400226 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000227
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400228 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 kwlist, &name, &globals, &locals, &fromlist, &level))
230 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400231 return PyImport_ImportModuleLevelObject(name, globals, locals,
232 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000233}
234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000235PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400236"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000237\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000238Import a module. Because this function is meant for use by the Python\n\
239interpreter and not for general use it is better to use\n\
240importlib.import_module() to programmatically import a module.\n\
241\n\
242The globals argument is only used to determine the context;\n\
243they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000244should be a list of names to emulate ``from name import ...'', or an\n\
245empty list to emulate ``import name''.\n\
246When importing a module from a package, note that __import__('A.B', ...)\n\
247returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000248fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400249absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000250is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000251
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000252
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000253/*[clinic input]
254abs as builtin_abs
255
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300256 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000257 /
258
259Return the absolute value of the argument.
260[clinic start generated code]*/
261
Guido van Rossum79f25d91997-04-29 20:08:16 +0000262static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300263builtin_abs(PyObject *module, PyObject *x)
264/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000265{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000266 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000267}
268
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000269/*[clinic input]
270all as builtin_all
271
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300272 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000273 /
274
275Return True if bool(x) is True for all values x in the iterable.
276
277If the iterable is empty, return True.
278[clinic start generated code]*/
279
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300281builtin_all(PyObject *module, PyObject *iterable)
282/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 PyObject *it, *item;
285 PyObject *(*iternext)(PyObject *);
286 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000287
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000288 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 if (it == NULL)
290 return NULL;
291 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 for (;;) {
294 item = iternext(it);
295 if (item == NULL)
296 break;
297 cmp = PyObject_IsTrue(item);
298 Py_DECREF(item);
299 if (cmp < 0) {
300 Py_DECREF(it);
301 return NULL;
302 }
303 if (cmp == 0) {
304 Py_DECREF(it);
305 Py_RETURN_FALSE;
306 }
307 }
308 Py_DECREF(it);
309 if (PyErr_Occurred()) {
310 if (PyErr_ExceptionMatches(PyExc_StopIteration))
311 PyErr_Clear();
312 else
313 return NULL;
314 }
315 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000316}
317
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000318/*[clinic input]
319any as builtin_any
320
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300321 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000322 /
323
324Return True if bool(x) is True for any x in the iterable.
325
326If the iterable is empty, return False.
327[clinic start generated code]*/
328
Raymond Hettinger96229b12005-03-11 06:49:40 +0000329static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300330builtin_any(PyObject *module, PyObject *iterable)
331/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *it, *item;
334 PyObject *(*iternext)(PyObject *);
335 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000336
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000337 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (it == NULL)
339 return NULL;
340 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 for (;;) {
343 item = iternext(it);
344 if (item == NULL)
345 break;
346 cmp = PyObject_IsTrue(item);
347 Py_DECREF(item);
348 if (cmp < 0) {
349 Py_DECREF(it);
350 return NULL;
351 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400352 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 Py_DECREF(it);
354 Py_RETURN_TRUE;
355 }
356 }
357 Py_DECREF(it);
358 if (PyErr_Occurred()) {
359 if (PyErr_ExceptionMatches(PyExc_StopIteration))
360 PyErr_Clear();
361 else
362 return NULL;
363 }
364 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000365}
366
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000367/*[clinic input]
368ascii as builtin_ascii
369
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300370 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000371 /
372
373Return an ASCII-only representation of an object.
374
375As repr(), return a string containing a printable representation of an
376object, but escape the non-ASCII characters in the string returned by
377repr() using \\x, \\u or \\U escapes. This generates a string similar
378to that returned by repr() in Python 2.
379[clinic start generated code]*/
380
Georg Brandl559e5d72008-06-11 18:37:52 +0000381static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300382builtin_ascii(PyObject *module, PyObject *obj)
383/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000384{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000385 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000386}
387
Georg Brandl559e5d72008-06-11 18:37:52 +0000388
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000389/*[clinic input]
390bin as builtin_bin
391
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300392 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000393 /
394
395Return the binary representation of an integer.
396
397 >>> bin(2796202)
398 '0b1010101010101010101010'
399[clinic start generated code]*/
400
Guido van Rossum79f25d91997-04-29 20:08:16 +0000401static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300402builtin_bin(PyObject *module, PyObject *number)
403/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000404{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000405 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000406}
407
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000408
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000409/*[clinic input]
410callable as builtin_callable
411
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300412 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000413 /
414
415Return whether the object is callable (i.e., some kind of function).
416
417Note that classes are callable, as are instances of classes with a
418__call__() method.
419[clinic start generated code]*/
420
Antoine Pitroue71362d2010-11-27 22:00:11 +0000421static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300422builtin_callable(PyObject *module, PyObject *obj)
423/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000424{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000425 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000426}
427
Antoine Pitroue71362d2010-11-27 22:00:11 +0000428
Raymond Hettinger17301e92008-03-13 00:19:26 +0000429typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyObject_HEAD
431 PyObject *func;
432 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000433} filterobject;
434
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000435static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000436filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 PyObject *func, *seq;
439 PyObject *it;
440 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
443 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
446 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 /* Get iterator. */
449 it = PyObject_GetIter(seq);
450 if (it == NULL)
451 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* create filterobject structure */
454 lz = (filterobject *)type->tp_alloc(type, 0);
455 if (lz == NULL) {
456 Py_DECREF(it);
457 return NULL;
458 }
459 Py_INCREF(func);
460 lz->func = func;
461 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000464}
465
466static void
467filter_dealloc(filterobject *lz)
468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 PyObject_GC_UnTrack(lz);
470 Py_XDECREF(lz->func);
471 Py_XDECREF(lz->it);
472 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000473}
474
475static int
476filter_traverse(filterobject *lz, visitproc visit, void *arg)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 Py_VISIT(lz->it);
479 Py_VISIT(lz->func);
480 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000481}
482
483static PyObject *
484filter_next(filterobject *lz)
485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyObject *item;
487 PyObject *it = lz->it;
488 long ok;
489 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400490 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 iternext = *Py_TYPE(it)->tp_iternext;
493 for (;;) {
494 item = iternext(it);
495 if (item == NULL)
496 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000497
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400498 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 ok = PyObject_IsTrue(item);
500 } else {
501 PyObject *good;
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400502 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 if (good == NULL) {
504 Py_DECREF(item);
505 return NULL;
506 }
507 ok = PyObject_IsTrue(good);
508 Py_DECREF(good);
509 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200510 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return item;
512 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200513 if (ok < 0)
514 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000516}
517
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000518static PyObject *
519filter_reduce(filterobject *lz)
520{
521 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
522}
523
524PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
525
526static PyMethodDef filter_methods[] = {
527 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
528 {NULL, NULL} /* sentinel */
529};
530
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000531PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000532"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000533\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000534Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000535is true. If function is None, return the items that are true.");
536
537PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 PyVarObject_HEAD_INIT(&PyType_Type, 0)
539 "filter", /* tp_name */
540 sizeof(filterobject), /* tp_basicsize */
541 0, /* tp_itemsize */
542 /* methods */
543 (destructor)filter_dealloc, /* tp_dealloc */
544 0, /* tp_print */
545 0, /* tp_getattr */
546 0, /* tp_setattr */
547 0, /* tp_reserved */
548 0, /* tp_repr */
549 0, /* tp_as_number */
550 0, /* tp_as_sequence */
551 0, /* tp_as_mapping */
552 0, /* tp_hash */
553 0, /* tp_call */
554 0, /* tp_str */
555 PyObject_GenericGetAttr, /* tp_getattro */
556 0, /* tp_setattro */
557 0, /* tp_as_buffer */
558 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
559 Py_TPFLAGS_BASETYPE, /* tp_flags */
560 filter_doc, /* tp_doc */
561 (traverseproc)filter_traverse, /* tp_traverse */
562 0, /* tp_clear */
563 0, /* tp_richcompare */
564 0, /* tp_weaklistoffset */
565 PyObject_SelfIter, /* tp_iter */
566 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000567 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 0, /* tp_members */
569 0, /* tp_getset */
570 0, /* tp_base */
571 0, /* tp_dict */
572 0, /* tp_descr_get */
573 0, /* tp_descr_set */
574 0, /* tp_dictoffset */
575 0, /* tp_init */
576 PyType_GenericAlloc, /* tp_alloc */
577 filter_new, /* tp_new */
578 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000579};
580
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000581
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000582/*[clinic input]
583format as builtin_format
584
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300585 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000586 format_spec: unicode(c_default="NULL") = ''
587 /
588
589Return value.__format__(format_spec)
590
Serhiy Storchakac67838d2017-09-11 09:26:15 +0300591format_spec defaults to the empty string.
592See the Format Specification Mini-Language section of help('FORMATTING') for
593details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000594[clinic start generated code]*/
595
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000596static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300597builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Serhiy Storchakac67838d2017-09-11 09:26:15 +0300598/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000599{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000600 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000601}
602
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000603/*[clinic input]
604chr as builtin_chr
605
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300606 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000607 /
608
609Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
610[clinic start generated code]*/
611
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000612static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300613builtin_chr_impl(PyObject *module, int i)
614/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000615{
616 return PyUnicode_FromOrdinal(i);
617}
Guido van Rossum09095f32000-03-10 23:00:52 +0000618
619
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200620static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000621source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000622{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200623 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000625 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000626
Martin Pantereeb896c2015-11-07 02:32:21 +0000627 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (PyUnicode_Check(cmd)) {
629 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200630 str = PyUnicode_AsUTF8AndSize(cmd, &size);
631 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return NULL;
633 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000634 else if (PyBytes_Check(cmd)) {
635 str = PyBytes_AS_STRING(cmd);
636 size = PyBytes_GET_SIZE(cmd);
637 }
638 else if (PyByteArray_Check(cmd)) {
639 str = PyByteArray_AS_STRING(cmd);
640 size = PyByteArray_GET_SIZE(cmd);
641 }
642 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
643 /* Copy to NUL-terminated buffer. */
644 *cmd_copy = PyBytes_FromStringAndSize(
645 (const char *)view.buf, view.len);
646 PyBuffer_Release(&view);
647 if (*cmd_copy == NULL) {
648 return NULL;
649 }
650 str = PyBytes_AS_STRING(*cmd_copy);
651 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200652 }
653 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyErr_Format(PyExc_TypeError,
655 "%s() arg 1 must be a %s object",
656 funcname, what);
657 return NULL;
658 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200659
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200660 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300661 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000663 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 return NULL;
665 }
666 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000667}
668
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000669/*[clinic input]
670compile as builtin_compile
671
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300672 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000673 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300674 mode: str
675 flags: int = 0
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300676 dont_inherit: int(c_default="0") = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300677 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000678
679Compile source into a code object that can be executed by exec() or eval().
680
681The source code may represent a Python module, statement or expression.
682The filename will be used for run-time error messages.
683The mode must be 'exec' to compile a module, 'single' to compile a
684single (interactive) statement, or 'eval' to compile an expression.
685The flags argument, if present, controls which future statements influence
686the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300687The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000688the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300689compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000690in addition to any features explicitly specified.
691[clinic start generated code]*/
692
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000693static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300694builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
695 const char *mode, int flags, int dont_inherit,
696 int optimize)
697/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000698{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000699 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200700 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000701 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 int is_ast;
703 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000705 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000706
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000707 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000708
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000709 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
711 {
712 PyErr_SetString(PyExc_ValueError,
713 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000714 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 }
716 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000717
Georg Brandl8334fd92010-12-04 10:26:46 +0000718 if (optimize < -1 || optimize > 2) {
719 PyErr_SetString(PyExc_ValueError,
720 "compile(): invalid optimize value");
721 goto error;
722 }
723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (!dont_inherit) {
725 PyEval_MergeCompilerFlags(&cf);
726 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000727
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000728 if (strcmp(mode, "exec") == 0)
729 compile_mode = 0;
730 else if (strcmp(mode, "eval") == 0)
731 compile_mode = 1;
732 else if (strcmp(mode, "single") == 0)
733 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 else {
735 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000736 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000737 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000739
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000740 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000742 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000744 if (flags & PyCF_ONLY_AST) {
745 Py_INCREF(source);
746 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 }
748 else {
749 PyArena *arena;
750 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200753 if (arena == NULL)
754 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000755 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (mod == NULL) {
757 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000758 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500760 if (!PyAST_Validate(mod)) {
761 PyArena_Free(arena);
762 goto error;
763 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200764 result = (PyObject*)PyAST_CompileObject(mod, filename,
765 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyArena_Free(arena);
767 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000768 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000770
Martin Panter61d6e4a2015-11-07 02:56:11 +0000771 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000773 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000774
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000775 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000776 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000777 goto finally;
778
779error:
780 result = NULL;
781finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200782 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000783 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000784}
785
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000786/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000787static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000788builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
793 return NULL;
794 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000795}
796
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000797PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000798"dir([object]) -> list of strings\n"
799"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000800"If called without an argument, return the names in the current scope.\n"
801"Else, return an alphabetized list of names comprising (some of) the attributes\n"
802"of the given object, and of attributes reachable from it.\n"
803"If the object supplies a method named __dir__, it will be used; otherwise\n"
804"the default dir() logic is used and returns:\n"
805" for a module object: the module's attributes.\n"
806" for a class object: its attributes, and recursively the attributes\n"
807" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000808" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000809" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000810
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000811/*[clinic input]
812divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000813
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300814 x: object
815 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000816 /
817
Zachary Ware7f227d92016-04-28 14:39:50 -0500818Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000819[clinic start generated code]*/
820
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000821static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300822builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
823/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000824{
825 return PyNumber_Divmod(x, y);
826}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000827
828
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000829/*[clinic input]
830eval as builtin_eval
831
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300832 source: object
833 globals: object = None
834 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000835 /
836
837Evaluate the given source in the context of globals and locals.
838
839The source may be a string representing a Python expression
840or a code object as returned by compile().
841The globals must be a dictionary and locals can be any mapping,
842defaulting to the current globals and locals.
843If only globals is given, locals defaults to it.
844[clinic start generated code]*/
845
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000846static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300847builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400848 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300849/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000850{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000851 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200852 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (locals != Py_None && !PyMapping_Check(locals)) {
856 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
857 return NULL;
858 }
859 if (globals != Py_None && !PyDict_Check(globals)) {
860 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
861 "globals must be a real dict; try eval(expr, {}, mapping)"
862 : "globals must be a dict");
863 return NULL;
864 }
865 if (globals == Py_None) {
866 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100867 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100869 if (locals == NULL)
870 return NULL;
871 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 }
873 else if (locals == Py_None)
874 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 if (globals == NULL || locals == NULL) {
877 PyErr_SetString(PyExc_TypeError,
878 "eval must be given globals and locals "
879 "when called without a frame");
880 return NULL;
881 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000882
Victor Stinnerb44562b2013-11-06 19:03:11 +0100883 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
884 if (_PyDict_SetItemId(globals, &PyId___builtins__,
885 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 return NULL;
887 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000888
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000889 if (PyCode_Check(source)) {
890 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 PyErr_SetString(PyExc_TypeError,
892 "code object passed to eval() may not contain free variables");
893 return NULL;
894 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000895 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000899 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 if (str == NULL)
901 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 while (*str == ' ' || *str == '\t')
904 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 (void)PyEval_MergeCompilerFlags(&cf);
907 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000908 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000910}
911
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000912/*[clinic input]
913exec as builtin_exec
914
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300915 source: object
916 globals: object = None
917 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000918 /
919
920Execute the given source in the context of globals and locals.
921
922The source may be a string representing one or more Python statements
923or a code object as returned by compile().
924The globals must be a dictionary and locals can be any mapping,
925defaulting to the current globals and locals.
926If only globals is given, locals defaults to it.
927[clinic start generated code]*/
928
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000929static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300930builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400931 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300932/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (globals == Py_None) {
937 globals = PyEval_GetGlobals();
938 if (locals == Py_None) {
939 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100940 if (locals == NULL)
941 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 }
943 if (!globals || !locals) {
944 PyErr_SetString(PyExc_SystemError,
945 "globals and locals cannot be NULL");
946 return NULL;
947 }
948 }
949 else if (locals == Py_None)
950 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000953 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 globals->ob_type->tp_name);
955 return NULL;
956 }
957 if (!PyMapping_Check(locals)) {
958 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000959 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 locals->ob_type->tp_name);
961 return NULL;
962 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100963 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
964 if (_PyDict_SetItemId(globals, &PyId___builtins__,
965 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 return NULL;
967 }
968
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000969 if (PyCode_Check(source)) {
970 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 PyErr_SetString(PyExc_TypeError,
972 "code object passed to exec() may not "
973 "contain free variables");
974 return NULL;
975 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000976 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 }
978 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000979 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200980 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 PyCompilerFlags cf;
982 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000983 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000984 "string, bytes or code", &cf,
985 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (str == NULL)
987 return NULL;
988 if (PyEval_MergeCompilerFlags(&cf))
989 v = PyRun_StringFlags(str, Py_file_input, globals,
990 locals, &cf);
991 else
992 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000993 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 }
995 if (v == NULL)
996 return NULL;
997 Py_DECREF(v);
998 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000999}
1000
Georg Brandl7cae87c2006-09-06 06:51:57 +00001001
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001002/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001003static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001004builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 PyObject *v, *result, *dflt = NULL;
1007 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
1010 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (!PyUnicode_Check(name)) {
1013 PyErr_SetString(PyExc_TypeError,
1014 "getattr(): attribute name must be string");
1015 return NULL;
1016 }
1017 result = PyObject_GetAttr(v, name);
1018 if (result == NULL && dflt != NULL &&
1019 PyErr_ExceptionMatches(PyExc_AttributeError))
1020 {
1021 PyErr_Clear();
1022 Py_INCREF(dflt);
1023 result = dflt;
1024 }
1025 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001026}
1027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001028PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001029"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001030\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001031Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1032When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001033exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001034
1035
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001036/*[clinic input]
1037globals as builtin_globals
1038
1039Return the dictionary containing the current scope's global variables.
1040
1041NOTE: Updates to this dictionary *will* affect name lookups in the current
1042global scope and vice-versa.
1043[clinic start generated code]*/
1044
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001045static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001046builtin_globals_impl(PyObject *module)
1047/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 d = PyEval_GetGlobals();
1052 Py_XINCREF(d);
1053 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001054}
1055
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001056
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001057/*[clinic input]
1058hasattr as builtin_hasattr
1059
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001060 obj: object
1061 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001062 /
1063
1064Return whether the object has an attribute with the given name.
1065
1066This is done by calling getattr(obj, name) and catching AttributeError.
1067[clinic start generated code]*/
1068
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001069static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001070builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1071/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001072{
1073 PyObject *v;
1074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (!PyUnicode_Check(name)) {
1076 PyErr_SetString(PyExc_TypeError,
1077 "hasattr(): attribute name must be string");
1078 return NULL;
1079 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001080 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001082 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001084 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001086 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 }
1088 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001089 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001090}
1091
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001092
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001093/* AC: gdb's integration with CPython relies on builtin_id having
1094 * the *exact* parameter names of "self" and "v", so we ensure we
1095 * preserve those name rather than using the AC defaults.
1096 */
1097/*[clinic input]
1098id as builtin_id
1099
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001100 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001101 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001102 /
1103
1104Return the identity of an object.
1105
1106This is guaranteed to be unique among simultaneously existing objects.
1107(CPython uses the object's memory address.)
1108[clinic start generated code]*/
1109
Guido van Rossum79f25d91997-04-29 20:08:16 +00001110static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001111builtin_id(PyModuleDef *self, PyObject *v)
1112/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001115}
1116
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001117
Raymond Hettingera6c60372008-03-13 01:26:19 +00001118/* map object ************************************************************/
1119
1120typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 PyObject_HEAD
1122 PyObject *iters;
1123 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001124} mapobject;
1125
Guido van Rossum79f25d91997-04-29 20:08:16 +00001126static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001127map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 PyObject *it, *iters, *func;
1130 mapobject *lz;
1131 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1134 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 numargs = PyTuple_Size(args);
1137 if (numargs < 2) {
1138 PyErr_SetString(PyExc_TypeError,
1139 "map() must have at least two arguments.");
1140 return NULL;
1141 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 iters = PyTuple_New(numargs-1);
1144 if (iters == NULL)
1145 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 for (i=1 ; i<numargs ; i++) {
1148 /* Get iterator. */
1149 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1150 if (it == NULL) {
1151 Py_DECREF(iters);
1152 return NULL;
1153 }
1154 PyTuple_SET_ITEM(iters, i-1, it);
1155 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 /* create mapobject structure */
1158 lz = (mapobject *)type->tp_alloc(type, 0);
1159 if (lz == NULL) {
1160 Py_DECREF(iters);
1161 return NULL;
1162 }
1163 lz->iters = iters;
1164 func = PyTuple_GET_ITEM(args, 0);
1165 Py_INCREF(func);
1166 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001169}
1170
1171static void
1172map_dealloc(mapobject *lz)
1173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 PyObject_GC_UnTrack(lz);
1175 Py_XDECREF(lz->iters);
1176 Py_XDECREF(lz->func);
1177 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001178}
1179
1180static int
1181map_traverse(mapobject *lz, visitproc visit, void *arg)
1182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_VISIT(lz->iters);
1184 Py_VISIT(lz->func);
1185 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001186}
1187
1188static PyObject *
1189map_next(mapobject *lz)
1190{
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001191 PyObject *small_stack[5];
1192 PyObject **stack;
1193 Py_ssize_t niters, nargs, i;
1194 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001195
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001196 niters = PyTuple_GET_SIZE(lz->iters);
1197 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1198 stack = small_stack;
1199 }
1200 else {
1201 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1202 if (stack == NULL) {
1203 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return NULL;
1205 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001207
1208 nargs = 0;
1209 for (i=0; i < niters; i++) {
1210 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1211 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1212 if (val == NULL) {
1213 goto exit;
1214 }
1215 stack[i] = val;
1216 nargs++;
1217 }
1218
1219 result = _PyObject_FastCall(lz->func, stack, nargs);
1220
1221exit:
1222 for (i=0; i < nargs; i++) {
1223 Py_DECREF(stack[i]);
1224 }
1225 if (stack != small_stack) {
1226 PyMem_Free(stack);
1227 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001229}
1230
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001231static PyObject *
1232map_reduce(mapobject *lz)
1233{
1234 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1235 PyObject *args = PyTuple_New(numargs+1);
1236 Py_ssize_t i;
1237 if (args == NULL)
1238 return NULL;
1239 Py_INCREF(lz->func);
1240 PyTuple_SET_ITEM(args, 0, lz->func);
1241 for (i = 0; i<numargs; i++){
1242 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1243 Py_INCREF(it);
1244 PyTuple_SET_ITEM(args, i+1, it);
1245 }
1246
1247 return Py_BuildValue("ON", Py_TYPE(lz), args);
1248}
1249
1250static PyMethodDef map_methods[] = {
1251 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1252 {NULL, NULL} /* sentinel */
1253};
1254
1255
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001256PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001257"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001258\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001259Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001261
Raymond Hettingera6c60372008-03-13 01:26:19 +00001262PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1264 "map", /* tp_name */
1265 sizeof(mapobject), /* tp_basicsize */
1266 0, /* tp_itemsize */
1267 /* methods */
1268 (destructor)map_dealloc, /* tp_dealloc */
1269 0, /* tp_print */
1270 0, /* tp_getattr */
1271 0, /* tp_setattr */
1272 0, /* tp_reserved */
1273 0, /* tp_repr */
1274 0, /* tp_as_number */
1275 0, /* tp_as_sequence */
1276 0, /* tp_as_mapping */
1277 0, /* tp_hash */
1278 0, /* tp_call */
1279 0, /* tp_str */
1280 PyObject_GenericGetAttr, /* tp_getattro */
1281 0, /* tp_setattro */
1282 0, /* tp_as_buffer */
1283 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1284 Py_TPFLAGS_BASETYPE, /* tp_flags */
1285 map_doc, /* tp_doc */
1286 (traverseproc)map_traverse, /* tp_traverse */
1287 0, /* tp_clear */
1288 0, /* tp_richcompare */
1289 0, /* tp_weaklistoffset */
1290 PyObject_SelfIter, /* tp_iter */
1291 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001292 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 0, /* tp_members */
1294 0, /* tp_getset */
1295 0, /* tp_base */
1296 0, /* tp_dict */
1297 0, /* tp_descr_get */
1298 0, /* tp_descr_set */
1299 0, /* tp_dictoffset */
1300 0, /* tp_init */
1301 PyType_GenericAlloc, /* tp_alloc */
1302 map_new, /* tp_new */
1303 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001304};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001305
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001306
1307/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001308static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001309builtin_next(PyObject *self, PyObject *args)
1310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 PyObject *it, *res;
1312 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1315 return NULL;
1316 if (!PyIter_Check(it)) {
1317 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001318 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 it->ob_type->tp_name);
1320 return NULL;
1321 }
1322
1323 res = (*it->ob_type->tp_iternext)(it);
1324 if (res != NULL) {
1325 return res;
1326 } else if (def != NULL) {
1327 if (PyErr_Occurred()) {
1328 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1329 return NULL;
1330 PyErr_Clear();
1331 }
1332 Py_INCREF(def);
1333 return def;
1334 } else if (PyErr_Occurred()) {
1335 return NULL;
1336 } else {
1337 PyErr_SetNone(PyExc_StopIteration);
1338 return NULL;
1339 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001340}
1341
1342PyDoc_STRVAR(next_doc,
1343"next(iterator[, default])\n\
1344\n\
1345Return the next item from the iterator. If default is given and the iterator\n\
1346is exhausted, it is returned instead of raising StopIteration.");
1347
1348
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001349/*[clinic input]
1350setattr as builtin_setattr
1351
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001352 obj: object
1353 name: object
1354 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001355 /
1356
1357Sets the named attribute on the given object to the specified value.
1358
1359setattr(x, 'y', v) is equivalent to ``x.y = v''
1360[clinic start generated code]*/
1361
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001362static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001363builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001364 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001365/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001366{
1367 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 return NULL;
1369 Py_INCREF(Py_None);
1370 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001371}
1372
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001373
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001374/*[clinic input]
1375delattr as builtin_delattr
1376
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001377 obj: object
1378 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001379 /
1380
1381Deletes the named attribute from the given object.
1382
1383delattr(x, 'y') is equivalent to ``del x.y''
1384[clinic start generated code]*/
1385
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001386static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001387builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1388/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001389{
1390 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 return NULL;
1392 Py_INCREF(Py_None);
1393 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001394}
1395
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001396
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001397/*[clinic input]
1398hash as builtin_hash
1399
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001400 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001401 /
1402
1403Return the hash value for the given object.
1404
1405Two objects that compare equal must also have the same hash value, but the
1406reverse is not necessarily true.
1407[clinic start generated code]*/
1408
Guido van Rossum79f25d91997-04-29 20:08:16 +00001409static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001410builtin_hash(PyObject *module, PyObject *obj)
1411/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001412{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001413 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001414
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001415 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (x == -1)
1417 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001418 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001419}
1420
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001421
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001422/*[clinic input]
1423hex as builtin_hex
1424
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001425 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001426 /
1427
1428Return the hexadecimal representation of an integer.
1429
1430 >>> hex(12648430)
1431 '0xc0ffee'
1432[clinic start generated code]*/
1433
Guido van Rossum79f25d91997-04-29 20:08:16 +00001434static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001435builtin_hex(PyObject *module, PyObject *number)
1436/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001437{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001438 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001439}
1440
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001441
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001442/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001443static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001444builtin_iter(PyObject *self, PyObject *args)
1445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1449 return NULL;
1450 if (w == NULL)
1451 return PyObject_GetIter(v);
1452 if (!PyCallable_Check(v)) {
1453 PyErr_SetString(PyExc_TypeError,
1454 "iter(v, w): v must be callable");
1455 return NULL;
1456 }
1457 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001458}
1459
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001460PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001461"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001462iter(callable, sentinel) -> iterator\n\
1463\n\
1464Get an iterator from an object. In the first form, the argument must\n\
1465supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001466In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001467
1468
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001469/*[clinic input]
1470len as builtin_len
1471
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001472 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001473 /
1474
1475Return the number of items in a container.
1476[clinic start generated code]*/
1477
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001478static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001479builtin_len(PyObject *module, PyObject *obj)
1480/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001483
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001484 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (res < 0 && PyErr_Occurred())
1486 return NULL;
1487 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001488}
1489
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001490
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001491/*[clinic input]
1492locals as builtin_locals
1493
1494Return a dictionary containing the current scope's local variables.
1495
1496NOTE: Whether or not updates to this dictionary will affect name lookups in
1497the local scope and vice-versa is *implementation dependent* and not
1498covered by any backwards compatibility guarantees.
1499[clinic start generated code]*/
1500
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001501static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001502builtin_locals_impl(PyObject *module)
1503/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 d = PyEval_GetLocals();
1508 Py_XINCREF(d);
1509 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001510}
1511
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001512
Guido van Rossum79f25d91997-04-29 20:08:16 +00001513static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001514min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001517 PyObject *emptytuple, *defaultval = NULL;
1518 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001520 const int positional = PyTuple_Size(args) > 1;
1521 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001522
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001523 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001525 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001527
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001528 emptytuple = PyTuple_New(0);
1529 if (emptytuple == NULL)
1530 return NULL;
1531 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1532 &keyfunc, &defaultval);
1533 Py_DECREF(emptytuple);
1534 if (!ret)
1535 return NULL;
1536
1537 if (positional && defaultval != NULL) {
1538 PyErr_Format(PyExc_TypeError,
1539 "Cannot specify a default for %s() with multiple "
1540 "positional arguments", name);
1541 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 it = PyObject_GetIter(v);
1545 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 return NULL;
1547 }
Tim Petersc3074532001-05-03 07:00:32 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 maxitem = NULL; /* the result */
1550 maxval = NULL; /* the value associated with the result */
1551 while (( item = PyIter_Next(it) )) {
1552 /* get the value from the key function */
1553 if (keyfunc != NULL) {
1554 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1555 if (val == NULL)
1556 goto Fail_it_item;
1557 }
1558 /* no key function; the value is the item */
1559 else {
1560 val = item;
1561 Py_INCREF(val);
1562 }
Tim Petersc3074532001-05-03 07:00:32 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 /* maximum value and item are unset; set them */
1565 if (maxval == NULL) {
1566 maxitem = item;
1567 maxval = val;
1568 }
1569 /* maximum value and item are set; update them as necessary */
1570 else {
1571 int cmp = PyObject_RichCompareBool(val, maxval, op);
1572 if (cmp < 0)
1573 goto Fail_it_item_and_val;
1574 else if (cmp > 0) {
1575 Py_DECREF(maxval);
1576 Py_DECREF(maxitem);
1577 maxval = val;
1578 maxitem = item;
1579 }
1580 else {
1581 Py_DECREF(item);
1582 Py_DECREF(val);
1583 }
1584 }
1585 }
1586 if (PyErr_Occurred())
1587 goto Fail_it;
1588 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001590 if (defaultval != NULL) {
1591 Py_INCREF(defaultval);
1592 maxitem = defaultval;
1593 } else {
1594 PyErr_Format(PyExc_ValueError,
1595 "%s() arg is an empty sequence", name);
1596 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 }
1598 else
1599 Py_DECREF(maxval);
1600 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001602
1603Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001605Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001607Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 Py_XDECREF(maxval);
1609 Py_XDECREF(maxitem);
1610 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001612}
1613
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001614/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001615static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001616builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001619}
1620
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001621PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001622"min(iterable, *[, default=obj, key=func]) -> value\n\
1623min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001624\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001625With a single iterable argument, return its smallest item. The\n\
1626default keyword-only argument specifies an object to return if\n\
1627the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001628With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001629
1630
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001631/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001632static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001633builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001636}
1637
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001638PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001639"max(iterable, *[, default=obj, key=func]) -> value\n\
1640max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001641\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001642With a single iterable argument, return its biggest item. The\n\
1643default keyword-only argument specifies an object to return if\n\
1644the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001645With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001646
1647
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001648/*[clinic input]
1649oct as builtin_oct
1650
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001651 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001652 /
1653
1654Return the octal representation of an integer.
1655
1656 >>> oct(342391)
1657 '0o1234567'
1658[clinic start generated code]*/
1659
Guido van Rossum79f25d91997-04-29 20:08:16 +00001660static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001661builtin_oct(PyObject *module, PyObject *number)
1662/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001663{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001664 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001665}
1666
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001667
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001668/*[clinic input]
1669ord as builtin_ord
1670
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001671 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001672 /
1673
1674Return the Unicode code point for a one-character string.
1675[clinic start generated code]*/
1676
Guido van Rossum79f25d91997-04-29 20:08:16 +00001677static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001678builtin_ord(PyObject *module, PyObject *c)
1679/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 long ord;
1682 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001683
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001684 if (PyBytes_Check(c)) {
1685 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001687 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 return PyLong_FromLong(ord);
1689 }
1690 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001691 else if (PyUnicode_Check(c)) {
1692 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001693 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001694 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001696 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 return PyLong_FromLong(ord);
1698 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001700 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001702 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001704 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 return PyLong_FromLong(ord);
1706 }
1707 }
1708 else {
1709 PyErr_Format(PyExc_TypeError,
1710 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001711 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 return NULL;
1713 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 PyErr_Format(PyExc_TypeError,
1716 "ord() expected a character, "
1717 "but string of length %zd found",
1718 size);
1719 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001720}
1721
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001722
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001723/*[clinic input]
1724pow as builtin_pow
1725
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001726 x: object
1727 y: object
1728 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001729 /
1730
1731Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1732
1733Some types, such as ints, are able to use a more efficient algorithm when
1734invoked using the three argument form.
1735[clinic start generated code]*/
1736
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001737static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001738builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1739/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001740{
1741 return PyNumber_Power(x, y, z);
1742}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001743
1744
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001745/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001746static PyObject *
1747builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1748{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001749 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001751 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001753
Benjamin Peterson00102562012-01-11 21:00:16 -05001754 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001755 return NULL;
1756 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1757 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 return NULL;
1759 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001760 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001761 if (file == NULL) {
1762 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1763 return NULL;
1764 }
1765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 /* sys.stdout may be None when FILE* stdout isn't connected */
1767 if (file == Py_None)
1768 Py_RETURN_NONE;
1769 }
Guido van Rossum34343512006-11-30 22:13:52 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (sep == Py_None) {
1772 sep = NULL;
1773 }
1774 else if (sep && !PyUnicode_Check(sep)) {
1775 PyErr_Format(PyExc_TypeError,
1776 "sep must be None or a string, not %.200s",
1777 sep->ob_type->tp_name);
1778 return NULL;
1779 }
1780 if (end == Py_None) {
1781 end = NULL;
1782 }
1783 else if (end && !PyUnicode_Check(end)) {
1784 PyErr_Format(PyExc_TypeError,
1785 "end must be None or a string, not %.200s",
1786 end->ob_type->tp_name);
1787 return NULL;
1788 }
Guido van Rossum34343512006-11-30 22:13:52 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 for (i = 0; i < PyTuple_Size(args); i++) {
1791 if (i > 0) {
1792 if (sep == NULL)
1793 err = PyFile_WriteString(" ", file);
1794 else
1795 err = PyFile_WriteObject(sep, file,
1796 Py_PRINT_RAW);
1797 if (err)
1798 return NULL;
1799 }
1800 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1801 Py_PRINT_RAW);
1802 if (err)
1803 return NULL;
1804 }
Guido van Rossum34343512006-11-30 22:13:52 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 if (end == NULL)
1807 err = PyFile_WriteString("\n", file);
1808 else
1809 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1810 if (err)
1811 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001812
Georg Brandlbc3b6822012-01-13 19:41:25 +01001813 if (flush != NULL) {
1814 PyObject *tmp;
1815 int do_flush = PyObject_IsTrue(flush);
1816 if (do_flush == -1)
1817 return NULL;
1818 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001819 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001820 if (tmp == NULL)
1821 return NULL;
1822 else
1823 Py_DECREF(tmp);
1824 }
1825 }
1826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001828}
1829
1830PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001831"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001832\n\
1833Prints the values to a stream, or to sys.stdout by default.\n\
1834Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001835file: a file-like object (stream); defaults to the current sys.stdout.\n\
1836sep: string inserted between values, default a space.\n\
1837end: string appended after the last value, default a newline.\n\
1838flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001839
1840
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001841/*[clinic input]
1842input as builtin_input
1843
1844 prompt: object(c_default="NULL") = None
1845 /
1846
1847Read a string from standard input. The trailing newline is stripped.
1848
1849The prompt string, if given, is printed to standard output without a
1850trailing newline before reading input.
1851
1852If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1853On *nix systems, readline is used if available.
1854[clinic start generated code]*/
1855
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001856static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001857builtin_input_impl(PyObject *module, PyObject *prompt)
1858/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001859{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001860 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1861 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1862 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 PyObject *tmp;
1864 long fd;
1865 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 /* Check that stdin/out/err are intact */
1868 if (fin == NULL || fin == Py_None) {
1869 PyErr_SetString(PyExc_RuntimeError,
1870 "input(): lost sys.stdin");
1871 return NULL;
1872 }
1873 if (fout == NULL || fout == Py_None) {
1874 PyErr_SetString(PyExc_RuntimeError,
1875 "input(): lost sys.stdout");
1876 return NULL;
1877 }
1878 if (ferr == NULL || ferr == Py_None) {
1879 PyErr_SetString(PyExc_RuntimeError,
1880 "input(): lost sys.stderr");
1881 return NULL;
1882 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001885 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (tmp == NULL)
1887 PyErr_Clear();
1888 else
1889 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* We should only use (GNU) readline if Python's sys.stdin and
1892 sys.stdout are the same as C's stdin and stdout, because we
1893 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001894 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 if (tmp == NULL) {
1896 PyErr_Clear();
1897 tty = 0;
1898 }
1899 else {
1900 fd = PyLong_AsLong(tmp);
1901 Py_DECREF(tmp);
1902 if (fd < 0 && PyErr_Occurred())
1903 return NULL;
1904 tty = fd == fileno(stdin) && isatty(fd);
1905 }
1906 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001907 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001908 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001910 tty = 0;
1911 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 else {
1913 fd = PyLong_AsLong(tmp);
1914 Py_DECREF(tmp);
1915 if (fd < 0 && PyErr_Occurred())
1916 return NULL;
1917 tty = fd == fileno(stdout) && isatty(fd);
1918 }
1919 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 /* If we're interactive, use (GNU) readline */
1922 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001923 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001924 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001925 char *s = NULL;
1926 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1927 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1928 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001930 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001931
Serhiy Storchakaaac875f2017-03-12 21:52:17 +02001932 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001933 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001934 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakaaac875f2017-03-12 21:52:17 +02001935 if (!stdin_encoding || !stdin_errors ||
1936 !PyUnicode_Check(stdin_encoding) ||
1937 !PyUnicode_Check(stdin_errors)) {
1938 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001939 goto _readline_errors;
Serhiy Storchakaaac875f2017-03-12 21:52:17 +02001940 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001941 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
1942 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001943 if (!stdin_encoding_str || !stdin_errors_str)
1944 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07001945 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 if (tmp == NULL)
1947 PyErr_Clear();
1948 else
1949 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001950 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001951 /* We have a prompt, encode it as stdout would */
1952 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001954 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001955 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakaaac875f2017-03-12 21:52:17 +02001956 if (!stdout_encoding || !stdout_errors ||
1957 !PyUnicode_Check(stdout_encoding) ||
1958 !PyUnicode_Check(stdout_errors)) {
1959 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001960 goto _readline_errors;
Serhiy Storchakaaac875f2017-03-12 21:52:17 +02001961 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001962 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
1963 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001964 if (!stdout_encoding_str || !stdout_errors_str)
1965 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001966 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001967 if (stringpo == NULL)
1968 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001970 stdout_encoding_str, stdout_errors_str);
1971 Py_CLEAR(stdout_encoding);
1972 Py_CLEAR(stdout_errors);
1973 Py_CLEAR(stringpo);
1974 if (po == NULL)
1975 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001976 assert(PyBytes_Check(po));
1977 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 }
1979 else {
1980 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001981 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001983 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001985 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (!PyErr_Occurred())
1987 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001988 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001990
1991 len = strlen(s);
1992 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 PyErr_SetNone(PyExc_EOFError);
1994 result = NULL;
1995 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001996 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (len > PY_SSIZE_T_MAX) {
1998 PyErr_SetString(PyExc_OverflowError,
1999 "input: input too long");
2000 result = NULL;
2001 }
2002 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002003 len--; /* strip trailing '\n' */
2004 if (len != 0 && s[len-1] == '\r')
2005 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002006 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2007 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 }
2009 }
2010 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002011 Py_DECREF(stdin_errors);
2012 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 PyMem_FREE(s);
2014 return result;
Serhiy Storchakaaac875f2017-03-12 21:52:17 +02002015
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002016 _readline_errors:
2017 Py_XDECREF(stdin_encoding);
2018 Py_XDECREF(stdout_encoding);
2019 Py_XDECREF(stdin_errors);
2020 Py_XDECREF(stdout_errors);
2021 Py_XDECREF(po);
Serhiy Storchakaaac875f2017-03-12 21:52:17 +02002022 if (tty)
2023 return NULL;
2024
2025 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002029 if (prompt != NULL) {
2030 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 return NULL;
2032 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002033 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if (tmp == NULL)
2035 PyErr_Clear();
2036 else
2037 Py_DECREF(tmp);
2038 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002039}
2040
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002041
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002042/*[clinic input]
2043repr as builtin_repr
2044
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002045 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002046 /
2047
2048Return the canonical string representation of the object.
2049
2050For many object types, including most builtins, eval(repr(obj)) == obj.
2051[clinic start generated code]*/
2052
Guido van Rossum79f25d91997-04-29 20:08:16 +00002053static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002054builtin_repr(PyObject *module, PyObject *obj)
2055/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002056{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002057 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002058}
2059
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002060
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002061/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2062 * or a semantic change to accept None for "ndigits"
2063 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002064static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002065builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyObject *ndigits = NULL;
2068 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002069 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2072 kwlist, &number, &ndigits))
2073 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (Py_TYPE(number)->tp_dict == NULL) {
2076 if (PyType_Ready(Py_TYPE(number)) < 0)
2077 return NULL;
2078 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002079
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002080 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002082 if (!PyErr_Occurred())
2083 PyErr_Format(PyExc_TypeError,
2084 "type %.100s doesn't define __round__ method",
2085 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 return NULL;
2087 }
Alex Martelliae211f92007-08-22 23:21:33 +00002088
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002089 if (ndigits == NULL || ndigits == Py_None)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002090 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002092 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2093 Py_DECREF(round);
2094 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002095}
2096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002097PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002098"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002099\n\
2100Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002101This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002102same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002103
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002104
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002105/*AC: we need to keep the kwds dict intact to easily call into the
2106 * list.sort method, which isn't currently supported in AC. So we just use
2107 * the initially generated signature with a custom implementation.
2108 */
2109/* [disabled clinic input]
2110sorted as builtin_sorted
2111
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002112 iterable as seq: object
2113 key as keyfunc: object = None
2114 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002115
2116Return a new list containing all items from the iterable in ascending order.
2117
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002118A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002119reverse flag can be set to request the result in descending order.
2120[end disabled clinic input]*/
2121
2122PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002123"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002124"--\n"
2125"\n"
2126"Return a new list containing all items from the iterable in ascending order.\n"
2127"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002128"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002129"reverse flag can be set to request the result in descending order.");
2130
2131#define BUILTIN_SORTED_METHODDEF \
2132 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
2133
Raymond Hettinger64958a12003-12-17 20:43:33 +00002134static PyObject *
2135builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2136{
Victor Stinner2990fa12016-08-22 23:21:55 +02002137 PyObject *newlist, *v, *seq, *keyfunc=NULL, **newargs;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 PyObject *callable;
Serhiy Storchaka398ef5c2017-01-20 08:33:06 +02002139 static char *kwlist[] = {"", "key", "reverse", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 int reverse;
Victor Stinner74319ae2016-08-25 00:04:09 +02002141 Py_ssize_t nargs;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* args 1-3 should match listsort in Objects/listobject.c */
2144 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
2145 kwlist, &seq, &keyfunc, &reverse))
2146 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 newlist = PySequence_List(seq);
2149 if (newlist == NULL)
2150 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002151
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002152 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 if (callable == NULL) {
2154 Py_DECREF(newlist);
2155 return NULL;
2156 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002157
Serhiy Storchaka398ef5c2017-01-20 08:33:06 +02002158 assert(PyTuple_GET_SIZE(args) >= 1);
Victor Stinner2990fa12016-08-22 23:21:55 +02002159 newargs = &PyTuple_GET_ITEM(args, 1);
2160 nargs = PyTuple_GET_SIZE(args) - 1;
2161 v = _PyObject_FastCallDict(callable, newargs, nargs, kwds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 Py_DECREF(callable);
2163 if (v == NULL) {
2164 Py_DECREF(newlist);
2165 return NULL;
2166 }
2167 Py_DECREF(v);
2168 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002169}
2170
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002171
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002172/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002173static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002174builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 PyObject *v = NULL;
2177 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2180 return NULL;
2181 if (v == NULL) {
2182 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002183 if (d == NULL)
2184 return NULL;
2185 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 }
2187 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002188 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (d == NULL) {
2190 PyErr_SetString(PyExc_TypeError,
2191 "vars() argument must have __dict__ attribute");
2192 return NULL;
2193 }
2194 }
2195 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002196}
2197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002198PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002199"vars([object]) -> dictionary\n\
2200\n\
2201Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002202With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002203
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002204
2205/*[clinic input]
2206sum as builtin_sum
2207
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002208 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002209 start: object(c_default="NULL") = 0
2210 /
2211
2212Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2213
2214When the iterable is empty, return the start value.
2215This function is intended specifically for use with numeric values and may
2216reject non-numeric types.
2217[clinic start generated code]*/
2218
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002219static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002220builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2221/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002222{
2223 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002225
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002226 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 if (iter == NULL)
2228 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (result == NULL) {
2231 result = PyLong_FromLong(0);
2232 if (result == NULL) {
2233 Py_DECREF(iter);
2234 return NULL;
2235 }
2236 } else {
2237 /* reject string values for 'start' parameter */
2238 if (PyUnicode_Check(result)) {
2239 PyErr_SetString(PyExc_TypeError,
2240 "sum() can't sum strings [use ''.join(seq) instead]");
2241 Py_DECREF(iter);
2242 return NULL;
2243 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002244 if (PyBytes_Check(result)) {
2245 PyErr_SetString(PyExc_TypeError,
2246 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002247 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002248 return NULL;
2249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 if (PyByteArray_Check(result)) {
2251 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002252 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 Py_DECREF(iter);
2254 return NULL;
2255 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 Py_INCREF(result);
2257 }
Alex Martellia70b1912003-04-22 08:12:33 +00002258
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002259#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2261 Assumes all inputs are the same type. If the assumption fails, default
2262 to the more general routine.
2263 */
2264 if (PyLong_CheckExact(result)) {
2265 int overflow;
2266 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2267 /* If this already overflowed, don't even enter the loop. */
2268 if (overflow == 0) {
2269 Py_DECREF(result);
2270 result = NULL;
2271 }
2272 while(result == NULL) {
2273 item = PyIter_Next(iter);
2274 if (item == NULL) {
2275 Py_DECREF(iter);
2276 if (PyErr_Occurred())
2277 return NULL;
2278 return PyLong_FromLong(i_result);
2279 }
2280 if (PyLong_CheckExact(item)) {
2281 long b = PyLong_AsLongAndOverflow(item, &overflow);
2282 long x = i_result + b;
2283 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2284 i_result = x;
2285 Py_DECREF(item);
2286 continue;
2287 }
2288 }
2289 /* Either overflowed or is not an int. Restore real objects and process normally */
2290 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002291 if (result == NULL) {
2292 Py_DECREF(item);
2293 Py_DECREF(iter);
2294 return NULL;
2295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 temp = PyNumber_Add(result, item);
2297 Py_DECREF(result);
2298 Py_DECREF(item);
2299 result = temp;
2300 if (result == NULL) {
2301 Py_DECREF(iter);
2302 return NULL;
2303 }
2304 }
2305 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 if (PyFloat_CheckExact(result)) {
2308 double f_result = PyFloat_AS_DOUBLE(result);
2309 Py_DECREF(result);
2310 result = NULL;
2311 while(result == NULL) {
2312 item = PyIter_Next(iter);
2313 if (item == NULL) {
2314 Py_DECREF(iter);
2315 if (PyErr_Occurred())
2316 return NULL;
2317 return PyFloat_FromDouble(f_result);
2318 }
2319 if (PyFloat_CheckExact(item)) {
2320 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2321 f_result += PyFloat_AS_DOUBLE(item);
2322 PyFPE_END_PROTECT(f_result)
2323 Py_DECREF(item);
2324 continue;
2325 }
2326 if (PyLong_CheckExact(item)) {
2327 long value;
2328 int overflow;
2329 value = PyLong_AsLongAndOverflow(item, &overflow);
2330 if (!overflow) {
2331 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2332 f_result += (double)value;
2333 PyFPE_END_PROTECT(f_result)
2334 Py_DECREF(item);
2335 continue;
2336 }
2337 }
2338 result = PyFloat_FromDouble(f_result);
2339 temp = PyNumber_Add(result, item);
2340 Py_DECREF(result);
2341 Py_DECREF(item);
2342 result = temp;
2343 if (result == NULL) {
2344 Py_DECREF(iter);
2345 return NULL;
2346 }
2347 }
2348 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002349#endif
2350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 for(;;) {
2352 item = PyIter_Next(iter);
2353 if (item == NULL) {
2354 /* error, or end-of-sequence */
2355 if (PyErr_Occurred()) {
2356 Py_DECREF(result);
2357 result = NULL;
2358 }
2359 break;
2360 }
2361 /* It's tempting to use PyNumber_InPlaceAdd instead of
2362 PyNumber_Add here, to avoid quadratic running time
2363 when doing 'sum(list_of_lists, [])'. However, this
2364 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 empty = []
2367 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 would change the value of empty. */
2370 temp = PyNumber_Add(result, item);
2371 Py_DECREF(result);
2372 Py_DECREF(item);
2373 result = temp;
2374 if (result == NULL)
2375 break;
2376 }
2377 Py_DECREF(iter);
2378 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002379}
2380
Alex Martellia70b1912003-04-22 08:12:33 +00002381
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002382/*[clinic input]
2383isinstance as builtin_isinstance
2384
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002385 obj: object
2386 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002387 /
2388
2389Return whether an object is an instance of a class or of a subclass thereof.
2390
2391A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2392check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2393or ...`` etc.
2394[clinic start generated code]*/
2395
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002396static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002397builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002398 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002399/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002402
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002403 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 if (retval < 0)
2405 return NULL;
2406 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002407}
2408
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002409
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002410/*[clinic input]
2411issubclass as builtin_issubclass
2412
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002413 cls: object
2414 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002415 /
2416
2417Return whether 'cls' is a derived from another class or is the same class.
2418
2419A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2420check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2421or ...`` etc.
2422[clinic start generated code]*/
2423
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002424static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002425builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002426 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002427/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002430
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002431 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 if (retval < 0)
2433 return NULL;
2434 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002435}
2436
2437
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002438typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 PyObject_HEAD
2440 Py_ssize_t tuplesize;
2441 PyObject *ittuple; /* tuple of iterators */
2442 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002443} zipobject;
2444
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002445static PyObject *
2446zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 zipobject *lz;
2449 Py_ssize_t i;
2450 PyObject *ittuple; /* tuple of iterators */
2451 PyObject *result;
2452 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2455 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* args must be a tuple */
2458 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 /* obtain iterators */
2461 ittuple = PyTuple_New(tuplesize);
2462 if (ittuple == NULL)
2463 return NULL;
2464 for (i=0; i < tuplesize; ++i) {
2465 PyObject *item = PyTuple_GET_ITEM(args, i);
2466 PyObject *it = PyObject_GetIter(item);
2467 if (it == NULL) {
2468 if (PyErr_ExceptionMatches(PyExc_TypeError))
2469 PyErr_Format(PyExc_TypeError,
2470 "zip argument #%zd must support iteration",
2471 i+1);
2472 Py_DECREF(ittuple);
2473 return NULL;
2474 }
2475 PyTuple_SET_ITEM(ittuple, i, it);
2476 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* create a result holder */
2479 result = PyTuple_New(tuplesize);
2480 if (result == NULL) {
2481 Py_DECREF(ittuple);
2482 return NULL;
2483 }
2484 for (i=0 ; i < tuplesize ; i++) {
2485 Py_INCREF(Py_None);
2486 PyTuple_SET_ITEM(result, i, Py_None);
2487 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 /* create zipobject structure */
2490 lz = (zipobject *)type->tp_alloc(type, 0);
2491 if (lz == NULL) {
2492 Py_DECREF(ittuple);
2493 Py_DECREF(result);
2494 return NULL;
2495 }
2496 lz->ittuple = ittuple;
2497 lz->tuplesize = tuplesize;
2498 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002501}
2502
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002503static void
2504zip_dealloc(zipobject *lz)
2505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 PyObject_GC_UnTrack(lz);
2507 Py_XDECREF(lz->ittuple);
2508 Py_XDECREF(lz->result);
2509 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002510}
2511
2512static int
2513zip_traverse(zipobject *lz, visitproc visit, void *arg)
2514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 Py_VISIT(lz->ittuple);
2516 Py_VISIT(lz->result);
2517 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002518}
2519
2520static PyObject *
2521zip_next(zipobject *lz)
2522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 Py_ssize_t i;
2524 Py_ssize_t tuplesize = lz->tuplesize;
2525 PyObject *result = lz->result;
2526 PyObject *it;
2527 PyObject *item;
2528 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 if (tuplesize == 0)
2531 return NULL;
2532 if (Py_REFCNT(result) == 1) {
2533 Py_INCREF(result);
2534 for (i=0 ; i < tuplesize ; i++) {
2535 it = PyTuple_GET_ITEM(lz->ittuple, i);
2536 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002537 if (item == NULL) {
2538 Py_DECREF(result);
2539 return NULL;
2540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 olditem = PyTuple_GET_ITEM(result, i);
2542 PyTuple_SET_ITEM(result, i, item);
2543 Py_DECREF(olditem);
2544 }
2545 } else {
2546 result = PyTuple_New(tuplesize);
2547 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002548 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 for (i=0 ; i < tuplesize ; i++) {
2550 it = PyTuple_GET_ITEM(lz->ittuple, i);
2551 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002552 if (item == NULL) {
2553 Py_DECREF(result);
2554 return NULL;
2555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 PyTuple_SET_ITEM(result, i, item);
2557 }
2558 }
2559 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002560}
Barry Warsawbd599b52000-08-03 15:45:29 +00002561
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002562static PyObject *
2563zip_reduce(zipobject *lz)
2564{
2565 /* Just recreate the zip with the internal iterator tuple */
2566 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2567}
2568
2569static PyMethodDef zip_methods[] = {
2570 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2571 {NULL, NULL} /* sentinel */
2572};
2573
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002574PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002575"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002576\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002577Return a zip object whose .__next__() method returns a tuple where\n\
2578the i-th element comes from the i-th iterable argument. The .__next__()\n\
2579method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002580is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002581
2582PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2584 "zip", /* tp_name */
2585 sizeof(zipobject), /* tp_basicsize */
2586 0, /* tp_itemsize */
2587 /* methods */
2588 (destructor)zip_dealloc, /* tp_dealloc */
2589 0, /* tp_print */
2590 0, /* tp_getattr */
2591 0, /* tp_setattr */
2592 0, /* tp_reserved */
2593 0, /* tp_repr */
2594 0, /* tp_as_number */
2595 0, /* tp_as_sequence */
2596 0, /* tp_as_mapping */
2597 0, /* tp_hash */
2598 0, /* tp_call */
2599 0, /* tp_str */
2600 PyObject_GenericGetAttr, /* tp_getattro */
2601 0, /* tp_setattro */
2602 0, /* tp_as_buffer */
2603 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2604 Py_TPFLAGS_BASETYPE, /* tp_flags */
2605 zip_doc, /* tp_doc */
2606 (traverseproc)zip_traverse, /* tp_traverse */
2607 0, /* tp_clear */
2608 0, /* tp_richcompare */
2609 0, /* tp_weaklistoffset */
2610 PyObject_SelfIter, /* tp_iter */
2611 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002612 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 0, /* tp_members */
2614 0, /* tp_getset */
2615 0, /* tp_base */
2616 0, /* tp_dict */
2617 0, /* tp_descr_get */
2618 0, /* tp_descr_set */
2619 0, /* tp_dictoffset */
2620 0, /* tp_init */
2621 PyType_GenericAlloc, /* tp_alloc */
2622 zip_new, /* tp_new */
2623 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002624};
Barry Warsawbd599b52000-08-03 15:45:29 +00002625
2626
Guido van Rossum79f25d91997-04-29 20:08:16 +00002627static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 {"__build_class__", (PyCFunction)builtin___build_class__,
2629 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2630 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002631 BUILTIN_ABS_METHODDEF
2632 BUILTIN_ALL_METHODDEF
2633 BUILTIN_ANY_METHODDEF
2634 BUILTIN_ASCII_METHODDEF
2635 BUILTIN_BIN_METHODDEF
2636 BUILTIN_CALLABLE_METHODDEF
2637 BUILTIN_CHR_METHODDEF
2638 BUILTIN_COMPILE_METHODDEF
2639 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002641 BUILTIN_DIVMOD_METHODDEF
2642 BUILTIN_EVAL_METHODDEF
2643 BUILTIN_EXEC_METHODDEF
2644 BUILTIN_FORMAT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002646 BUILTIN_GLOBALS_METHODDEF
2647 BUILTIN_HASATTR_METHODDEF
2648 BUILTIN_HASH_METHODDEF
2649 BUILTIN_HEX_METHODDEF
2650 BUILTIN_ID_METHODDEF
2651 BUILTIN_INPUT_METHODDEF
2652 BUILTIN_ISINSTANCE_METHODDEF
2653 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002655 BUILTIN_LEN_METHODDEF
2656 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2658 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2659 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002660 BUILTIN_OCT_METHODDEF
2661 BUILTIN_ORD_METHODDEF
2662 BUILTIN_POW_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002664 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002666 BUILTIN_SETATTR_METHODDEF
2667 BUILTIN_SORTED_METHODDEF
2668 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2670 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002671};
2672
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002673PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002674"Built-in functions, exceptions, and other objects.\n\
2675\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002676Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002677
Martin v. Löwis1a214512008-06-11 05:26:20 +00002678static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 PyModuleDef_HEAD_INIT,
2680 "builtins",
2681 builtin_doc,
2682 -1, /* multiple "initialization" just copies the module dict. */
2683 builtin_methods,
2684 NULL,
2685 NULL,
2686 NULL,
2687 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002688};
2689
2690
Guido van Rossum25ce5661997-08-02 03:10:38 +00002691PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002692_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002695
2696 if (PyType_Ready(&PyFilter_Type) < 0 ||
2697 PyType_Ready(&PyMap_Type) < 0 ||
2698 PyType_Ready(&PyZip_Type) < 0)
2699 return NULL;
2700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 mod = PyModule_Create(&builtinsmodule);
2702 if (mod == NULL)
2703 return NULL;
2704 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002705
Tim Peters7571a0f2003-03-23 17:52:28 +00002706#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 /* "builtins" exposes a number of statically allocated objects
2708 * that, before this code was added in 2.3, never showed up in
2709 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2710 * result, programs leaking references to None and False (etc)
2711 * couldn't be diagnosed by examining sys.getobjects(0).
2712 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002713#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2714#else
2715#define ADD_TO_ALL(OBJECT) (void)0
2716#endif
2717
Tim Peters4b7625e2001-09-13 21:37:17 +00002718#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2720 return NULL; \
2721 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 SETBUILTIN("None", Py_None);
2724 SETBUILTIN("Ellipsis", Py_Ellipsis);
2725 SETBUILTIN("NotImplemented", Py_NotImplemented);
2726 SETBUILTIN("False", Py_False);
2727 SETBUILTIN("True", Py_True);
2728 SETBUILTIN("bool", &PyBool_Type);
2729 SETBUILTIN("memoryview", &PyMemoryView_Type);
2730 SETBUILTIN("bytearray", &PyByteArray_Type);
2731 SETBUILTIN("bytes", &PyBytes_Type);
2732 SETBUILTIN("classmethod", &PyClassMethod_Type);
2733 SETBUILTIN("complex", &PyComplex_Type);
2734 SETBUILTIN("dict", &PyDict_Type);
2735 SETBUILTIN("enumerate", &PyEnum_Type);
2736 SETBUILTIN("filter", &PyFilter_Type);
2737 SETBUILTIN("float", &PyFloat_Type);
2738 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2739 SETBUILTIN("property", &PyProperty_Type);
2740 SETBUILTIN("int", &PyLong_Type);
2741 SETBUILTIN("list", &PyList_Type);
2742 SETBUILTIN("map", &PyMap_Type);
2743 SETBUILTIN("object", &PyBaseObject_Type);
2744 SETBUILTIN("range", &PyRange_Type);
2745 SETBUILTIN("reversed", &PyReversed_Type);
2746 SETBUILTIN("set", &PySet_Type);
2747 SETBUILTIN("slice", &PySlice_Type);
2748 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2749 SETBUILTIN("str", &PyUnicode_Type);
2750 SETBUILTIN("super", &PySuper_Type);
2751 SETBUILTIN("tuple", &PyTuple_Type);
2752 SETBUILTIN("type", &PyType_Type);
2753 SETBUILTIN("zip", &PyZip_Type);
2754 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2755 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002756 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 return NULL;
2758 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002759 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002762#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002763#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002764}