blob: 23d7aa4568371b15b09820fef3dab8243a698928 [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
Mark Hammond26cffde42001-05-14 12:17:34 +000014/* The default encoding used by the platform file system APIs
15 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000016
17 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
18 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000019*/
Steve Dowercc16be82016-09-08 10:35:16 -070020#if defined(__APPLE__)
21const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000022int Py_HasFileSystemDefaultEncoding = 1;
Steve Dowercc16be82016-09-08 10:35:16 -070023#elif defined(MS_WINDOWS)
24/* may be changed by initfsencoding(), but should never be free()d */
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000025const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020027#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000028const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000030#endif
Steve Dowercc16be82016-09-08 10:35:16 -070031const char *Py_FileSystemDefaultEncodeErrors = "surrogateescape";
Victor Stinner91106cd2017-12-13 12:29:09 +010032/* UTF-8 mode (PEP 540): if non-zero, use the UTF-8 encoding, and change stdin
33 and stdout error handler to "surrogateescape". */
34int Py_UTF8Mode = 0;
Mark Hammondef8b6542001-05-13 08:04:26 +000035
Victor Stinnerbd303c12013-11-07 23:07:29 +010036_Py_IDENTIFIER(__builtins__);
37_Py_IDENTIFIER(__dict__);
38_Py_IDENTIFIER(__prepare__);
39_Py_IDENTIFIER(__round__);
40_Py_IDENTIFIER(encoding);
41_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020042_Py_IDENTIFIER(fileno);
43_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010044_Py_IDENTIFIER(metaclass);
45_Py_IDENTIFIER(sort);
46_Py_IDENTIFIER(stdin);
47_Py_IDENTIFIER(stdout);
48_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020049
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030050#include "clinic/bltinmodule.c.h"
51
Nick Coghlanf9e227e2014-08-17 14:01:19 +100052/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000053static PyObject *
Victor Stinner773dc6d2017-01-16 23:46:26 +010054builtin___build_class__(PyObject *self, PyObject **args, Py_ssize_t nargs,
55 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +000056{
Nick Coghlan19d24672016-12-05 16:47:55 +100057 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns;
58 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010059 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 if (nargs < 2) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: not enough arguments");
64 return NULL;
65 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010066 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050067 if (!PyFunction_Check(func)) {
68 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050069 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050070 return NULL;
71 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010072 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 if (!PyUnicode_Check(name)) {
74 PyErr_SetString(PyExc_TypeError,
75 "__build_class__: name is not a string");
76 return NULL;
77 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010078 bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 if (bases == NULL)
80 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000081
Victor Stinner773dc6d2017-01-16 23:46:26 +010082 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 meta = NULL;
84 mkw = NULL;
85 }
86 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +010087 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 if (mkw == NULL) {
89 Py_DECREF(bases);
90 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000091 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010092
Victor Stinnerae9f1612013-11-06 22:46:51 +010093 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 if (meta != NULL) {
95 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010096 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 Py_DECREF(meta);
98 Py_DECREF(mkw);
99 Py_DECREF(bases);
100 return NULL;
101 }
Nick Coghlande31b192011-10-23 22:04:16 +1000102 /* metaclass is explicitly given, check if it's indeed a class */
103 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 }
105 }
106 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000107 /* if there are no bases, use type: */
108 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000110 }
111 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 else {
113 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
114 meta = (PyObject *) (base0->ob_type);
115 }
116 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000117 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000119
Nick Coghlande31b192011-10-23 22:04:16 +1000120 if (isclass) {
121 /* meta is really a class, so check for a more derived
122 metaclass, or possible metaclass conflicts: */
123 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
124 bases);
125 if (winner == NULL) {
126 Py_DECREF(meta);
127 Py_XDECREF(mkw);
128 Py_DECREF(bases);
129 return NULL;
130 }
131 if (winner != meta) {
132 Py_DECREF(meta);
133 meta = winner;
134 Py_INCREF(meta);
135 }
136 }
137 /* else: meta is not a class, so we cannot do the metaclass
138 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200139 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 if (prep == NULL) {
141 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
142 PyErr_Clear();
Eric Snow4f29e752016-09-08 15:11:11 -0700143 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 }
145 else {
146 Py_DECREF(meta);
147 Py_XDECREF(mkw);
148 Py_DECREF(bases);
149 return NULL;
150 }
151 }
152 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200153 PyObject *pargs[2] = {name, bases};
154 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 Py_DECREF(prep);
156 }
157 if (ns == NULL) {
158 Py_DECREF(meta);
159 Py_XDECREF(mkw);
160 Py_DECREF(bases);
161 return NULL;
162 }
Oren Milman5837d042017-09-27 17:04:37 +0300163 if (!PyMapping_Check(ns)) {
164 PyErr_Format(PyExc_TypeError,
165 "%.200s.__prepare__() must return a mapping, not %.200s",
166 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
167 Py_TYPE(ns)->tp_name);
168 goto error;
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
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400428static PyObject *
429builtin_breakpoint(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *keywords)
430{
431 PyObject *hook = PySys_GetObject("breakpointhook");
432
433 if (hook == NULL) {
434 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
435 return NULL;
436 }
437 Py_INCREF(hook);
438 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
439 Py_DECREF(hook);
440 return retval;
441}
442
443PyDoc_STRVAR(breakpoint_doc,
444"breakpoint(*args, **kws)\n\
445\n\
446Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
447whatever arguments are passed.\n\
448\n\
449By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000450
Raymond Hettinger17301e92008-03-13 00:19:26 +0000451typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 PyObject_HEAD
453 PyObject *func;
454 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000455} filterobject;
456
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000457static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000458filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyObject *func, *seq;
461 PyObject *it;
462 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000463
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300464 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
468 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 /* Get iterator. */
471 it = PyObject_GetIter(seq);
472 if (it == NULL)
473 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 /* create filterobject structure */
476 lz = (filterobject *)type->tp_alloc(type, 0);
477 if (lz == NULL) {
478 Py_DECREF(it);
479 return NULL;
480 }
481 Py_INCREF(func);
482 lz->func = func;
483 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000486}
487
488static void
489filter_dealloc(filterobject *lz)
490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 PyObject_GC_UnTrack(lz);
492 Py_XDECREF(lz->func);
493 Py_XDECREF(lz->it);
494 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000495}
496
497static int
498filter_traverse(filterobject *lz, visitproc visit, void *arg)
499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 Py_VISIT(lz->it);
501 Py_VISIT(lz->func);
502 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000503}
504
505static PyObject *
506filter_next(filterobject *lz)
507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyObject *item;
509 PyObject *it = lz->it;
510 long ok;
511 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400512 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 iternext = *Py_TYPE(it)->tp_iternext;
515 for (;;) {
516 item = iternext(it);
517 if (item == NULL)
518 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000519
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400520 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 ok = PyObject_IsTrue(item);
522 } else {
523 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100524 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 if (good == NULL) {
526 Py_DECREF(item);
527 return NULL;
528 }
529 ok = PyObject_IsTrue(good);
530 Py_DECREF(good);
531 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200532 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return item;
534 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200535 if (ok < 0)
536 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000538}
539
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000540static PyObject *
541filter_reduce(filterobject *lz)
542{
543 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
544}
545
546PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
547
548static PyMethodDef filter_methods[] = {
549 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
550 {NULL, NULL} /* sentinel */
551};
552
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000553PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000554"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000555\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000556Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000557is true. If function is None, return the items that are true.");
558
559PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 PyVarObject_HEAD_INIT(&PyType_Type, 0)
561 "filter", /* tp_name */
562 sizeof(filterobject), /* tp_basicsize */
563 0, /* tp_itemsize */
564 /* methods */
565 (destructor)filter_dealloc, /* tp_dealloc */
566 0, /* tp_print */
567 0, /* tp_getattr */
568 0, /* tp_setattr */
569 0, /* tp_reserved */
570 0, /* tp_repr */
571 0, /* tp_as_number */
572 0, /* tp_as_sequence */
573 0, /* tp_as_mapping */
574 0, /* tp_hash */
575 0, /* tp_call */
576 0, /* tp_str */
577 PyObject_GenericGetAttr, /* tp_getattro */
578 0, /* tp_setattro */
579 0, /* tp_as_buffer */
580 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
581 Py_TPFLAGS_BASETYPE, /* tp_flags */
582 filter_doc, /* tp_doc */
583 (traverseproc)filter_traverse, /* tp_traverse */
584 0, /* tp_clear */
585 0, /* tp_richcompare */
586 0, /* tp_weaklistoffset */
587 PyObject_SelfIter, /* tp_iter */
588 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000589 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 0, /* tp_members */
591 0, /* tp_getset */
592 0, /* tp_base */
593 0, /* tp_dict */
594 0, /* tp_descr_get */
595 0, /* tp_descr_set */
596 0, /* tp_dictoffset */
597 0, /* tp_init */
598 PyType_GenericAlloc, /* tp_alloc */
599 filter_new, /* tp_new */
600 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000601};
602
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000603
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000604/*[clinic input]
605format as builtin_format
606
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300607 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000608 format_spec: unicode(c_default="NULL") = ''
609 /
610
611Return value.__format__(format_spec)
612
Amit Kumar2e6bb442017-05-29 06:32:26 +0530613format_spec defaults to the empty string.
614See the Format Specification Mini-Language section of help('FORMATTING') for
615details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000616[clinic start generated code]*/
617
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000618static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300619builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530620/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000621{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000622 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000623}
624
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000625/*[clinic input]
626chr as builtin_chr
627
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300628 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000629 /
630
631Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
632[clinic start generated code]*/
633
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000634static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300635builtin_chr_impl(PyObject *module, int i)
636/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000637{
638 return PyUnicode_FromOrdinal(i);
639}
Guido van Rossum09095f32000-03-10 23:00:52 +0000640
641
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200642static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000643source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000644{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200645 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000647 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000648
Martin Pantereeb896c2015-11-07 02:32:21 +0000649 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (PyUnicode_Check(cmd)) {
651 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200652 str = PyUnicode_AsUTF8AndSize(cmd, &size);
653 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 return NULL;
655 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000656 else if (PyBytes_Check(cmd)) {
657 str = PyBytes_AS_STRING(cmd);
658 size = PyBytes_GET_SIZE(cmd);
659 }
660 else if (PyByteArray_Check(cmd)) {
661 str = PyByteArray_AS_STRING(cmd);
662 size = PyByteArray_GET_SIZE(cmd);
663 }
664 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
665 /* Copy to NUL-terminated buffer. */
666 *cmd_copy = PyBytes_FromStringAndSize(
667 (const char *)view.buf, view.len);
668 PyBuffer_Release(&view);
669 if (*cmd_copy == NULL) {
670 return NULL;
671 }
672 str = PyBytes_AS_STRING(*cmd_copy);
673 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200674 }
675 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyErr_Format(PyExc_TypeError,
677 "%s() arg 1 must be a %s object",
678 funcname, what);
679 return NULL;
680 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200681
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200682 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300683 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000685 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 return NULL;
687 }
688 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000689}
690
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000691/*[clinic input]
692compile as builtin_compile
693
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300694 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000695 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300696 mode: str
697 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200698 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300699 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000700
701Compile source into a code object that can be executed by exec() or eval().
702
703The source code may represent a Python module, statement or expression.
704The filename will be used for run-time error messages.
705The mode must be 'exec' to compile a module, 'single' to compile a
706single (interactive) statement, or 'eval' to compile an expression.
707The flags argument, if present, controls which future statements influence
708the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300709The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000710the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300711compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000712in addition to any features explicitly specified.
713[clinic start generated code]*/
714
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000715static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300716builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
717 const char *mode, int flags, int dont_inherit,
718 int optimize)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200719/*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000720{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000721 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200722 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000723 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 int is_ast;
725 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000727 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000728
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000729 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000730
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000731 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
733 {
734 PyErr_SetString(PyExc_ValueError,
735 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000736 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 }
738 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000739
Georg Brandl8334fd92010-12-04 10:26:46 +0000740 if (optimize < -1 || optimize > 2) {
741 PyErr_SetString(PyExc_ValueError,
742 "compile(): invalid optimize value");
743 goto error;
744 }
745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (!dont_inherit) {
747 PyEval_MergeCompilerFlags(&cf);
748 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000749
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000750 if (strcmp(mode, "exec") == 0)
751 compile_mode = 0;
752 else if (strcmp(mode, "eval") == 0)
753 compile_mode = 1;
754 else if (strcmp(mode, "single") == 0)
755 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 else {
757 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000758 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000759 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000761
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000762 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000764 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000766 if (flags & PyCF_ONLY_AST) {
767 Py_INCREF(source);
768 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 }
770 else {
771 PyArena *arena;
772 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200775 if (arena == NULL)
776 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000777 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (mod == NULL) {
779 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000780 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500782 if (!PyAST_Validate(mod)) {
783 PyArena_Free(arena);
784 goto error;
785 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200786 result = (PyObject*)PyAST_CompileObject(mod, filename,
787 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyArena_Free(arena);
789 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000790 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000792
Martin Panter61d6e4a2015-11-07 02:56:11 +0000793 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000795 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000796
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000797 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000798 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000799 goto finally;
800
801error:
802 result = NULL;
803finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200804 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000805 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000806}
807
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000808/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000809static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000810builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
815 return NULL;
816 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000817}
818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000819PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000820"dir([object]) -> list of strings\n"
821"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000822"If called without an argument, return the names in the current scope.\n"
823"Else, return an alphabetized list of names comprising (some of) the attributes\n"
824"of the given object, and of attributes reachable from it.\n"
825"If the object supplies a method named __dir__, it will be used; otherwise\n"
826"the default dir() logic is used and returns:\n"
827" for a module object: the module's attributes.\n"
828" for a class object: its attributes, and recursively the attributes\n"
829" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000830" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000831" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000832
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000833/*[clinic input]
834divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000835
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300836 x: object
837 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000838 /
839
Zachary Ware7f227d92016-04-28 14:39:50 -0500840Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000841[clinic start generated code]*/
842
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000843static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300844builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
845/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000846{
847 return PyNumber_Divmod(x, y);
848}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000849
850
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000851/*[clinic input]
852eval as builtin_eval
853
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300854 source: object
855 globals: object = None
856 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000857 /
858
859Evaluate the given source in the context of globals and locals.
860
861The source may be a string representing a Python expression
862or a code object as returned by compile().
863The globals must be a dictionary and locals can be any mapping,
864defaulting to the current globals and locals.
865If only globals is given, locals defaults to it.
866[clinic start generated code]*/
867
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000868static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300869builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400870 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300871/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000872{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000873 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200874 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (locals != Py_None && !PyMapping_Check(locals)) {
878 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
879 return NULL;
880 }
881 if (globals != Py_None && !PyDict_Check(globals)) {
882 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
883 "globals must be a real dict; try eval(expr, {}, mapping)"
884 : "globals must be a dict");
885 return NULL;
886 }
887 if (globals == Py_None) {
888 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100889 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100891 if (locals == NULL)
892 return NULL;
893 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 }
895 else if (locals == Py_None)
896 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 if (globals == NULL || locals == NULL) {
899 PyErr_SetString(PyExc_TypeError,
900 "eval must be given globals and locals "
901 "when called without a frame");
902 return NULL;
903 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000904
Victor Stinnerb44562b2013-11-06 19:03:11 +0100905 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
906 if (_PyDict_SetItemId(globals, &PyId___builtins__,
907 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 return NULL;
909 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000910
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000911 if (PyCode_Check(source)) {
912 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyErr_SetString(PyExc_TypeError,
914 "code object passed to eval() may not contain free variables");
915 return NULL;
916 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000917 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000921 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 if (str == NULL)
923 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 while (*str == ' ' || *str == '\t')
926 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 (void)PyEval_MergeCompilerFlags(&cf);
929 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000930 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000932}
933
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000934/*[clinic input]
935exec as builtin_exec
936
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300937 source: object
938 globals: object = None
939 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000940 /
941
942Execute the given source in the context of globals and locals.
943
944The source may be a string representing one or more Python statements
945or a code object as returned by compile().
946The globals must be a dictionary and locals can be any mapping,
947defaulting to the current globals and locals.
948If only globals is given, locals defaults to it.
949[clinic start generated code]*/
950
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000951static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300952builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400953 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300954/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (globals == Py_None) {
959 globals = PyEval_GetGlobals();
960 if (locals == Py_None) {
961 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100962 if (locals == NULL)
963 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
965 if (!globals || !locals) {
966 PyErr_SetString(PyExc_SystemError,
967 "globals and locals cannot be NULL");
968 return NULL;
969 }
970 }
971 else if (locals == Py_None)
972 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000975 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 globals->ob_type->tp_name);
977 return NULL;
978 }
979 if (!PyMapping_Check(locals)) {
980 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000981 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 locals->ob_type->tp_name);
983 return NULL;
984 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100985 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
986 if (_PyDict_SetItemId(globals, &PyId___builtins__,
987 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 return NULL;
989 }
990
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000991 if (PyCode_Check(source)) {
992 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 PyErr_SetString(PyExc_TypeError,
994 "code object passed to exec() may not "
995 "contain free variables");
996 return NULL;
997 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000998 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 }
1000 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001001 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001002 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 PyCompilerFlags cf;
1004 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001005 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001006 "string, bytes or code", &cf,
1007 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (str == NULL)
1009 return NULL;
1010 if (PyEval_MergeCompilerFlags(&cf))
1011 v = PyRun_StringFlags(str, Py_file_input, globals,
1012 locals, &cf);
1013 else
1014 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001015 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 }
1017 if (v == NULL)
1018 return NULL;
1019 Py_DECREF(v);
1020 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001021}
1022
Georg Brandl7cae87c2006-09-06 06:51:57 +00001023
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001024/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001025static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03001026builtin_getattr(PyObject *self, PyObject **args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyObject *v, *result, *dflt = NULL;
1029 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001030
Sylvain96c7c062017-06-15 17:05:23 +02001031 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
1032 return NULL;
1033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (!PyUnicode_Check(name)) {
1035 PyErr_SetString(PyExc_TypeError,
1036 "getattr(): attribute name must be string");
1037 return NULL;
1038 }
1039 result = PyObject_GetAttr(v, name);
1040 if (result == NULL && dflt != NULL &&
1041 PyErr_ExceptionMatches(PyExc_AttributeError))
1042 {
1043 PyErr_Clear();
1044 Py_INCREF(dflt);
1045 result = dflt;
1046 }
1047 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001048}
1049
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001050PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001051"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001052\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001053Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1054When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001055exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001056
1057
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001058/*[clinic input]
1059globals as builtin_globals
1060
1061Return the dictionary containing the current scope's global variables.
1062
1063NOTE: Updates to this dictionary *will* affect name lookups in the current
1064global scope and vice-versa.
1065[clinic start generated code]*/
1066
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001067static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001068builtin_globals_impl(PyObject *module)
1069/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 d = PyEval_GetGlobals();
1074 Py_XINCREF(d);
1075 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001076}
1077
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001078
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001079/*[clinic input]
1080hasattr as builtin_hasattr
1081
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001082 obj: object
1083 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001084 /
1085
1086Return whether the object has an attribute with the given name.
1087
1088This is done by calling getattr(obj, name) and catching AttributeError.
1089[clinic start generated code]*/
1090
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001091static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001092builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1093/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001094{
1095 PyObject *v;
1096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (!PyUnicode_Check(name)) {
1098 PyErr_SetString(PyExc_TypeError,
1099 "hasattr(): attribute name must be string");
1100 return NULL;
1101 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001102 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001104 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001106 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001108 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 }
1110 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001111 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001112}
1113
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001114
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001115/* AC: gdb's integration with CPython relies on builtin_id having
1116 * the *exact* parameter names of "self" and "v", so we ensure we
1117 * preserve those name rather than using the AC defaults.
1118 */
1119/*[clinic input]
1120id as builtin_id
1121
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001122 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001123 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001124 /
1125
1126Return the identity of an object.
1127
1128This is guaranteed to be unique among simultaneously existing objects.
1129(CPython uses the object's memory address.)
1130[clinic start generated code]*/
1131
Guido van Rossum79f25d91997-04-29 20:08:16 +00001132static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001133builtin_id(PyModuleDef *self, PyObject *v)
1134/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001137}
1138
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001139
Raymond Hettingera6c60372008-03-13 01:26:19 +00001140/* map object ************************************************************/
1141
1142typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyObject_HEAD
1144 PyObject *iters;
1145 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001146} mapobject;
1147
Guido van Rossum79f25d91997-04-29 20:08:16 +00001148static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001149map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *it, *iters, *func;
1152 mapobject *lz;
1153 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001154
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001155 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 numargs = PyTuple_Size(args);
1159 if (numargs < 2) {
1160 PyErr_SetString(PyExc_TypeError,
1161 "map() must have at least two arguments.");
1162 return NULL;
1163 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 iters = PyTuple_New(numargs-1);
1166 if (iters == NULL)
1167 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 for (i=1 ; i<numargs ; i++) {
1170 /* Get iterator. */
1171 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1172 if (it == NULL) {
1173 Py_DECREF(iters);
1174 return NULL;
1175 }
1176 PyTuple_SET_ITEM(iters, i-1, it);
1177 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 /* create mapobject structure */
1180 lz = (mapobject *)type->tp_alloc(type, 0);
1181 if (lz == NULL) {
1182 Py_DECREF(iters);
1183 return NULL;
1184 }
1185 lz->iters = iters;
1186 func = PyTuple_GET_ITEM(args, 0);
1187 Py_INCREF(func);
1188 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001191}
1192
1193static void
1194map_dealloc(mapobject *lz)
1195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 PyObject_GC_UnTrack(lz);
1197 Py_XDECREF(lz->iters);
1198 Py_XDECREF(lz->func);
1199 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001200}
1201
1202static int
1203map_traverse(mapobject *lz, visitproc visit, void *arg)
1204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 Py_VISIT(lz->iters);
1206 Py_VISIT(lz->func);
1207 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001208}
1209
1210static PyObject *
1211map_next(mapobject *lz)
1212{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001213 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001214 PyObject **stack;
1215 Py_ssize_t niters, nargs, i;
1216 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001217
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001218 niters = PyTuple_GET_SIZE(lz->iters);
1219 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1220 stack = small_stack;
1221 }
1222 else {
1223 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1224 if (stack == NULL) {
1225 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 return NULL;
1227 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001229
1230 nargs = 0;
1231 for (i=0; i < niters; i++) {
1232 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1233 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1234 if (val == NULL) {
1235 goto exit;
1236 }
1237 stack[i] = val;
1238 nargs++;
1239 }
1240
1241 result = _PyObject_FastCall(lz->func, stack, nargs);
1242
1243exit:
1244 for (i=0; i < nargs; i++) {
1245 Py_DECREF(stack[i]);
1246 }
1247 if (stack != small_stack) {
1248 PyMem_Free(stack);
1249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001251}
1252
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001253static PyObject *
1254map_reduce(mapobject *lz)
1255{
1256 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1257 PyObject *args = PyTuple_New(numargs+1);
1258 Py_ssize_t i;
1259 if (args == NULL)
1260 return NULL;
1261 Py_INCREF(lz->func);
1262 PyTuple_SET_ITEM(args, 0, lz->func);
1263 for (i = 0; i<numargs; i++){
1264 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1265 Py_INCREF(it);
1266 PyTuple_SET_ITEM(args, i+1, it);
1267 }
1268
1269 return Py_BuildValue("ON", Py_TYPE(lz), args);
1270}
1271
1272static PyMethodDef map_methods[] = {
1273 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1274 {NULL, NULL} /* sentinel */
1275};
1276
1277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001278PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001279"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001280\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001281Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001283
Raymond Hettingera6c60372008-03-13 01:26:19 +00001284PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1286 "map", /* tp_name */
1287 sizeof(mapobject), /* tp_basicsize */
1288 0, /* tp_itemsize */
1289 /* methods */
1290 (destructor)map_dealloc, /* tp_dealloc */
1291 0, /* tp_print */
1292 0, /* tp_getattr */
1293 0, /* tp_setattr */
1294 0, /* tp_reserved */
1295 0, /* tp_repr */
1296 0, /* tp_as_number */
1297 0, /* tp_as_sequence */
1298 0, /* tp_as_mapping */
1299 0, /* tp_hash */
1300 0, /* tp_call */
1301 0, /* tp_str */
1302 PyObject_GenericGetAttr, /* tp_getattro */
1303 0, /* tp_setattro */
1304 0, /* tp_as_buffer */
1305 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1306 Py_TPFLAGS_BASETYPE, /* tp_flags */
1307 map_doc, /* tp_doc */
1308 (traverseproc)map_traverse, /* tp_traverse */
1309 0, /* tp_clear */
1310 0, /* tp_richcompare */
1311 0, /* tp_weaklistoffset */
1312 PyObject_SelfIter, /* tp_iter */
1313 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001314 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 0, /* tp_members */
1316 0, /* tp_getset */
1317 0, /* tp_base */
1318 0, /* tp_dict */
1319 0, /* tp_descr_get */
1320 0, /* tp_descr_set */
1321 0, /* tp_dictoffset */
1322 0, /* tp_init */
1323 PyType_GenericAlloc, /* tp_alloc */
1324 map_new, /* tp_new */
1325 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001326};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001327
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001328
1329/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001330static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03001331builtin_next(PyObject *self, PyObject **args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 PyObject *it, *res;
1334 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001335
Sylvain96c7c062017-06-15 17:05:23 +02001336 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
1337 return NULL;
1338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (!PyIter_Check(it)) {
1340 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001341 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 it->ob_type->tp_name);
1343 return NULL;
1344 }
1345
1346 res = (*it->ob_type->tp_iternext)(it);
1347 if (res != NULL) {
1348 return res;
1349 } else if (def != NULL) {
1350 if (PyErr_Occurred()) {
1351 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1352 return NULL;
1353 PyErr_Clear();
1354 }
1355 Py_INCREF(def);
1356 return def;
1357 } else if (PyErr_Occurred()) {
1358 return NULL;
1359 } else {
1360 PyErr_SetNone(PyExc_StopIteration);
1361 return NULL;
1362 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001363}
1364
1365PyDoc_STRVAR(next_doc,
1366"next(iterator[, default])\n\
1367\n\
1368Return the next item from the iterator. If default is given and the iterator\n\
1369is exhausted, it is returned instead of raising StopIteration.");
1370
1371
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001372/*[clinic input]
1373setattr as builtin_setattr
1374
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001375 obj: object
1376 name: object
1377 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001378 /
1379
1380Sets the named attribute on the given object to the specified value.
1381
1382setattr(x, 'y', v) is equivalent to ``x.y = v''
1383[clinic start generated code]*/
1384
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001385static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001386builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001387 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001388/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001389{
1390 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001392 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001393}
1394
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001395
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001396/*[clinic input]
1397delattr as builtin_delattr
1398
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001399 obj: object
1400 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001401 /
1402
1403Deletes the named attribute from the given object.
1404
1405delattr(x, 'y') is equivalent to ``del x.y''
1406[clinic start generated code]*/
1407
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001408static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001409builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1410/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001411{
1412 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001414 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001415}
1416
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001417
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001418/*[clinic input]
1419hash as builtin_hash
1420
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001421 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001422 /
1423
1424Return the hash value for the given object.
1425
1426Two objects that compare equal must also have the same hash value, but the
1427reverse is not necessarily true.
1428[clinic start generated code]*/
1429
Guido van Rossum79f25d91997-04-29 20:08:16 +00001430static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001431builtin_hash(PyObject *module, PyObject *obj)
1432/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001433{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001434 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001435
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001436 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (x == -1)
1438 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001439 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001440}
1441
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001442
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001443/*[clinic input]
1444hex as builtin_hex
1445
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001446 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001447 /
1448
1449Return the hexadecimal representation of an integer.
1450
1451 >>> hex(12648430)
1452 '0xc0ffee'
1453[clinic start generated code]*/
1454
Guido van Rossum79f25d91997-04-29 20:08:16 +00001455static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001456builtin_hex(PyObject *module, PyObject *number)
1457/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001458{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001459 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001460}
1461
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001462
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001463/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001464static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001465builtin_iter(PyObject *self, PyObject *args)
1466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1470 return NULL;
1471 if (w == NULL)
1472 return PyObject_GetIter(v);
1473 if (!PyCallable_Check(v)) {
1474 PyErr_SetString(PyExc_TypeError,
1475 "iter(v, w): v must be callable");
1476 return NULL;
1477 }
1478 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001479}
1480
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001481PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001482"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001483iter(callable, sentinel) -> iterator\n\
1484\n\
1485Get an iterator from an object. In the first form, the argument must\n\
1486supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001487In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001488
1489
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001490/*[clinic input]
1491len as builtin_len
1492
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001493 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001494 /
1495
1496Return the number of items in a container.
1497[clinic start generated code]*/
1498
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001499static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001500builtin_len(PyObject *module, PyObject *obj)
1501/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001504
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001505 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001506 if (res < 0) {
1507 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001509 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001511}
1512
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001513
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001514/*[clinic input]
1515locals as builtin_locals
1516
1517Return a dictionary containing the current scope's local variables.
1518
1519NOTE: Whether or not updates to this dictionary will affect name lookups in
1520the local scope and vice-versa is *implementation dependent* and not
1521covered by any backwards compatibility guarantees.
1522[clinic start generated code]*/
1523
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001524static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001525builtin_locals_impl(PyObject *module)
1526/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 d = PyEval_GetLocals();
1531 Py_XINCREF(d);
1532 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001533}
1534
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001535
Guido van Rossum79f25d91997-04-29 20:08:16 +00001536static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001537min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001540 PyObject *emptytuple, *defaultval = NULL;
1541 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001543 const int positional = PyTuple_Size(args) > 1;
1544 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001545
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001546 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001548 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001550
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001551 emptytuple = PyTuple_New(0);
1552 if (emptytuple == NULL)
1553 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001554 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1555 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1556 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001557 Py_DECREF(emptytuple);
1558 if (!ret)
1559 return NULL;
1560
1561 if (positional && defaultval != NULL) {
1562 PyErr_Format(PyExc_TypeError,
1563 "Cannot specify a default for %s() with multiple "
1564 "positional arguments", name);
1565 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 it = PyObject_GetIter(v);
1569 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 return NULL;
1571 }
Tim Petersc3074532001-05-03 07:00:32 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 maxitem = NULL; /* the result */
1574 maxval = NULL; /* the value associated with the result */
1575 while (( item = PyIter_Next(it) )) {
1576 /* get the value from the key function */
1577 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001578 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 if (val == NULL)
1580 goto Fail_it_item;
1581 }
1582 /* no key function; the value is the item */
1583 else {
1584 val = item;
1585 Py_INCREF(val);
1586 }
Tim Petersc3074532001-05-03 07:00:32 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* maximum value and item are unset; set them */
1589 if (maxval == NULL) {
1590 maxitem = item;
1591 maxval = val;
1592 }
1593 /* maximum value and item are set; update them as necessary */
1594 else {
1595 int cmp = PyObject_RichCompareBool(val, maxval, op);
1596 if (cmp < 0)
1597 goto Fail_it_item_and_val;
1598 else if (cmp > 0) {
1599 Py_DECREF(maxval);
1600 Py_DECREF(maxitem);
1601 maxval = val;
1602 maxitem = item;
1603 }
1604 else {
1605 Py_DECREF(item);
1606 Py_DECREF(val);
1607 }
1608 }
1609 }
1610 if (PyErr_Occurred())
1611 goto Fail_it;
1612 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001614 if (defaultval != NULL) {
1615 Py_INCREF(defaultval);
1616 maxitem = defaultval;
1617 } else {
1618 PyErr_Format(PyExc_ValueError,
1619 "%s() arg is an empty sequence", name);
1620 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 }
1622 else
1623 Py_DECREF(maxval);
1624 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001626
1627Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001629Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001631Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 Py_XDECREF(maxval);
1633 Py_XDECREF(maxitem);
1634 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001636}
1637
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001638/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001639static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001640builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001643}
1644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001645PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001646"min(iterable, *[, default=obj, key=func]) -> value\n\
1647min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001648\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001649With a single iterable argument, return its smallest item. The\n\
1650default keyword-only argument specifies an object to return if\n\
1651the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001652With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001653
1654
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001655/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001656static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001657builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001660}
1661
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001662PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001663"max(iterable, *[, default=obj, key=func]) -> value\n\
1664max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001665\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001666With a single iterable argument, return its biggest item. The\n\
1667default keyword-only argument specifies an object to return if\n\
1668the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001669With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001670
1671
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001672/*[clinic input]
1673oct as builtin_oct
1674
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001675 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001676 /
1677
1678Return the octal representation of an integer.
1679
1680 >>> oct(342391)
1681 '0o1234567'
1682[clinic start generated code]*/
1683
Guido van Rossum79f25d91997-04-29 20:08:16 +00001684static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001685builtin_oct(PyObject *module, PyObject *number)
1686/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001687{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001688 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001689}
1690
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001691
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001692/*[clinic input]
1693ord as builtin_ord
1694
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001695 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001696 /
1697
1698Return the Unicode code point for a one-character string.
1699[clinic start generated code]*/
1700
Guido van Rossum79f25d91997-04-29 20:08:16 +00001701static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001702builtin_ord(PyObject *module, PyObject *c)
1703/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 long ord;
1706 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001707
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001708 if (PyBytes_Check(c)) {
1709 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001711 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 return PyLong_FromLong(ord);
1713 }
1714 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001715 else if (PyUnicode_Check(c)) {
1716 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001717 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001718 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001720 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 return PyLong_FromLong(ord);
1722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001724 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001726 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001728 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 return PyLong_FromLong(ord);
1730 }
1731 }
1732 else {
1733 PyErr_Format(PyExc_TypeError,
1734 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001735 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 return NULL;
1737 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 PyErr_Format(PyExc_TypeError,
1740 "ord() expected a character, "
1741 "but string of length %zd found",
1742 size);
1743 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001744}
1745
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001746
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001747/*[clinic input]
1748pow as builtin_pow
1749
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001750 x: object
1751 y: object
1752 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001753 /
1754
1755Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1756
1757Some types, such as ints, are able to use a more efficient algorithm when
1758invoked using the three argument form.
1759[clinic start generated code]*/
1760
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001761static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001762builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1763/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001764{
1765 return PyNumber_Power(x, y, z);
1766}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001767
1768
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001769/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001770static PyObject *
INADA Naokibd584f12017-01-19 12:50:34 +01001771builtin_print(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001772{
INADA Naokibd584f12017-01-19 12:50:34 +01001773 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1774 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001775 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001777
INADA Naokibd584f12017-01-19 12:50:34 +01001778 if (kwnames != NULL &&
1779 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1780 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001781 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001782 }
1783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001785 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001786 if (file == NULL) {
1787 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1788 return NULL;
1789 }
1790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 /* sys.stdout may be None when FILE* stdout isn't connected */
1792 if (file == Py_None)
1793 Py_RETURN_NONE;
1794 }
Guido van Rossum34343512006-11-30 22:13:52 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 if (sep == Py_None) {
1797 sep = NULL;
1798 }
1799 else if (sep && !PyUnicode_Check(sep)) {
1800 PyErr_Format(PyExc_TypeError,
1801 "sep must be None or a string, not %.200s",
1802 sep->ob_type->tp_name);
1803 return NULL;
1804 }
1805 if (end == Py_None) {
1806 end = NULL;
1807 }
1808 else if (end && !PyUnicode_Check(end)) {
1809 PyErr_Format(PyExc_TypeError,
1810 "end must be None or a string, not %.200s",
1811 end->ob_type->tp_name);
1812 return NULL;
1813 }
Guido van Rossum34343512006-11-30 22:13:52 +00001814
INADA Naokibd584f12017-01-19 12:50:34 +01001815 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (i > 0) {
1817 if (sep == NULL)
1818 err = PyFile_WriteString(" ", file);
1819 else
1820 err = PyFile_WriteObject(sep, file,
1821 Py_PRINT_RAW);
1822 if (err)
1823 return NULL;
1824 }
INADA Naokibd584f12017-01-19 12:50:34 +01001825 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 if (err)
1827 return NULL;
1828 }
Guido van Rossum34343512006-11-30 22:13:52 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 if (end == NULL)
1831 err = PyFile_WriteString("\n", file);
1832 else
1833 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1834 if (err)
1835 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001836
Georg Brandlbc3b6822012-01-13 19:41:25 +01001837 if (flush != NULL) {
1838 PyObject *tmp;
1839 int do_flush = PyObject_IsTrue(flush);
1840 if (do_flush == -1)
1841 return NULL;
1842 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001843 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001844 if (tmp == NULL)
1845 return NULL;
1846 else
1847 Py_DECREF(tmp);
1848 }
1849 }
1850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001852}
1853
1854PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001855"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001856\n\
1857Prints the values to a stream, or to sys.stdout by default.\n\
1858Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001859file: a file-like object (stream); defaults to the current sys.stdout.\n\
1860sep: string inserted between values, default a space.\n\
1861end: string appended after the last value, default a newline.\n\
1862flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001863
1864
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001865/*[clinic input]
1866input as builtin_input
1867
1868 prompt: object(c_default="NULL") = None
1869 /
1870
1871Read a string from standard input. The trailing newline is stripped.
1872
1873The prompt string, if given, is printed to standard output without a
1874trailing newline before reading input.
1875
1876If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1877On *nix systems, readline is used if available.
1878[clinic start generated code]*/
1879
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001880static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001881builtin_input_impl(PyObject *module, PyObject *prompt)
1882/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001883{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001884 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1885 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1886 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 PyObject *tmp;
1888 long fd;
1889 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* Check that stdin/out/err are intact */
1892 if (fin == NULL || fin == Py_None) {
1893 PyErr_SetString(PyExc_RuntimeError,
1894 "input(): lost sys.stdin");
1895 return NULL;
1896 }
1897 if (fout == NULL || fout == Py_None) {
1898 PyErr_SetString(PyExc_RuntimeError,
1899 "input(): lost sys.stdout");
1900 return NULL;
1901 }
1902 if (ferr == NULL || ferr == Py_None) {
1903 PyErr_SetString(PyExc_RuntimeError,
1904 "input(): lost sys.stderr");
1905 return NULL;
1906 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001909 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 if (tmp == NULL)
1911 PyErr_Clear();
1912 else
1913 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 /* We should only use (GNU) readline if Python's sys.stdin and
1916 sys.stdout are the same as C's stdin and stdout, because we
1917 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001918 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (tmp == NULL) {
1920 PyErr_Clear();
1921 tty = 0;
1922 }
1923 else {
1924 fd = PyLong_AsLong(tmp);
1925 Py_DECREF(tmp);
1926 if (fd < 0 && PyErr_Occurred())
1927 return NULL;
1928 tty = fd == fileno(stdin) && isatty(fd);
1929 }
1930 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001931 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001932 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001934 tty = 0;
1935 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 else {
1937 fd = PyLong_AsLong(tmp);
1938 Py_DECREF(tmp);
1939 if (fd < 0 && PyErr_Occurred())
1940 return NULL;
1941 tty = fd == fileno(stdout) && isatty(fd);
1942 }
1943 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 /* If we're interactive, use (GNU) readline */
1946 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001947 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001948 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001949 char *s = NULL;
1950 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1951 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001952 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001954 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001955
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001956 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001957 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001958 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001959 if (!stdin_encoding || !stdin_errors ||
1960 !PyUnicode_Check(stdin_encoding) ||
1961 !PyUnicode_Check(stdin_errors)) {
1962 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001963 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001964 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001965 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
1966 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001967 if (!stdin_encoding_str || !stdin_errors_str)
1968 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07001969 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (tmp == NULL)
1971 PyErr_Clear();
1972 else
1973 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001974 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001975 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001976 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001978 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001979 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001980 if (!stdout_encoding || !stdout_errors ||
1981 !PyUnicode_Check(stdout_encoding) ||
1982 !PyUnicode_Check(stdout_errors)) {
1983 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001984 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001985 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001986 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
1987 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001988 if (!stdout_encoding_str || !stdout_errors_str)
1989 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001990 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001991 if (stringpo == NULL)
1992 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001994 stdout_encoding_str, stdout_errors_str);
1995 Py_CLEAR(stdout_encoding);
1996 Py_CLEAR(stdout_errors);
1997 Py_CLEAR(stringpo);
1998 if (po == NULL)
1999 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002000 assert(PyBytes_Check(po));
2001 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 }
2003 else {
2004 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002005 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002007 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002009 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (!PyErr_Occurred())
2011 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002012 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002014
2015 len = strlen(s);
2016 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 PyErr_SetNone(PyExc_EOFError);
2018 result = NULL;
2019 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002020 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (len > PY_SSIZE_T_MAX) {
2022 PyErr_SetString(PyExc_OverflowError,
2023 "input: input too long");
2024 result = NULL;
2025 }
2026 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002027 len--; /* strip trailing '\n' */
2028 if (len != 0 && s[len-1] == '\r')
2029 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002030 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2031 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 }
2033 }
2034 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002035 Py_DECREF(stdin_errors);
2036 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 PyMem_FREE(s);
2038 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002039
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002040 _readline_errors:
2041 Py_XDECREF(stdin_encoding);
2042 Py_XDECREF(stdout_encoding);
2043 Py_XDECREF(stdin_errors);
2044 Py_XDECREF(stdout_errors);
2045 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002046 if (tty)
2047 return NULL;
2048
2049 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002053 if (prompt != NULL) {
2054 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 return NULL;
2056 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002057 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (tmp == NULL)
2059 PyErr_Clear();
2060 else
2061 Py_DECREF(tmp);
2062 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002063}
2064
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002065
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002066/*[clinic input]
2067repr as builtin_repr
2068
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002069 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002070 /
2071
2072Return the canonical string representation of the object.
2073
2074For many object types, including most builtins, eval(repr(obj)) == obj.
2075[clinic start generated code]*/
2076
Guido van Rossum79f25d91997-04-29 20:08:16 +00002077static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002078builtin_repr(PyObject *module, PyObject *obj)
2079/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002080{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002081 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002082}
2083
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002084
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002085/*[clinic input]
2086round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002087
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002088 number: object
2089 ndigits: object = NULL
2090
2091Round a number to a given precision in decimal digits.
2092
2093The return value is an integer if ndigits is omitted or None. Otherwise
2094the return value has the same type as the number. ndigits may be negative.
2095[clinic start generated code]*/
2096
2097static PyObject *
2098builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2099/*[clinic end generated code: output=ff0d9dd176c02ede input=854bc3a217530c3d]*/
2100{
2101 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 if (Py_TYPE(number)->tp_dict == NULL) {
2104 if (PyType_Ready(Py_TYPE(number)) < 0)
2105 return NULL;
2106 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002107
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002108 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002110 if (!PyErr_Occurred())
2111 PyErr_Format(PyExc_TypeError,
2112 "type %.100s doesn't define __round__ method",
2113 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 return NULL;
2115 }
Alex Martelliae211f92007-08-22 23:21:33 +00002116
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002117 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002118 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002120 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002121 Py_DECREF(round);
2122 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002123}
2124
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002125
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002126/*AC: we need to keep the kwds dict intact to easily call into the
2127 * list.sort method, which isn't currently supported in AC. So we just use
2128 * the initially generated signature with a custom implementation.
2129 */
2130/* [disabled clinic input]
2131sorted as builtin_sorted
2132
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002133 iterable as seq: object
2134 key as keyfunc: object = None
2135 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002136
2137Return a new list containing all items from the iterable in ascending order.
2138
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002139A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002140reverse flag can be set to request the result in descending order.
2141[end disabled clinic input]*/
2142
2143PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002144"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002145"--\n"
2146"\n"
2147"Return a new list containing all items from the iterable in ascending order.\n"
2148"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002149"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002150"reverse flag can be set to request the result in descending order.");
2151
2152#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002153 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002154
Raymond Hettinger64958a12003-12-17 20:43:33 +00002155static PyObject *
Victor Stinner5a60eca2017-01-17 15:17:49 +01002156builtin_sorted(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002157{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002158 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002159
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002160 /* Keyword arguments are passed through list.sort() which will check
2161 them. */
2162 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 newlist = PySequence_List(seq);
2166 if (newlist == NULL)
2167 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002168
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002169 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (callable == NULL) {
2171 Py_DECREF(newlist);
2172 return NULL;
2173 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002174
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002175 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002176 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 Py_DECREF(callable);
2178 if (v == NULL) {
2179 Py_DECREF(newlist);
2180 return NULL;
2181 }
2182 Py_DECREF(v);
2183 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002184}
2185
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002186
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002187/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002188static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002189builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 PyObject *v = NULL;
2192 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2195 return NULL;
2196 if (v == NULL) {
2197 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002198 if (d == NULL)
2199 return NULL;
2200 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 }
2202 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002203 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 if (d == NULL) {
2205 PyErr_SetString(PyExc_TypeError,
2206 "vars() argument must have __dict__ attribute");
2207 return NULL;
2208 }
2209 }
2210 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002211}
2212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002213PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002214"vars([object]) -> dictionary\n\
2215\n\
2216Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002217With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002218
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002219
2220/*[clinic input]
2221sum as builtin_sum
2222
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002223 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002224 start: object(c_default="NULL") = 0
2225 /
2226
2227Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2228
2229When the iterable is empty, return the start value.
2230This function is intended specifically for use with numeric values and may
2231reject non-numeric types.
2232[clinic start generated code]*/
2233
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002235builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2236/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002237{
2238 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002240
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002241 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 if (iter == NULL)
2243 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 if (result == NULL) {
2246 result = PyLong_FromLong(0);
2247 if (result == NULL) {
2248 Py_DECREF(iter);
2249 return NULL;
2250 }
2251 } else {
2252 /* reject string values for 'start' parameter */
2253 if (PyUnicode_Check(result)) {
2254 PyErr_SetString(PyExc_TypeError,
2255 "sum() can't sum strings [use ''.join(seq) instead]");
2256 Py_DECREF(iter);
2257 return NULL;
2258 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002259 if (PyBytes_Check(result)) {
2260 PyErr_SetString(PyExc_TypeError,
2261 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002262 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002263 return NULL;
2264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (PyByteArray_Check(result)) {
2266 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002267 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 Py_DECREF(iter);
2269 return NULL;
2270 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 Py_INCREF(result);
2272 }
Alex Martellia70b1912003-04-22 08:12:33 +00002273
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002274#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2276 Assumes all inputs are the same type. If the assumption fails, default
2277 to the more general routine.
2278 */
2279 if (PyLong_CheckExact(result)) {
2280 int overflow;
2281 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2282 /* If this already overflowed, don't even enter the loop. */
2283 if (overflow == 0) {
2284 Py_DECREF(result);
2285 result = NULL;
2286 }
2287 while(result == NULL) {
2288 item = PyIter_Next(iter);
2289 if (item == NULL) {
2290 Py_DECREF(iter);
2291 if (PyErr_Occurred())
2292 return NULL;
2293 return PyLong_FromLong(i_result);
2294 }
2295 if (PyLong_CheckExact(item)) {
2296 long b = PyLong_AsLongAndOverflow(item, &overflow);
2297 long x = i_result + b;
2298 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2299 i_result = x;
2300 Py_DECREF(item);
2301 continue;
2302 }
2303 }
2304 /* Either overflowed or is not an int. Restore real objects and process normally */
2305 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002306 if (result == NULL) {
2307 Py_DECREF(item);
2308 Py_DECREF(iter);
2309 return NULL;
2310 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 temp = PyNumber_Add(result, item);
2312 Py_DECREF(result);
2313 Py_DECREF(item);
2314 result = temp;
2315 if (result == NULL) {
2316 Py_DECREF(iter);
2317 return NULL;
2318 }
2319 }
2320 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 if (PyFloat_CheckExact(result)) {
2323 double f_result = PyFloat_AS_DOUBLE(result);
2324 Py_DECREF(result);
2325 result = NULL;
2326 while(result == NULL) {
2327 item = PyIter_Next(iter);
2328 if (item == NULL) {
2329 Py_DECREF(iter);
2330 if (PyErr_Occurred())
2331 return NULL;
2332 return PyFloat_FromDouble(f_result);
2333 }
2334 if (PyFloat_CheckExact(item)) {
2335 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2336 f_result += PyFloat_AS_DOUBLE(item);
2337 PyFPE_END_PROTECT(f_result)
2338 Py_DECREF(item);
2339 continue;
2340 }
2341 if (PyLong_CheckExact(item)) {
2342 long value;
2343 int overflow;
2344 value = PyLong_AsLongAndOverflow(item, &overflow);
2345 if (!overflow) {
2346 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2347 f_result += (double)value;
2348 PyFPE_END_PROTECT(f_result)
2349 Py_DECREF(item);
2350 continue;
2351 }
2352 }
2353 result = PyFloat_FromDouble(f_result);
2354 temp = PyNumber_Add(result, item);
2355 Py_DECREF(result);
2356 Py_DECREF(item);
2357 result = temp;
2358 if (result == NULL) {
2359 Py_DECREF(iter);
2360 return NULL;
2361 }
2362 }
2363 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002364#endif
2365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 for(;;) {
2367 item = PyIter_Next(iter);
2368 if (item == NULL) {
2369 /* error, or end-of-sequence */
2370 if (PyErr_Occurred()) {
2371 Py_DECREF(result);
2372 result = NULL;
2373 }
2374 break;
2375 }
2376 /* It's tempting to use PyNumber_InPlaceAdd instead of
2377 PyNumber_Add here, to avoid quadratic running time
2378 when doing 'sum(list_of_lists, [])'. However, this
2379 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 empty = []
2382 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 would change the value of empty. */
2385 temp = PyNumber_Add(result, item);
2386 Py_DECREF(result);
2387 Py_DECREF(item);
2388 result = temp;
2389 if (result == NULL)
2390 break;
2391 }
2392 Py_DECREF(iter);
2393 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002394}
2395
Alex Martellia70b1912003-04-22 08:12:33 +00002396
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002397/*[clinic input]
2398isinstance as builtin_isinstance
2399
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002400 obj: object
2401 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002402 /
2403
2404Return whether an object is an instance of a class or of a subclass thereof.
2405
2406A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2407check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2408or ...`` etc.
2409[clinic start generated code]*/
2410
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002411static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002412builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002413 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002414/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002417
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002418 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (retval < 0)
2420 return NULL;
2421 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002422}
2423
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002424
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002425/*[clinic input]
2426issubclass as builtin_issubclass
2427
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002428 cls: object
2429 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002430 /
2431
2432Return whether 'cls' is a derived from another class or is the same class.
2433
2434A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2435check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2436or ...`` etc.
2437[clinic start generated code]*/
2438
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002439static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002440builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002441 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002442/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002445
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002446 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 if (retval < 0)
2448 return NULL;
2449 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002450}
2451
2452
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002453typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 PyObject_HEAD
2455 Py_ssize_t tuplesize;
2456 PyObject *ittuple; /* tuple of iterators */
2457 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002458} zipobject;
2459
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002460static PyObject *
2461zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 zipobject *lz;
2464 Py_ssize_t i;
2465 PyObject *ittuple; /* tuple of iterators */
2466 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002467 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002468
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002469 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* args must be a tuple */
2473 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002474 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* obtain iterators */
2477 ittuple = PyTuple_New(tuplesize);
2478 if (ittuple == NULL)
2479 return NULL;
2480 for (i=0; i < tuplesize; ++i) {
2481 PyObject *item = PyTuple_GET_ITEM(args, i);
2482 PyObject *it = PyObject_GetIter(item);
2483 if (it == NULL) {
2484 if (PyErr_ExceptionMatches(PyExc_TypeError))
2485 PyErr_Format(PyExc_TypeError,
2486 "zip argument #%zd must support iteration",
2487 i+1);
2488 Py_DECREF(ittuple);
2489 return NULL;
2490 }
2491 PyTuple_SET_ITEM(ittuple, i, it);
2492 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* create a result holder */
2495 result = PyTuple_New(tuplesize);
2496 if (result == NULL) {
2497 Py_DECREF(ittuple);
2498 return NULL;
2499 }
2500 for (i=0 ; i < tuplesize ; i++) {
2501 Py_INCREF(Py_None);
2502 PyTuple_SET_ITEM(result, i, Py_None);
2503 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 /* create zipobject structure */
2506 lz = (zipobject *)type->tp_alloc(type, 0);
2507 if (lz == NULL) {
2508 Py_DECREF(ittuple);
2509 Py_DECREF(result);
2510 return NULL;
2511 }
2512 lz->ittuple = ittuple;
2513 lz->tuplesize = tuplesize;
2514 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002517}
2518
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002519static void
2520zip_dealloc(zipobject *lz)
2521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 PyObject_GC_UnTrack(lz);
2523 Py_XDECREF(lz->ittuple);
2524 Py_XDECREF(lz->result);
2525 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002526}
2527
2528static int
2529zip_traverse(zipobject *lz, visitproc visit, void *arg)
2530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 Py_VISIT(lz->ittuple);
2532 Py_VISIT(lz->result);
2533 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002534}
2535
2536static PyObject *
2537zip_next(zipobject *lz)
2538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 Py_ssize_t i;
2540 Py_ssize_t tuplesize = lz->tuplesize;
2541 PyObject *result = lz->result;
2542 PyObject *it;
2543 PyObject *item;
2544 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 if (tuplesize == 0)
2547 return NULL;
2548 if (Py_REFCNT(result) == 1) {
2549 Py_INCREF(result);
2550 for (i=0 ; i < tuplesize ; i++) {
2551 it = PyTuple_GET_ITEM(lz->ittuple, i);
2552 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002553 if (item == NULL) {
2554 Py_DECREF(result);
2555 return NULL;
2556 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 olditem = PyTuple_GET_ITEM(result, i);
2558 PyTuple_SET_ITEM(result, i, item);
2559 Py_DECREF(olditem);
2560 }
2561 } else {
2562 result = PyTuple_New(tuplesize);
2563 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002564 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 for (i=0 ; i < tuplesize ; i++) {
2566 it = PyTuple_GET_ITEM(lz->ittuple, i);
2567 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002568 if (item == NULL) {
2569 Py_DECREF(result);
2570 return NULL;
2571 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 PyTuple_SET_ITEM(result, i, item);
2573 }
2574 }
2575 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002576}
Barry Warsawbd599b52000-08-03 15:45:29 +00002577
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002578static PyObject *
2579zip_reduce(zipobject *lz)
2580{
2581 /* Just recreate the zip with the internal iterator tuple */
2582 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2583}
2584
2585static PyMethodDef zip_methods[] = {
2586 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2587 {NULL, NULL} /* sentinel */
2588};
2589
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002590PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002591"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002592\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002593Return a zip object whose .__next__() method returns a tuple where\n\
2594the i-th element comes from the i-th iterable argument. The .__next__()\n\
2595method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002596is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002597
2598PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2600 "zip", /* tp_name */
2601 sizeof(zipobject), /* tp_basicsize */
2602 0, /* tp_itemsize */
2603 /* methods */
2604 (destructor)zip_dealloc, /* tp_dealloc */
2605 0, /* tp_print */
2606 0, /* tp_getattr */
2607 0, /* tp_setattr */
2608 0, /* tp_reserved */
2609 0, /* tp_repr */
2610 0, /* tp_as_number */
2611 0, /* tp_as_sequence */
2612 0, /* tp_as_mapping */
2613 0, /* tp_hash */
2614 0, /* tp_call */
2615 0, /* tp_str */
2616 PyObject_GenericGetAttr, /* tp_getattro */
2617 0, /* tp_setattro */
2618 0, /* tp_as_buffer */
2619 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2620 Py_TPFLAGS_BASETYPE, /* tp_flags */
2621 zip_doc, /* tp_doc */
2622 (traverseproc)zip_traverse, /* tp_traverse */
2623 0, /* tp_clear */
2624 0, /* tp_richcompare */
2625 0, /* tp_weaklistoffset */
2626 PyObject_SelfIter, /* tp_iter */
2627 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002628 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 0, /* tp_members */
2630 0, /* tp_getset */
2631 0, /* tp_base */
2632 0, /* tp_dict */
2633 0, /* tp_descr_get */
2634 0, /* tp_descr_set */
2635 0, /* tp_dictoffset */
2636 0, /* tp_init */
2637 PyType_GenericAlloc, /* tp_alloc */
2638 zip_new, /* tp_new */
2639 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002640};
Barry Warsawbd599b52000-08-03 15:45:29 +00002641
2642
Guido van Rossum79f25d91997-04-29 20:08:16 +00002643static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 {"__build_class__", (PyCFunction)builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002645 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002647 BUILTIN_ABS_METHODDEF
2648 BUILTIN_ALL_METHODDEF
2649 BUILTIN_ANY_METHODDEF
2650 BUILTIN_ASCII_METHODDEF
2651 BUILTIN_BIN_METHODDEF
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002652 {"breakpoint", (PyCFunction)builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002653 BUILTIN_CALLABLE_METHODDEF
2654 BUILTIN_CHR_METHODDEF
2655 BUILTIN_COMPILE_METHODDEF
2656 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002658 BUILTIN_DIVMOD_METHODDEF
2659 BUILTIN_EVAL_METHODDEF
2660 BUILTIN_EXEC_METHODDEF
2661 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002662 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002663 BUILTIN_GLOBALS_METHODDEF
2664 BUILTIN_HASATTR_METHODDEF
2665 BUILTIN_HASH_METHODDEF
2666 BUILTIN_HEX_METHODDEF
2667 BUILTIN_ID_METHODDEF
2668 BUILTIN_INPUT_METHODDEF
2669 BUILTIN_ISINSTANCE_METHODDEF
2670 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002672 BUILTIN_LEN_METHODDEF
2673 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2675 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002676 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002677 BUILTIN_OCT_METHODDEF
2678 BUILTIN_ORD_METHODDEF
2679 BUILTIN_POW_METHODDEF
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002680 {"print", (PyCFunction)builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002681 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002682 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002683 BUILTIN_SETATTR_METHODDEF
2684 BUILTIN_SORTED_METHODDEF
2685 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2687 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002688};
2689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002690PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002691"Built-in functions, exceptions, and other objects.\n\
2692\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002693Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002694
Martin v. Löwis1a214512008-06-11 05:26:20 +00002695static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 PyModuleDef_HEAD_INIT,
2697 "builtins",
2698 builtin_doc,
2699 -1, /* multiple "initialization" just copies the module dict. */
2700 builtin_methods,
2701 NULL,
2702 NULL,
2703 NULL,
2704 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002705};
2706
2707
Guido van Rossum25ce5661997-08-02 03:10:38 +00002708PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002709_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002712
2713 if (PyType_Ready(&PyFilter_Type) < 0 ||
2714 PyType_Ready(&PyMap_Type) < 0 ||
2715 PyType_Ready(&PyZip_Type) < 0)
2716 return NULL;
2717
Eric Snowd393c1b2017-09-14 12:18:12 -06002718 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 if (mod == NULL)
2720 return NULL;
2721 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002722
Tim Peters7571a0f2003-03-23 17:52:28 +00002723#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 /* "builtins" exposes a number of statically allocated objects
2725 * that, before this code was added in 2.3, never showed up in
2726 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2727 * result, programs leaking references to None and False (etc)
2728 * couldn't be diagnosed by examining sys.getobjects(0).
2729 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002730#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2731#else
2732#define ADD_TO_ALL(OBJECT) (void)0
2733#endif
2734
Tim Peters4b7625e2001-09-13 21:37:17 +00002735#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2737 return NULL; \
2738 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 SETBUILTIN("None", Py_None);
2741 SETBUILTIN("Ellipsis", Py_Ellipsis);
2742 SETBUILTIN("NotImplemented", Py_NotImplemented);
2743 SETBUILTIN("False", Py_False);
2744 SETBUILTIN("True", Py_True);
2745 SETBUILTIN("bool", &PyBool_Type);
2746 SETBUILTIN("memoryview", &PyMemoryView_Type);
2747 SETBUILTIN("bytearray", &PyByteArray_Type);
2748 SETBUILTIN("bytes", &PyBytes_Type);
2749 SETBUILTIN("classmethod", &PyClassMethod_Type);
2750 SETBUILTIN("complex", &PyComplex_Type);
2751 SETBUILTIN("dict", &PyDict_Type);
2752 SETBUILTIN("enumerate", &PyEnum_Type);
2753 SETBUILTIN("filter", &PyFilter_Type);
2754 SETBUILTIN("float", &PyFloat_Type);
2755 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2756 SETBUILTIN("property", &PyProperty_Type);
2757 SETBUILTIN("int", &PyLong_Type);
2758 SETBUILTIN("list", &PyList_Type);
2759 SETBUILTIN("map", &PyMap_Type);
2760 SETBUILTIN("object", &PyBaseObject_Type);
2761 SETBUILTIN("range", &PyRange_Type);
2762 SETBUILTIN("reversed", &PyReversed_Type);
2763 SETBUILTIN("set", &PySet_Type);
2764 SETBUILTIN("slice", &PySlice_Type);
2765 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2766 SETBUILTIN("str", &PyUnicode_Type);
2767 SETBUILTIN("super", &PySuper_Type);
2768 SETBUILTIN("tuple", &PyTuple_Type);
2769 SETBUILTIN("type", &PyType_Type);
2770 SETBUILTIN("zip", &PyZip_Type);
2771 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2772 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002773 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 return NULL;
2775 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002776 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002779#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002780#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002781}