blob: 6215a638c94b71b2f3cdc0ab3895bdb1da957dd8 [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";
Mark Hammondef8b6542001-05-13 08:04:26 +000032
Victor Stinnerbd303c12013-11-07 23:07:29 +010033_Py_IDENTIFIER(__builtins__);
34_Py_IDENTIFIER(__dict__);
35_Py_IDENTIFIER(__prepare__);
36_Py_IDENTIFIER(__round__);
37_Py_IDENTIFIER(encoding);
38_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020039_Py_IDENTIFIER(fileno);
40_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010041_Py_IDENTIFIER(metaclass);
42_Py_IDENTIFIER(sort);
43_Py_IDENTIFIER(stdin);
44_Py_IDENTIFIER(stdout);
45_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020046
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030047#include "clinic/bltinmodule.c.h"
48
Nick Coghlanf9e227e2014-08-17 14:01:19 +100049/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000050static PyObject *
Victor Stinner773dc6d2017-01-16 23:46:26 +010051builtin___build_class__(PyObject *self, PyObject **args, Py_ssize_t nargs,
52 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +000053{
Nick Coghlan19d24672016-12-05 16:47:55 +100054 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns;
55 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010056 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (nargs < 2) {
59 PyErr_SetString(PyExc_TypeError,
60 "__build_class__: not enough arguments");
61 return NULL;
62 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010063 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050064 if (!PyFunction_Check(func)) {
65 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050066 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050067 return NULL;
68 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010069 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 if (!PyUnicode_Check(name)) {
71 PyErr_SetString(PyExc_TypeError,
72 "__build_class__: name is not a string");
73 return NULL;
74 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010075 bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 if (bases == NULL)
77 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000078
Victor Stinner773dc6d2017-01-16 23:46:26 +010079 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 meta = NULL;
81 mkw = NULL;
82 }
83 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +010084 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 if (mkw == NULL) {
86 Py_DECREF(bases);
87 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000088 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010089
Victor Stinnerae9f1612013-11-06 22:46:51 +010090 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 if (meta != NULL) {
92 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010093 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 Py_DECREF(meta);
95 Py_DECREF(mkw);
96 Py_DECREF(bases);
97 return NULL;
98 }
Nick Coghlande31b192011-10-23 22:04:16 +100099 /* metaclass is explicitly given, check if it's indeed a class */
100 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 }
102 }
103 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000104 /* if there are no bases, use type: */
105 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000107 }
108 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 else {
110 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
111 meta = (PyObject *) (base0->ob_type);
112 }
113 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000114 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000116
Nick Coghlande31b192011-10-23 22:04:16 +1000117 if (isclass) {
118 /* meta is really a class, so check for a more derived
119 metaclass, or possible metaclass conflicts: */
120 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
121 bases);
122 if (winner == NULL) {
123 Py_DECREF(meta);
124 Py_XDECREF(mkw);
125 Py_DECREF(bases);
126 return NULL;
127 }
128 if (winner != meta) {
129 Py_DECREF(meta);
130 meta = winner;
131 Py_INCREF(meta);
132 }
133 }
134 /* else: meta is not a class, so we cannot do the metaclass
135 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200136 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (prep == NULL) {
138 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
139 PyErr_Clear();
Eric Snow4f29e752016-09-08 15:11:11 -0700140 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 }
142 else {
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return NULL;
147 }
148 }
149 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200150 PyObject *pargs[2] = {name, bases};
151 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_DECREF(prep);
153 }
154 if (ns == NULL) {
155 Py_DECREF(meta);
156 Py_XDECREF(mkw);
157 Py_DECREF(bases);
158 return NULL;
159 }
Oren Milman5837d042017-09-27 17:04:37 +0300160 if (!PyMapping_Check(ns)) {
161 PyErr_Format(PyExc_TypeError,
162 "%.200s.__prepare__() must return a mapping, not %.200s",
163 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
164 Py_TYPE(ns)->tp_name);
165 goto error;
166 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000167 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500168 NULL, 0, NULL, 0, NULL, 0, NULL,
169 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000170 if (cell != NULL) {
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200171 PyObject *margs[3] = {name, bases, ns};
172 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000173 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
174 PyObject *cell_cls = PyCell_GET(cell);
175 if (cell_cls != cls) {
176 /* TODO: In 3.7, DeprecationWarning will become RuntimeError.
177 * At that point, cell_error won't be needed.
178 */
179 int cell_error;
180 if (cell_cls == NULL) {
181 const char *msg =
182 "__class__ not set defining %.200R as %.200R. "
183 "Was __classcell__ propagated to type.__new__?";
184 cell_error = PyErr_WarnFormat(
185 PyExc_DeprecationWarning, 1, msg, name, cls);
186 } else {
187 const char *msg =
188 "__class__ set to %.200R defining %.200R as %.200R";
189 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
190 cell_error = 1;
191 }
192 if (cell_error) {
193 Py_DECREF(cls);
194 cls = NULL;
195 goto error;
196 } else {
197 /* Fill in the cell, since type.__new__ didn't do it */
198 PyCell_Set(cell, cls);
199 }
200 }
201 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000203error:
204 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 Py_DECREF(ns);
206 Py_DECREF(meta);
207 Py_XDECREF(mkw);
208 Py_DECREF(bases);
209 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000210}
211
212PyDoc_STRVAR(build_class_doc,
213"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
214\n\
215Internal helper function used by the class statement.");
216
217static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
221 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400222 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400223 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000224
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400225 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 kwlist, &name, &globals, &locals, &fromlist, &level))
227 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400228 return PyImport_ImportModuleLevelObject(name, globals, locals,
229 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000230}
231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000232PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400233"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000234\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000235Import a module. Because this function is meant for use by the Python\n\
236interpreter and not for general use it is better to use\n\
237importlib.import_module() to programmatically import a module.\n\
238\n\
239The globals argument is only used to determine the context;\n\
240they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000241should be a list of names to emulate ``from name import ...'', or an\n\
242empty list to emulate ``import name''.\n\
243When importing a module from a package, note that __import__('A.B', ...)\n\
244returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000245fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400246absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000247is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000248
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000249
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000250/*[clinic input]
251abs as builtin_abs
252
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300253 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000254 /
255
256Return the absolute value of the argument.
257[clinic start generated code]*/
258
Guido van Rossum79f25d91997-04-29 20:08:16 +0000259static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300260builtin_abs(PyObject *module, PyObject *x)
261/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000262{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000263 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000264}
265
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000266/*[clinic input]
267all as builtin_all
268
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300269 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000270 /
271
272Return True if bool(x) is True for all values x in the iterable.
273
274If the iterable is empty, return True.
275[clinic start generated code]*/
276
Raymond Hettinger96229b12005-03-11 06:49:40 +0000277static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300278builtin_all(PyObject *module, PyObject *iterable)
279/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyObject *it, *item;
282 PyObject *(*iternext)(PyObject *);
283 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000284
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000285 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 if (it == NULL)
287 return NULL;
288 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 for (;;) {
291 item = iternext(it);
292 if (item == NULL)
293 break;
294 cmp = PyObject_IsTrue(item);
295 Py_DECREF(item);
296 if (cmp < 0) {
297 Py_DECREF(it);
298 return NULL;
299 }
300 if (cmp == 0) {
301 Py_DECREF(it);
302 Py_RETURN_FALSE;
303 }
304 }
305 Py_DECREF(it);
306 if (PyErr_Occurred()) {
307 if (PyErr_ExceptionMatches(PyExc_StopIteration))
308 PyErr_Clear();
309 else
310 return NULL;
311 }
312 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000313}
314
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000315/*[clinic input]
316any as builtin_any
317
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300318 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000319 /
320
321Return True if bool(x) is True for any x in the iterable.
322
323If the iterable is empty, return False.
324[clinic start generated code]*/
325
Raymond Hettinger96229b12005-03-11 06:49:40 +0000326static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300327builtin_any(PyObject *module, PyObject *iterable)
328/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 PyObject *it, *item;
331 PyObject *(*iternext)(PyObject *);
332 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000333
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000334 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (it == NULL)
336 return NULL;
337 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 for (;;) {
340 item = iternext(it);
341 if (item == NULL)
342 break;
343 cmp = PyObject_IsTrue(item);
344 Py_DECREF(item);
345 if (cmp < 0) {
346 Py_DECREF(it);
347 return NULL;
348 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400349 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 Py_DECREF(it);
351 Py_RETURN_TRUE;
352 }
353 }
354 Py_DECREF(it);
355 if (PyErr_Occurred()) {
356 if (PyErr_ExceptionMatches(PyExc_StopIteration))
357 PyErr_Clear();
358 else
359 return NULL;
360 }
361 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000362}
363
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000364/*[clinic input]
365ascii as builtin_ascii
366
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300367 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000368 /
369
370Return an ASCII-only representation of an object.
371
372As repr(), return a string containing a printable representation of an
373object, but escape the non-ASCII characters in the string returned by
374repr() using \\x, \\u or \\U escapes. This generates a string similar
375to that returned by repr() in Python 2.
376[clinic start generated code]*/
377
Georg Brandl559e5d72008-06-11 18:37:52 +0000378static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300379builtin_ascii(PyObject *module, PyObject *obj)
380/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000381{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000382 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000383}
384
Georg Brandl559e5d72008-06-11 18:37:52 +0000385
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000386/*[clinic input]
387bin as builtin_bin
388
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300389 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000390 /
391
392Return the binary representation of an integer.
393
394 >>> bin(2796202)
395 '0b1010101010101010101010'
396[clinic start generated code]*/
397
Guido van Rossum79f25d91997-04-29 20:08:16 +0000398static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300399builtin_bin(PyObject *module, PyObject *number)
400/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000401{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000402 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000403}
404
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000405
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000406/*[clinic input]
407callable as builtin_callable
408
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300409 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000410 /
411
412Return whether the object is callable (i.e., some kind of function).
413
414Note that classes are callable, as are instances of classes with a
415__call__() method.
416[clinic start generated code]*/
417
Antoine Pitroue71362d2010-11-27 22:00:11 +0000418static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300419builtin_callable(PyObject *module, PyObject *obj)
420/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000421{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000422 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000423}
424
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400425static PyObject *
426builtin_breakpoint(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *keywords)
427{
428 PyObject *hook = PySys_GetObject("breakpointhook");
429
430 if (hook == NULL) {
431 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
432 return NULL;
433 }
434 Py_INCREF(hook);
435 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
436 Py_DECREF(hook);
437 return retval;
438}
439
440PyDoc_STRVAR(breakpoint_doc,
441"breakpoint(*args, **kws)\n\
442\n\
443Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
444whatever arguments are passed.\n\
445\n\
446By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000447
Raymond Hettinger17301e92008-03-13 00:19:26 +0000448typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 PyObject_HEAD
450 PyObject *func;
451 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000452} filterobject;
453
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000454static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000455filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 PyObject *func, *seq;
458 PyObject *it;
459 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000460
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300461 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
465 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* Get iterator. */
468 it = PyObject_GetIter(seq);
469 if (it == NULL)
470 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 /* create filterobject structure */
473 lz = (filterobject *)type->tp_alloc(type, 0);
474 if (lz == NULL) {
475 Py_DECREF(it);
476 return NULL;
477 }
478 Py_INCREF(func);
479 lz->func = func;
480 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000483}
484
485static void
486filter_dealloc(filterobject *lz)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 PyObject_GC_UnTrack(lz);
489 Py_XDECREF(lz->func);
490 Py_XDECREF(lz->it);
491 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000492}
493
494static int
495filter_traverse(filterobject *lz, visitproc visit, void *arg)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 Py_VISIT(lz->it);
498 Py_VISIT(lz->func);
499 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000500}
501
502static PyObject *
503filter_next(filterobject *lz)
504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 PyObject *item;
506 PyObject *it = lz->it;
507 long ok;
508 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400509 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 iternext = *Py_TYPE(it)->tp_iternext;
512 for (;;) {
513 item = iternext(it);
514 if (item == NULL)
515 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000516
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400517 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 ok = PyObject_IsTrue(item);
519 } else {
520 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100521 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (good == NULL) {
523 Py_DECREF(item);
524 return NULL;
525 }
526 ok = PyObject_IsTrue(good);
527 Py_DECREF(good);
528 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200529 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return item;
531 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200532 if (ok < 0)
533 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000535}
536
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000537static PyObject *
538filter_reduce(filterobject *lz)
539{
540 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
541}
542
543PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
544
545static PyMethodDef filter_methods[] = {
546 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
547 {NULL, NULL} /* sentinel */
548};
549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000550PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000551"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000552\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000553Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000554is true. If function is None, return the items that are true.");
555
556PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 PyVarObject_HEAD_INIT(&PyType_Type, 0)
558 "filter", /* tp_name */
559 sizeof(filterobject), /* tp_basicsize */
560 0, /* tp_itemsize */
561 /* methods */
562 (destructor)filter_dealloc, /* tp_dealloc */
563 0, /* tp_print */
564 0, /* tp_getattr */
565 0, /* tp_setattr */
566 0, /* tp_reserved */
567 0, /* tp_repr */
568 0, /* tp_as_number */
569 0, /* tp_as_sequence */
570 0, /* tp_as_mapping */
571 0, /* tp_hash */
572 0, /* tp_call */
573 0, /* tp_str */
574 PyObject_GenericGetAttr, /* tp_getattro */
575 0, /* tp_setattro */
576 0, /* tp_as_buffer */
577 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
578 Py_TPFLAGS_BASETYPE, /* tp_flags */
579 filter_doc, /* tp_doc */
580 (traverseproc)filter_traverse, /* tp_traverse */
581 0, /* tp_clear */
582 0, /* tp_richcompare */
583 0, /* tp_weaklistoffset */
584 PyObject_SelfIter, /* tp_iter */
585 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000586 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 0, /* tp_members */
588 0, /* tp_getset */
589 0, /* tp_base */
590 0, /* tp_dict */
591 0, /* tp_descr_get */
592 0, /* tp_descr_set */
593 0, /* tp_dictoffset */
594 0, /* tp_init */
595 PyType_GenericAlloc, /* tp_alloc */
596 filter_new, /* tp_new */
597 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000598};
599
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000600
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000601/*[clinic input]
602format as builtin_format
603
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300604 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000605 format_spec: unicode(c_default="NULL") = ''
606 /
607
608Return value.__format__(format_spec)
609
Amit Kumar2e6bb442017-05-29 06:32:26 +0530610format_spec defaults to the empty string.
611See the Format Specification Mini-Language section of help('FORMATTING') for
612details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000613[clinic start generated code]*/
614
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000615static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300616builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530617/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000618{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000619 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000620}
621
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000622/*[clinic input]
623chr as builtin_chr
624
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300625 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000626 /
627
628Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
629[clinic start generated code]*/
630
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000631static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300632builtin_chr_impl(PyObject *module, int i)
633/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000634{
635 return PyUnicode_FromOrdinal(i);
636}
Guido van Rossum09095f32000-03-10 23:00:52 +0000637
638
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200639static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000640source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000641{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200642 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000644 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000645
Martin Pantereeb896c2015-11-07 02:32:21 +0000646 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (PyUnicode_Check(cmd)) {
648 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200649 str = PyUnicode_AsUTF8AndSize(cmd, &size);
650 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return NULL;
652 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000653 else if (PyBytes_Check(cmd)) {
654 str = PyBytes_AS_STRING(cmd);
655 size = PyBytes_GET_SIZE(cmd);
656 }
657 else if (PyByteArray_Check(cmd)) {
658 str = PyByteArray_AS_STRING(cmd);
659 size = PyByteArray_GET_SIZE(cmd);
660 }
661 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
662 /* Copy to NUL-terminated buffer. */
663 *cmd_copy = PyBytes_FromStringAndSize(
664 (const char *)view.buf, view.len);
665 PyBuffer_Release(&view);
666 if (*cmd_copy == NULL) {
667 return NULL;
668 }
669 str = PyBytes_AS_STRING(*cmd_copy);
670 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200671 }
672 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyErr_Format(PyExc_TypeError,
674 "%s() arg 1 must be a %s object",
675 funcname, what);
676 return NULL;
677 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200678
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200679 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300680 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000682 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 return NULL;
684 }
685 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000686}
687
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000688/*[clinic input]
689compile as builtin_compile
690
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300691 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000692 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300693 mode: str
694 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200695 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300696 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000697
698Compile source into a code object that can be executed by exec() or eval().
699
700The source code may represent a Python module, statement or expression.
701The filename will be used for run-time error messages.
702The mode must be 'exec' to compile a module, 'single' to compile a
703single (interactive) statement, or 'eval' to compile an expression.
704The flags argument, if present, controls which future statements influence
705the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300706The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000707the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300708compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000709in addition to any features explicitly specified.
710[clinic start generated code]*/
711
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000712static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300713builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
714 const char *mode, int flags, int dont_inherit,
715 int optimize)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200716/*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000717{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000718 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200719 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000720 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 int is_ast;
722 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000724 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000725
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000726 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000727
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000728 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
730 {
731 PyErr_SetString(PyExc_ValueError,
732 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000733 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 }
735 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000736
Georg Brandl8334fd92010-12-04 10:26:46 +0000737 if (optimize < -1 || optimize > 2) {
738 PyErr_SetString(PyExc_ValueError,
739 "compile(): invalid optimize value");
740 goto error;
741 }
742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (!dont_inherit) {
744 PyEval_MergeCompilerFlags(&cf);
745 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000746
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000747 if (strcmp(mode, "exec") == 0)
748 compile_mode = 0;
749 else if (strcmp(mode, "eval") == 0)
750 compile_mode = 1;
751 else if (strcmp(mode, "single") == 0)
752 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 else {
754 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000755 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000756 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000758
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000759 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000761 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000763 if (flags & PyCF_ONLY_AST) {
764 Py_INCREF(source);
765 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 }
767 else {
768 PyArena *arena;
769 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200772 if (arena == NULL)
773 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000774 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 if (mod == NULL) {
776 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000777 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500779 if (!PyAST_Validate(mod)) {
780 PyArena_Free(arena);
781 goto error;
782 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200783 result = (PyObject*)PyAST_CompileObject(mod, filename,
784 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 PyArena_Free(arena);
786 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000787 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000789
Martin Panter61d6e4a2015-11-07 02:56:11 +0000790 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000792 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000793
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000794 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000795 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000796 goto finally;
797
798error:
799 result = NULL;
800finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200801 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000802 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000803}
804
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000805/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000806static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000807builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
812 return NULL;
813 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000814}
815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000816PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000817"dir([object]) -> list of strings\n"
818"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000819"If called without an argument, return the names in the current scope.\n"
820"Else, return an alphabetized list of names comprising (some of) the attributes\n"
821"of the given object, and of attributes reachable from it.\n"
822"If the object supplies a method named __dir__, it will be used; otherwise\n"
823"the default dir() logic is used and returns:\n"
824" for a module object: the module's attributes.\n"
825" for a class object: its attributes, and recursively the attributes\n"
826" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000827" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000828" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000829
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000830/*[clinic input]
831divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000832
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300833 x: object
834 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000835 /
836
Zachary Ware7f227d92016-04-28 14:39:50 -0500837Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000838[clinic start generated code]*/
839
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000840static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300841builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
842/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000843{
844 return PyNumber_Divmod(x, y);
845}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000846
847
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000848/*[clinic input]
849eval as builtin_eval
850
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300851 source: object
852 globals: object = None
853 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000854 /
855
856Evaluate the given source in the context of globals and locals.
857
858The source may be a string representing a Python expression
859or a code object as returned by compile().
860The globals must be a dictionary and locals can be any mapping,
861defaulting to the current globals and locals.
862If only globals is given, locals defaults to it.
863[clinic start generated code]*/
864
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000865static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300866builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400867 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300868/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000869{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000870 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200871 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (locals != Py_None && !PyMapping_Check(locals)) {
875 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
876 return NULL;
877 }
878 if (globals != Py_None && !PyDict_Check(globals)) {
879 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
880 "globals must be a real dict; try eval(expr, {}, mapping)"
881 : "globals must be a dict");
882 return NULL;
883 }
884 if (globals == Py_None) {
885 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100886 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100888 if (locals == NULL)
889 return NULL;
890 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 }
892 else if (locals == Py_None)
893 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 if (globals == NULL || locals == NULL) {
896 PyErr_SetString(PyExc_TypeError,
897 "eval must be given globals and locals "
898 "when called without a frame");
899 return NULL;
900 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000901
Victor Stinnerb44562b2013-11-06 19:03:11 +0100902 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
903 if (_PyDict_SetItemId(globals, &PyId___builtins__,
904 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 return NULL;
906 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000907
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000908 if (PyCode_Check(source)) {
909 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyErr_SetString(PyExc_TypeError,
911 "code object passed to eval() may not contain free variables");
912 return NULL;
913 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000914 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000918 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (str == NULL)
920 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 while (*str == ' ' || *str == '\t')
923 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 (void)PyEval_MergeCompilerFlags(&cf);
926 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000927 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000929}
930
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000931/*[clinic input]
932exec as builtin_exec
933
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300934 source: object
935 globals: object = None
936 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000937 /
938
939Execute the given source in the context of globals and locals.
940
941The source may be a string representing one or more Python statements
942or a code object as returned by compile().
943The globals must be a dictionary and locals can be any mapping,
944defaulting to the current globals and locals.
945If only globals is given, locals defaults to it.
946[clinic start generated code]*/
947
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000948static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300949builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400950 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300951/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (globals == Py_None) {
956 globals = PyEval_GetGlobals();
957 if (locals == Py_None) {
958 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100959 if (locals == NULL)
960 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 }
962 if (!globals || !locals) {
963 PyErr_SetString(PyExc_SystemError,
964 "globals and locals cannot be NULL");
965 return NULL;
966 }
967 }
968 else if (locals == Py_None)
969 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000972 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 globals->ob_type->tp_name);
974 return NULL;
975 }
976 if (!PyMapping_Check(locals)) {
977 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000978 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 locals->ob_type->tp_name);
980 return NULL;
981 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100982 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
983 if (_PyDict_SetItemId(globals, &PyId___builtins__,
984 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 return NULL;
986 }
987
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000988 if (PyCode_Check(source)) {
989 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 PyErr_SetString(PyExc_TypeError,
991 "code object passed to exec() may not "
992 "contain free variables");
993 return NULL;
994 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000995 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 }
997 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000998 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200999 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyCompilerFlags cf;
1001 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001002 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001003 "string, bytes or code", &cf,
1004 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (str == NULL)
1006 return NULL;
1007 if (PyEval_MergeCompilerFlags(&cf))
1008 v = PyRun_StringFlags(str, Py_file_input, globals,
1009 locals, &cf);
1010 else
1011 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001012 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 }
1014 if (v == NULL)
1015 return NULL;
1016 Py_DECREF(v);
1017 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001018}
1019
Georg Brandl7cae87c2006-09-06 06:51:57 +00001020
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001021/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001022static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03001023builtin_getattr(PyObject *self, PyObject **args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PyObject *v, *result, *dflt = NULL;
1026 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001027
Sylvain96c7c062017-06-15 17:05:23 +02001028 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
1029 return NULL;
1030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (!PyUnicode_Check(name)) {
1032 PyErr_SetString(PyExc_TypeError,
1033 "getattr(): attribute name must be string");
1034 return NULL;
1035 }
1036 result = PyObject_GetAttr(v, name);
1037 if (result == NULL && dflt != NULL &&
1038 PyErr_ExceptionMatches(PyExc_AttributeError))
1039 {
1040 PyErr_Clear();
1041 Py_INCREF(dflt);
1042 result = dflt;
1043 }
1044 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001045}
1046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001047PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001048"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001049\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001050Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1051When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001052exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001053
1054
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001055/*[clinic input]
1056globals as builtin_globals
1057
1058Return the dictionary containing the current scope's global variables.
1059
1060NOTE: Updates to this dictionary *will* affect name lookups in the current
1061global scope and vice-versa.
1062[clinic start generated code]*/
1063
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001064static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001065builtin_globals_impl(PyObject *module)
1066/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 d = PyEval_GetGlobals();
1071 Py_XINCREF(d);
1072 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001073}
1074
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001075
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001076/*[clinic input]
1077hasattr as builtin_hasattr
1078
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001079 obj: object
1080 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001081 /
1082
1083Return whether the object has an attribute with the given name.
1084
1085This is done by calling getattr(obj, name) and catching AttributeError.
1086[clinic start generated code]*/
1087
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001088static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001089builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1090/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001091{
1092 PyObject *v;
1093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (!PyUnicode_Check(name)) {
1095 PyErr_SetString(PyExc_TypeError,
1096 "hasattr(): attribute name must be string");
1097 return NULL;
1098 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001099 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001101 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001103 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001105 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 }
1107 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001108 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001109}
1110
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001111
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001112/* AC: gdb's integration with CPython relies on builtin_id having
1113 * the *exact* parameter names of "self" and "v", so we ensure we
1114 * preserve those name rather than using the AC defaults.
1115 */
1116/*[clinic input]
1117id as builtin_id
1118
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001119 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001120 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001121 /
1122
1123Return the identity of an object.
1124
1125This is guaranteed to be unique among simultaneously existing objects.
1126(CPython uses the object's memory address.)
1127[clinic start generated code]*/
1128
Guido van Rossum79f25d91997-04-29 20:08:16 +00001129static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001130builtin_id(PyModuleDef *self, PyObject *v)
1131/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001134}
1135
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001136
Raymond Hettingera6c60372008-03-13 01:26:19 +00001137/* map object ************************************************************/
1138
1139typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 PyObject_HEAD
1141 PyObject *iters;
1142 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001143} mapobject;
1144
Guido van Rossum79f25d91997-04-29 20:08:16 +00001145static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001146map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 PyObject *it, *iters, *func;
1149 mapobject *lz;
1150 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001151
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001152 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 numargs = PyTuple_Size(args);
1156 if (numargs < 2) {
1157 PyErr_SetString(PyExc_TypeError,
1158 "map() must have at least two arguments.");
1159 return NULL;
1160 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 iters = PyTuple_New(numargs-1);
1163 if (iters == NULL)
1164 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 for (i=1 ; i<numargs ; i++) {
1167 /* Get iterator. */
1168 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1169 if (it == NULL) {
1170 Py_DECREF(iters);
1171 return NULL;
1172 }
1173 PyTuple_SET_ITEM(iters, i-1, it);
1174 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 /* create mapobject structure */
1177 lz = (mapobject *)type->tp_alloc(type, 0);
1178 if (lz == NULL) {
1179 Py_DECREF(iters);
1180 return NULL;
1181 }
1182 lz->iters = iters;
1183 func = PyTuple_GET_ITEM(args, 0);
1184 Py_INCREF(func);
1185 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001188}
1189
1190static void
1191map_dealloc(mapobject *lz)
1192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 PyObject_GC_UnTrack(lz);
1194 Py_XDECREF(lz->iters);
1195 Py_XDECREF(lz->func);
1196 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001197}
1198
1199static int
1200map_traverse(mapobject *lz, visitproc visit, void *arg)
1201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 Py_VISIT(lz->iters);
1203 Py_VISIT(lz->func);
1204 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001205}
1206
1207static PyObject *
1208map_next(mapobject *lz)
1209{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001210 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001211 PyObject **stack;
1212 Py_ssize_t niters, nargs, i;
1213 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001214
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001215 niters = PyTuple_GET_SIZE(lz->iters);
1216 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1217 stack = small_stack;
1218 }
1219 else {
1220 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1221 if (stack == NULL) {
1222 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 return NULL;
1224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001226
1227 nargs = 0;
1228 for (i=0; i < niters; i++) {
1229 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1230 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1231 if (val == NULL) {
1232 goto exit;
1233 }
1234 stack[i] = val;
1235 nargs++;
1236 }
1237
1238 result = _PyObject_FastCall(lz->func, stack, nargs);
1239
1240exit:
1241 for (i=0; i < nargs; i++) {
1242 Py_DECREF(stack[i]);
1243 }
1244 if (stack != small_stack) {
1245 PyMem_Free(stack);
1246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001248}
1249
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001250static PyObject *
1251map_reduce(mapobject *lz)
1252{
1253 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1254 PyObject *args = PyTuple_New(numargs+1);
1255 Py_ssize_t i;
1256 if (args == NULL)
1257 return NULL;
1258 Py_INCREF(lz->func);
1259 PyTuple_SET_ITEM(args, 0, lz->func);
1260 for (i = 0; i<numargs; i++){
1261 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1262 Py_INCREF(it);
1263 PyTuple_SET_ITEM(args, i+1, it);
1264 }
1265
1266 return Py_BuildValue("ON", Py_TYPE(lz), args);
1267}
1268
1269static PyMethodDef map_methods[] = {
1270 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1271 {NULL, NULL} /* sentinel */
1272};
1273
1274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001275PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001276"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001277\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001278Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001280
Raymond Hettingera6c60372008-03-13 01:26:19 +00001281PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1283 "map", /* tp_name */
1284 sizeof(mapobject), /* tp_basicsize */
1285 0, /* tp_itemsize */
1286 /* methods */
1287 (destructor)map_dealloc, /* tp_dealloc */
1288 0, /* tp_print */
1289 0, /* tp_getattr */
1290 0, /* tp_setattr */
1291 0, /* tp_reserved */
1292 0, /* tp_repr */
1293 0, /* tp_as_number */
1294 0, /* tp_as_sequence */
1295 0, /* tp_as_mapping */
1296 0, /* tp_hash */
1297 0, /* tp_call */
1298 0, /* tp_str */
1299 PyObject_GenericGetAttr, /* tp_getattro */
1300 0, /* tp_setattro */
1301 0, /* tp_as_buffer */
1302 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1303 Py_TPFLAGS_BASETYPE, /* tp_flags */
1304 map_doc, /* tp_doc */
1305 (traverseproc)map_traverse, /* tp_traverse */
1306 0, /* tp_clear */
1307 0, /* tp_richcompare */
1308 0, /* tp_weaklistoffset */
1309 PyObject_SelfIter, /* tp_iter */
1310 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001311 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 0, /* tp_members */
1313 0, /* tp_getset */
1314 0, /* tp_base */
1315 0, /* tp_dict */
1316 0, /* tp_descr_get */
1317 0, /* tp_descr_set */
1318 0, /* tp_dictoffset */
1319 0, /* tp_init */
1320 PyType_GenericAlloc, /* tp_alloc */
1321 map_new, /* tp_new */
1322 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001323};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001324
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001325
1326/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001327static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03001328builtin_next(PyObject *self, PyObject **args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 PyObject *it, *res;
1331 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001332
Sylvain96c7c062017-06-15 17:05:23 +02001333 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
1334 return NULL;
1335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (!PyIter_Check(it)) {
1337 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001338 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 it->ob_type->tp_name);
1340 return NULL;
1341 }
1342
1343 res = (*it->ob_type->tp_iternext)(it);
1344 if (res != NULL) {
1345 return res;
1346 } else if (def != NULL) {
1347 if (PyErr_Occurred()) {
1348 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1349 return NULL;
1350 PyErr_Clear();
1351 }
1352 Py_INCREF(def);
1353 return def;
1354 } else if (PyErr_Occurred()) {
1355 return NULL;
1356 } else {
1357 PyErr_SetNone(PyExc_StopIteration);
1358 return NULL;
1359 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001360}
1361
1362PyDoc_STRVAR(next_doc,
1363"next(iterator[, default])\n\
1364\n\
1365Return the next item from the iterator. If default is given and the iterator\n\
1366is exhausted, it is returned instead of raising StopIteration.");
1367
1368
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001369/*[clinic input]
1370setattr as builtin_setattr
1371
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001372 obj: object
1373 name: object
1374 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001375 /
1376
1377Sets the named attribute on the given object to the specified value.
1378
1379setattr(x, 'y', v) is equivalent to ``x.y = v''
1380[clinic start generated code]*/
1381
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001382static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001383builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001384 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001385/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001386{
1387 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001389 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001390}
1391
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001392
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001393/*[clinic input]
1394delattr as builtin_delattr
1395
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001396 obj: object
1397 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001398 /
1399
1400Deletes the named attribute from the given object.
1401
1402delattr(x, 'y') is equivalent to ``del x.y''
1403[clinic start generated code]*/
1404
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001405static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001406builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1407/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001408{
1409 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001411 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001412}
1413
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001414
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001415/*[clinic input]
1416hash as builtin_hash
1417
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001418 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001419 /
1420
1421Return the hash value for the given object.
1422
1423Two objects that compare equal must also have the same hash value, but the
1424reverse is not necessarily true.
1425[clinic start generated code]*/
1426
Guido van Rossum79f25d91997-04-29 20:08:16 +00001427static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001428builtin_hash(PyObject *module, PyObject *obj)
1429/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001430{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001431 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001432
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001433 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (x == -1)
1435 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001436 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001437}
1438
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001439
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001440/*[clinic input]
1441hex as builtin_hex
1442
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001443 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001444 /
1445
1446Return the hexadecimal representation of an integer.
1447
1448 >>> hex(12648430)
1449 '0xc0ffee'
1450[clinic start generated code]*/
1451
Guido van Rossum79f25d91997-04-29 20:08:16 +00001452static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001453builtin_hex(PyObject *module, PyObject *number)
1454/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001455{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001456 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001457}
1458
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001459
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001460/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001461static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001462builtin_iter(PyObject *self, PyObject *args)
1463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1467 return NULL;
1468 if (w == NULL)
1469 return PyObject_GetIter(v);
1470 if (!PyCallable_Check(v)) {
1471 PyErr_SetString(PyExc_TypeError,
1472 "iter(v, w): v must be callable");
1473 return NULL;
1474 }
1475 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001476}
1477
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001478PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001479"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001480iter(callable, sentinel) -> iterator\n\
1481\n\
1482Get an iterator from an object. In the first form, the argument must\n\
1483supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001484In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001485
1486
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001487/*[clinic input]
1488len as builtin_len
1489
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001490 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001491 /
1492
1493Return the number of items in a container.
1494[clinic start generated code]*/
1495
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001496static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001497builtin_len(PyObject *module, PyObject *obj)
1498/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001501
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001502 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001503 if (res < 0) {
1504 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001506 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001508}
1509
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001510
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001511/*[clinic input]
1512locals as builtin_locals
1513
1514Return a dictionary containing the current scope's local variables.
1515
1516NOTE: Whether or not updates to this dictionary will affect name lookups in
1517the local scope and vice-versa is *implementation dependent* and not
1518covered by any backwards compatibility guarantees.
1519[clinic start generated code]*/
1520
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001521static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001522builtin_locals_impl(PyObject *module)
1523/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 d = PyEval_GetLocals();
1528 Py_XINCREF(d);
1529 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001530}
1531
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001532
Guido van Rossum79f25d91997-04-29 20:08:16 +00001533static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001534min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001537 PyObject *emptytuple, *defaultval = NULL;
1538 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001540 const int positional = PyTuple_Size(args) > 1;
1541 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001542
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001543 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001545 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001547
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001548 emptytuple = PyTuple_New(0);
1549 if (emptytuple == NULL)
1550 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001551 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1552 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1553 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001554 Py_DECREF(emptytuple);
1555 if (!ret)
1556 return NULL;
1557
1558 if (positional && defaultval != NULL) {
1559 PyErr_Format(PyExc_TypeError,
1560 "Cannot specify a default for %s() with multiple "
1561 "positional arguments", name);
1562 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 it = PyObject_GetIter(v);
1566 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 return NULL;
1568 }
Tim Petersc3074532001-05-03 07:00:32 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 maxitem = NULL; /* the result */
1571 maxval = NULL; /* the value associated with the result */
1572 while (( item = PyIter_Next(it) )) {
1573 /* get the value from the key function */
1574 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001575 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (val == NULL)
1577 goto Fail_it_item;
1578 }
1579 /* no key function; the value is the item */
1580 else {
1581 val = item;
1582 Py_INCREF(val);
1583 }
Tim Petersc3074532001-05-03 07:00:32 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 /* maximum value and item are unset; set them */
1586 if (maxval == NULL) {
1587 maxitem = item;
1588 maxval = val;
1589 }
1590 /* maximum value and item are set; update them as necessary */
1591 else {
1592 int cmp = PyObject_RichCompareBool(val, maxval, op);
1593 if (cmp < 0)
1594 goto Fail_it_item_and_val;
1595 else if (cmp > 0) {
1596 Py_DECREF(maxval);
1597 Py_DECREF(maxitem);
1598 maxval = val;
1599 maxitem = item;
1600 }
1601 else {
1602 Py_DECREF(item);
1603 Py_DECREF(val);
1604 }
1605 }
1606 }
1607 if (PyErr_Occurred())
1608 goto Fail_it;
1609 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001611 if (defaultval != NULL) {
1612 Py_INCREF(defaultval);
1613 maxitem = defaultval;
1614 } else {
1615 PyErr_Format(PyExc_ValueError,
1616 "%s() arg is an empty sequence", name);
1617 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 }
1619 else
1620 Py_DECREF(maxval);
1621 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001623
1624Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001626Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001628Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 Py_XDECREF(maxval);
1630 Py_XDECREF(maxitem);
1631 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001633}
1634
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001635/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001636static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001637builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001640}
1641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001642PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001643"min(iterable, *[, default=obj, key=func]) -> value\n\
1644min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001645\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001646With a single iterable argument, return its smallest item. The\n\
1647default keyword-only argument specifies an object to return if\n\
1648the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001649With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001650
1651
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001652/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001653static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001654builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001657}
1658
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001659PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001660"max(iterable, *[, default=obj, key=func]) -> value\n\
1661max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001662\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001663With a single iterable argument, return its biggest item. The\n\
1664default keyword-only argument specifies an object to return if\n\
1665the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001666With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001667
1668
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001669/*[clinic input]
1670oct as builtin_oct
1671
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001672 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001673 /
1674
1675Return the octal representation of an integer.
1676
1677 >>> oct(342391)
1678 '0o1234567'
1679[clinic start generated code]*/
1680
Guido van Rossum79f25d91997-04-29 20:08:16 +00001681static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001682builtin_oct(PyObject *module, PyObject *number)
1683/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001684{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001685 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001686}
1687
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001688
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001689/*[clinic input]
1690ord as builtin_ord
1691
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001692 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001693 /
1694
1695Return the Unicode code point for a one-character string.
1696[clinic start generated code]*/
1697
Guido van Rossum79f25d91997-04-29 20:08:16 +00001698static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001699builtin_ord(PyObject *module, PyObject *c)
1700/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 long ord;
1703 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001704
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001705 if (PyBytes_Check(c)) {
1706 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001708 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 return PyLong_FromLong(ord);
1710 }
1711 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001712 else if (PyUnicode_Check(c)) {
1713 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001714 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001715 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001717 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 return PyLong_FromLong(ord);
1719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001721 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001723 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001725 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 return PyLong_FromLong(ord);
1727 }
1728 }
1729 else {
1730 PyErr_Format(PyExc_TypeError,
1731 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001732 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return NULL;
1734 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyErr_Format(PyExc_TypeError,
1737 "ord() expected a character, "
1738 "but string of length %zd found",
1739 size);
1740 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001741}
1742
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001743
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001744/*[clinic input]
1745pow as builtin_pow
1746
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001747 x: object
1748 y: object
1749 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001750 /
1751
1752Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1753
1754Some types, such as ints, are able to use a more efficient algorithm when
1755invoked using the three argument form.
1756[clinic start generated code]*/
1757
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001758static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001759builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1760/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001761{
1762 return PyNumber_Power(x, y, z);
1763}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001764
1765
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001766/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001767static PyObject *
INADA Naokibd584f12017-01-19 12:50:34 +01001768builtin_print(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001769{
INADA Naokibd584f12017-01-19 12:50:34 +01001770 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1771 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001772 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001774
INADA Naokibd584f12017-01-19 12:50:34 +01001775 if (kwnames != NULL &&
1776 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1777 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001778 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001779 }
1780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001782 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001783 if (file == NULL) {
1784 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1785 return NULL;
1786 }
1787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 /* sys.stdout may be None when FILE* stdout isn't connected */
1789 if (file == Py_None)
1790 Py_RETURN_NONE;
1791 }
Guido van Rossum34343512006-11-30 22:13:52 +00001792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 if (sep == Py_None) {
1794 sep = NULL;
1795 }
1796 else if (sep && !PyUnicode_Check(sep)) {
1797 PyErr_Format(PyExc_TypeError,
1798 "sep must be None or a string, not %.200s",
1799 sep->ob_type->tp_name);
1800 return NULL;
1801 }
1802 if (end == Py_None) {
1803 end = NULL;
1804 }
1805 else if (end && !PyUnicode_Check(end)) {
1806 PyErr_Format(PyExc_TypeError,
1807 "end must be None or a string, not %.200s",
1808 end->ob_type->tp_name);
1809 return NULL;
1810 }
Guido van Rossum34343512006-11-30 22:13:52 +00001811
INADA Naokibd584f12017-01-19 12:50:34 +01001812 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 if (i > 0) {
1814 if (sep == NULL)
1815 err = PyFile_WriteString(" ", file);
1816 else
1817 err = PyFile_WriteObject(sep, file,
1818 Py_PRINT_RAW);
1819 if (err)
1820 return NULL;
1821 }
INADA Naokibd584f12017-01-19 12:50:34 +01001822 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (err)
1824 return NULL;
1825 }
Guido van Rossum34343512006-11-30 22:13:52 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 if (end == NULL)
1828 err = PyFile_WriteString("\n", file);
1829 else
1830 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1831 if (err)
1832 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001833
Georg Brandlbc3b6822012-01-13 19:41:25 +01001834 if (flush != NULL) {
1835 PyObject *tmp;
1836 int do_flush = PyObject_IsTrue(flush);
1837 if (do_flush == -1)
1838 return NULL;
1839 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001840 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001841 if (tmp == NULL)
1842 return NULL;
1843 else
1844 Py_DECREF(tmp);
1845 }
1846 }
1847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001849}
1850
1851PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001852"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001853\n\
1854Prints the values to a stream, or to sys.stdout by default.\n\
1855Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001856file: a file-like object (stream); defaults to the current sys.stdout.\n\
1857sep: string inserted between values, default a space.\n\
1858end: string appended after the last value, default a newline.\n\
1859flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001860
1861
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001862/*[clinic input]
1863input as builtin_input
1864
1865 prompt: object(c_default="NULL") = None
1866 /
1867
1868Read a string from standard input. The trailing newline is stripped.
1869
1870The prompt string, if given, is printed to standard output without a
1871trailing newline before reading input.
1872
1873If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1874On *nix systems, readline is used if available.
1875[clinic start generated code]*/
1876
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001877static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001878builtin_input_impl(PyObject *module, PyObject *prompt)
1879/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001880{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001881 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1882 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1883 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 PyObject *tmp;
1885 long fd;
1886 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 /* Check that stdin/out/err are intact */
1889 if (fin == NULL || fin == Py_None) {
1890 PyErr_SetString(PyExc_RuntimeError,
1891 "input(): lost sys.stdin");
1892 return NULL;
1893 }
1894 if (fout == NULL || fout == Py_None) {
1895 PyErr_SetString(PyExc_RuntimeError,
1896 "input(): lost sys.stdout");
1897 return NULL;
1898 }
1899 if (ferr == NULL || ferr == Py_None) {
1900 PyErr_SetString(PyExc_RuntimeError,
1901 "input(): lost sys.stderr");
1902 return NULL;
1903 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001906 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 if (tmp == NULL)
1908 PyErr_Clear();
1909 else
1910 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* We should only use (GNU) readline if Python's sys.stdin and
1913 sys.stdout are the same as C's stdin and stdout, because we
1914 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001915 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (tmp == NULL) {
1917 PyErr_Clear();
1918 tty = 0;
1919 }
1920 else {
1921 fd = PyLong_AsLong(tmp);
1922 Py_DECREF(tmp);
1923 if (fd < 0 && PyErr_Occurred())
1924 return NULL;
1925 tty = fd == fileno(stdin) && isatty(fd);
1926 }
1927 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001928 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001929 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001931 tty = 0;
1932 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 else {
1934 fd = PyLong_AsLong(tmp);
1935 Py_DECREF(tmp);
1936 if (fd < 0 && PyErr_Occurred())
1937 return NULL;
1938 tty = fd == fileno(stdout) && isatty(fd);
1939 }
1940 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 /* If we're interactive, use (GNU) readline */
1943 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001944 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001945 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001946 char *s = NULL;
1947 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1948 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001949 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001951 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001952
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001953 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001954 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001955 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001956 if (!stdin_encoding || !stdin_errors ||
1957 !PyUnicode_Check(stdin_encoding) ||
1958 !PyUnicode_Check(stdin_errors)) {
1959 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001960 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001961 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001962 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
1963 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001964 if (!stdin_encoding_str || !stdin_errors_str)
1965 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07001966 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 if (tmp == NULL)
1968 PyErr_Clear();
1969 else
1970 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001971 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001972 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001973 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001975 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001976 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001977 if (!stdout_encoding || !stdout_errors ||
1978 !PyUnicode_Check(stdout_encoding) ||
1979 !PyUnicode_Check(stdout_errors)) {
1980 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001981 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001982 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001983 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
1984 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001985 if (!stdout_encoding_str || !stdout_errors_str)
1986 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001987 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001988 if (stringpo == NULL)
1989 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001991 stdout_encoding_str, stdout_errors_str);
1992 Py_CLEAR(stdout_encoding);
1993 Py_CLEAR(stdout_errors);
1994 Py_CLEAR(stringpo);
1995 if (po == NULL)
1996 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001997 assert(PyBytes_Check(po));
1998 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 }
2000 else {
2001 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002002 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002004 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002006 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 if (!PyErr_Occurred())
2008 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002009 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002011
2012 len = strlen(s);
2013 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 PyErr_SetNone(PyExc_EOFError);
2015 result = NULL;
2016 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002017 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 if (len > PY_SSIZE_T_MAX) {
2019 PyErr_SetString(PyExc_OverflowError,
2020 "input: input too long");
2021 result = NULL;
2022 }
2023 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002024 len--; /* strip trailing '\n' */
2025 if (len != 0 && s[len-1] == '\r')
2026 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002027 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2028 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 }
2030 }
2031 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002032 Py_DECREF(stdin_errors);
2033 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 PyMem_FREE(s);
2035 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002036
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002037 _readline_errors:
2038 Py_XDECREF(stdin_encoding);
2039 Py_XDECREF(stdout_encoding);
2040 Py_XDECREF(stdin_errors);
2041 Py_XDECREF(stdout_errors);
2042 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002043 if (tty)
2044 return NULL;
2045
2046 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002050 if (prompt != NULL) {
2051 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 return NULL;
2053 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002054 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (tmp == NULL)
2056 PyErr_Clear();
2057 else
2058 Py_DECREF(tmp);
2059 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002060}
2061
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002062
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002063/*[clinic input]
2064repr as builtin_repr
2065
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002066 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002067 /
2068
2069Return the canonical string representation of the object.
2070
2071For many object types, including most builtins, eval(repr(obj)) == obj.
2072[clinic start generated code]*/
2073
Guido van Rossum79f25d91997-04-29 20:08:16 +00002074static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002075builtin_repr(PyObject *module, PyObject *obj)
2076/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002077{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002078 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002079}
2080
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002081
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002082/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2083 * or a semantic change to accept None for "ndigits"
2084 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002085static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002086builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 PyObject *ndigits = NULL;
2089 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002090 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2093 kwlist, &number, &ndigits))
2094 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 if (Py_TYPE(number)->tp_dict == NULL) {
2097 if (PyType_Ready(Py_TYPE(number)) < 0)
2098 return NULL;
2099 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002100
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002101 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002103 if (!PyErr_Occurred())
2104 PyErr_Format(PyExc_TypeError,
2105 "type %.100s doesn't define __round__ method",
2106 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 return NULL;
2108 }
Alex Martelliae211f92007-08-22 23:21:33 +00002109
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002110 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002111 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002113 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002114 Py_DECREF(round);
2115 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002116}
2117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002118PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002119"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002120\n\
2121Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002122This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002123same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002124
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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
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}