blob: 14550fd233f4ff8a20f571c9be7303210faca7f1 [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"
Guido van Rossum6bf62da1997-04-11 20:37:35 +00004#include <ctype.h>
Victor Stinner5f2df882018-11-12 00:56:19 +01005#include "ast.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01006#include "pycore_pystate.h"
Guido van Rossum6bf62da1997-04-11 20:37:35 +00007
Victor Stinnerbd303c12013-11-07 23:07:29 +01008_Py_IDENTIFIER(__builtins__);
9_Py_IDENTIFIER(__dict__);
10_Py_IDENTIFIER(__prepare__);
11_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010012_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010013_Py_IDENTIFIER(encoding);
14_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020015_Py_IDENTIFIER(fileno);
16_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010017_Py_IDENTIFIER(metaclass);
18_Py_IDENTIFIER(sort);
19_Py_IDENTIFIER(stdin);
20_Py_IDENTIFIER(stdout);
21_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020022
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030023#include "clinic/bltinmodule.c.h"
24
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010025static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010026update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010027{
Victor Stinner05d68a82018-01-18 11:15:25 +010028 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010029 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
30 PyObject *stack[1] = {bases};
31 assert(PyTuple_Check(bases));
32
33 for (i = 0; i < nargs; i++) {
34 base = args[i];
35 if (PyType_Check(base)) {
36 if (new_bases) {
37 /* If we already have made a replacement, then we append every normal base,
38 otherwise just skip it. */
39 if (PyList_Append(new_bases, base) < 0) {
40 goto error;
41 }
42 }
43 continue;
44 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020045 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
46 goto error;
47 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010048 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010049 if (new_bases) {
50 if (PyList_Append(new_bases, base) < 0) {
51 goto error;
52 }
53 }
54 continue;
55 }
56 new_base = _PyObject_FastCall(meth, stack, 1);
57 Py_DECREF(meth);
58 if (!new_base) {
59 goto error;
60 }
61 if (!PyTuple_Check(new_base)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__mro_entries__ must return a tuple");
64 Py_DECREF(new_base);
65 goto error;
66 }
67 if (!new_bases) {
68 /* If this is a first successful replacement, create new_bases list and
69 copy previously encountered bases. */
70 if (!(new_bases = PyList_New(i))) {
71 goto error;
72 }
73 for (j = 0; j < i; j++) {
74 base = args[j];
75 PyList_SET_ITEM(new_bases, j, base);
76 Py_INCREF(base);
77 }
78 }
79 j = PyList_GET_SIZE(new_bases);
80 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
81 goto error;
82 }
83 Py_DECREF(new_base);
84 }
85 if (!new_bases) {
86 return bases;
87 }
88 result = PyList_AsTuple(new_bases);
89 Py_DECREF(new_bases);
90 return result;
91
92error:
93 Py_XDECREF(new_bases);
94 return NULL;
95}
96
Nick Coghlanf9e227e2014-08-17 14:01:19 +100097/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000098static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +020099builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100100 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000101{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100102 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000103 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100104 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 if (nargs < 2) {
107 PyErr_SetString(PyExc_TypeError,
108 "__build_class__: not enough arguments");
109 return NULL;
110 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100111 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500112 if (!PyFunction_Check(func)) {
113 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500114 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500115 return NULL;
116 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100117 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 if (!PyUnicode_Check(name)) {
119 PyErr_SetString(PyExc_TypeError,
120 "__build_class__: name is not a string");
121 return NULL;
122 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100123 orig_bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs);
124 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000126
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100127 bases = update_bases(orig_bases, args + 2, nargs - 2);
128 if (bases == NULL) {
129 Py_DECREF(orig_bases);
130 return NULL;
131 }
132
Victor Stinner773dc6d2017-01-16 23:46:26 +0100133 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 meta = NULL;
135 mkw = NULL;
136 }
137 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100138 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 if (mkw == NULL) {
140 Py_DECREF(bases);
141 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000142 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100143
Victor Stinnerae9f1612013-11-06 22:46:51 +0100144 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 if (meta != NULL) {
146 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100147 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 Py_DECREF(meta);
149 Py_DECREF(mkw);
150 Py_DECREF(bases);
151 return NULL;
152 }
Nick Coghlande31b192011-10-23 22:04:16 +1000153 /* metaclass is explicitly given, check if it's indeed a class */
154 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 }
156 }
157 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000158 /* if there are no bases, use type: */
159 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000161 }
162 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 else {
164 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
165 meta = (PyObject *) (base0->ob_type);
166 }
167 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000168 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000170
Nick Coghlande31b192011-10-23 22:04:16 +1000171 if (isclass) {
172 /* meta is really a class, so check for a more derived
173 metaclass, or possible metaclass conflicts: */
174 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
175 bases);
176 if (winner == NULL) {
177 Py_DECREF(meta);
178 Py_XDECREF(mkw);
179 Py_DECREF(bases);
180 return NULL;
181 }
182 if (winner != meta) {
183 Py_DECREF(meta);
184 meta = winner;
185 Py_INCREF(meta);
186 }
187 }
188 /* else: meta is not a class, so we cannot do the metaclass
189 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200190 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
191 ns = NULL;
192 }
193 else if (prep == NULL) {
194 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 }
196 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200197 PyObject *pargs[2] = {name, bases};
198 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 Py_DECREF(prep);
200 }
201 if (ns == NULL) {
202 Py_DECREF(meta);
203 Py_XDECREF(mkw);
204 Py_DECREF(bases);
205 return NULL;
206 }
Oren Milman5837d042017-09-27 17:04:37 +0300207 if (!PyMapping_Check(ns)) {
208 PyErr_Format(PyExc_TypeError,
209 "%.200s.__prepare__() must return a mapping, not %.200s",
210 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
211 Py_TYPE(ns)->tp_name);
212 goto error;
213 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000214 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500215 NULL, 0, NULL, 0, NULL, 0, NULL,
216 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000217 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100218 if (bases != orig_bases) {
219 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
220 goto error;
221 }
222 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200223 PyObject *margs[3] = {name, bases, ns};
224 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000225 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
226 PyObject *cell_cls = PyCell_GET(cell);
227 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000228 if (cell_cls == NULL) {
229 const char *msg =
230 "__class__ not set defining %.200R as %.200R. "
231 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300232 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000233 } else {
234 const char *msg =
235 "__class__ set to %.200R defining %.200R as %.200R";
236 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000237 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300238 Py_DECREF(cls);
239 cls = NULL;
240 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000241 }
242 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000244error:
245 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 Py_DECREF(ns);
247 Py_DECREF(meta);
248 Py_XDECREF(mkw);
249 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100250 if (bases != orig_bases) {
251 Py_DECREF(orig_bases);
252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000254}
255
256PyDoc_STRVAR(build_class_doc,
257"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
258\n\
259Internal helper function used by the class statement.");
260
261static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000262builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
265 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400266 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400267 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000268
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400269 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 kwlist, &name, &globals, &locals, &fromlist, &level))
271 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400272 return PyImport_ImportModuleLevelObject(name, globals, locals,
273 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000274}
275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000276PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400277"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000278\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000279Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800280interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000281importlib.import_module() to programmatically import a module.\n\
282\n\
283The globals argument is only used to determine the context;\n\
284they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000285should be a list of names to emulate ``from name import ...'', or an\n\
286empty list to emulate ``import name''.\n\
287When importing a module from a package, note that __import__('A.B', ...)\n\
288returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800289fromlist is not empty. The level argument is used to determine whether to\n\
290perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000291is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000292
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000293
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000294/*[clinic input]
295abs as builtin_abs
296
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300297 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000298 /
299
300Return the absolute value of the argument.
301[clinic start generated code]*/
302
Guido van Rossum79f25d91997-04-29 20:08:16 +0000303static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300304builtin_abs(PyObject *module, PyObject *x)
305/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000306{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000307 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000308}
309
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000310/*[clinic input]
311all as builtin_all
312
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300313 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000314 /
315
316Return True if bool(x) is True for all values x in the iterable.
317
318If the iterable is empty, return True.
319[clinic start generated code]*/
320
Raymond Hettinger96229b12005-03-11 06:49:40 +0000321static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300322builtin_all(PyObject *module, PyObject *iterable)
323/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 PyObject *it, *item;
326 PyObject *(*iternext)(PyObject *);
327 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000328
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000329 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (it == NULL)
331 return NULL;
332 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 for (;;) {
335 item = iternext(it);
336 if (item == NULL)
337 break;
338 cmp = PyObject_IsTrue(item);
339 Py_DECREF(item);
340 if (cmp < 0) {
341 Py_DECREF(it);
342 return NULL;
343 }
344 if (cmp == 0) {
345 Py_DECREF(it);
346 Py_RETURN_FALSE;
347 }
348 }
349 Py_DECREF(it);
350 if (PyErr_Occurred()) {
351 if (PyErr_ExceptionMatches(PyExc_StopIteration))
352 PyErr_Clear();
353 else
354 return NULL;
355 }
356 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000357}
358
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000359/*[clinic input]
360any as builtin_any
361
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300362 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000363 /
364
365Return True if bool(x) is True for any x in the iterable.
366
367If the iterable is empty, return False.
368[clinic start generated code]*/
369
Raymond Hettinger96229b12005-03-11 06:49:40 +0000370static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300371builtin_any(PyObject *module, PyObject *iterable)
372/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 PyObject *it, *item;
375 PyObject *(*iternext)(PyObject *);
376 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000377
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000378 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (it == NULL)
380 return NULL;
381 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 for (;;) {
384 item = iternext(it);
385 if (item == NULL)
386 break;
387 cmp = PyObject_IsTrue(item);
388 Py_DECREF(item);
389 if (cmp < 0) {
390 Py_DECREF(it);
391 return NULL;
392 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400393 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 Py_DECREF(it);
395 Py_RETURN_TRUE;
396 }
397 }
398 Py_DECREF(it);
399 if (PyErr_Occurred()) {
400 if (PyErr_ExceptionMatches(PyExc_StopIteration))
401 PyErr_Clear();
402 else
403 return NULL;
404 }
405 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000406}
407
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000408/*[clinic input]
409ascii as builtin_ascii
410
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300411 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000412 /
413
414Return an ASCII-only representation of an object.
415
416As repr(), return a string containing a printable representation of an
417object, but escape the non-ASCII characters in the string returned by
418repr() using \\x, \\u or \\U escapes. This generates a string similar
419to that returned by repr() in Python 2.
420[clinic start generated code]*/
421
Georg Brandl559e5d72008-06-11 18:37:52 +0000422static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300423builtin_ascii(PyObject *module, PyObject *obj)
424/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000425{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000426 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000427}
428
Georg Brandl559e5d72008-06-11 18:37:52 +0000429
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000430/*[clinic input]
431bin as builtin_bin
432
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300433 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000434 /
435
436Return the binary representation of an integer.
437
438 >>> bin(2796202)
439 '0b1010101010101010101010'
440[clinic start generated code]*/
441
Guido van Rossum79f25d91997-04-29 20:08:16 +0000442static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300443builtin_bin(PyObject *module, PyObject *number)
444/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000445{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000446 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000447}
448
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000449
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000450/*[clinic input]
451callable as builtin_callable
452
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300453 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000454 /
455
456Return whether the object is callable (i.e., some kind of function).
457
458Note that classes are callable, as are instances of classes with a
459__call__() method.
460[clinic start generated code]*/
461
Antoine Pitroue71362d2010-11-27 22:00:11 +0000462static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300463builtin_callable(PyObject *module, PyObject *obj)
464/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000465{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000466 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000467}
468
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400469static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200470builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400471{
472 PyObject *hook = PySys_GetObject("breakpointhook");
473
474 if (hook == NULL) {
475 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
476 return NULL;
477 }
478 Py_INCREF(hook);
479 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
480 Py_DECREF(hook);
481 return retval;
482}
483
484PyDoc_STRVAR(breakpoint_doc,
485"breakpoint(*args, **kws)\n\
486\n\
487Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
488whatever arguments are passed.\n\
489\n\
490By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000491
Raymond Hettinger17301e92008-03-13 00:19:26 +0000492typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 PyObject_HEAD
494 PyObject *func;
495 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000496} filterobject;
497
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000498static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000499filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyObject *func, *seq;
502 PyObject *it;
503 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000504
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300505 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
509 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 /* Get iterator. */
512 it = PyObject_GetIter(seq);
513 if (it == NULL)
514 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* create filterobject structure */
517 lz = (filterobject *)type->tp_alloc(type, 0);
518 if (lz == NULL) {
519 Py_DECREF(it);
520 return NULL;
521 }
522 Py_INCREF(func);
523 lz->func = func;
524 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000527}
528
529static void
530filter_dealloc(filterobject *lz)
531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyObject_GC_UnTrack(lz);
533 Py_XDECREF(lz->func);
534 Py_XDECREF(lz->it);
535 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000536}
537
538static int
539filter_traverse(filterobject *lz, visitproc visit, void *arg)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 Py_VISIT(lz->it);
542 Py_VISIT(lz->func);
543 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000544}
545
546static PyObject *
547filter_next(filterobject *lz)
548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 PyObject *item;
550 PyObject *it = lz->it;
551 long ok;
552 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400553 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 iternext = *Py_TYPE(it)->tp_iternext;
556 for (;;) {
557 item = iternext(it);
558 if (item == NULL)
559 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000560
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400561 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 ok = PyObject_IsTrue(item);
563 } else {
564 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100565 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (good == NULL) {
567 Py_DECREF(item);
568 return NULL;
569 }
570 ok = PyObject_IsTrue(good);
571 Py_DECREF(good);
572 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200573 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 return item;
575 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200576 if (ok < 0)
577 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000579}
580
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000581static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530582filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000583{
584 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
585}
586
587PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
588
589static PyMethodDef filter_methods[] = {
590 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
591 {NULL, NULL} /* sentinel */
592};
593
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000594PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000595"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000596\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000597Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000598is true. If function is None, return the items that are true.");
599
600PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyVarObject_HEAD_INIT(&PyType_Type, 0)
602 "filter", /* tp_name */
603 sizeof(filterobject), /* tp_basicsize */
604 0, /* tp_itemsize */
605 /* methods */
606 (destructor)filter_dealloc, /* tp_dealloc */
607 0, /* tp_print */
608 0, /* tp_getattr */
609 0, /* tp_setattr */
610 0, /* tp_reserved */
611 0, /* tp_repr */
612 0, /* tp_as_number */
613 0, /* tp_as_sequence */
614 0, /* tp_as_mapping */
615 0, /* tp_hash */
616 0, /* tp_call */
617 0, /* tp_str */
618 PyObject_GenericGetAttr, /* tp_getattro */
619 0, /* tp_setattro */
620 0, /* tp_as_buffer */
621 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
622 Py_TPFLAGS_BASETYPE, /* tp_flags */
623 filter_doc, /* tp_doc */
624 (traverseproc)filter_traverse, /* tp_traverse */
625 0, /* tp_clear */
626 0, /* tp_richcompare */
627 0, /* tp_weaklistoffset */
628 PyObject_SelfIter, /* tp_iter */
629 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000630 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 0, /* tp_members */
632 0, /* tp_getset */
633 0, /* tp_base */
634 0, /* tp_dict */
635 0, /* tp_descr_get */
636 0, /* tp_descr_set */
637 0, /* tp_dictoffset */
638 0, /* tp_init */
639 PyType_GenericAlloc, /* tp_alloc */
640 filter_new, /* tp_new */
641 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000642};
643
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000644
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000645/*[clinic input]
646format as builtin_format
647
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300648 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000649 format_spec: unicode(c_default="NULL") = ''
650 /
651
652Return value.__format__(format_spec)
653
Amit Kumar2e6bb442017-05-29 06:32:26 +0530654format_spec defaults to the empty string.
655See the Format Specification Mini-Language section of help('FORMATTING') for
656details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000657[clinic start generated code]*/
658
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000659static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300660builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530661/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000662{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000663 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000664}
665
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000666/*[clinic input]
667chr as builtin_chr
668
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300669 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000670 /
671
672Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
673[clinic start generated code]*/
674
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000675static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300676builtin_chr_impl(PyObject *module, int i)
677/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000678{
679 return PyUnicode_FromOrdinal(i);
680}
Guido van Rossum09095f32000-03-10 23:00:52 +0000681
682
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200683static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000684source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000685{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200686 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000688 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000689
Martin Pantereeb896c2015-11-07 02:32:21 +0000690 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (PyUnicode_Check(cmd)) {
692 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200693 str = PyUnicode_AsUTF8AndSize(cmd, &size);
694 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 return NULL;
696 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000697 else if (PyBytes_Check(cmd)) {
698 str = PyBytes_AS_STRING(cmd);
699 size = PyBytes_GET_SIZE(cmd);
700 }
701 else if (PyByteArray_Check(cmd)) {
702 str = PyByteArray_AS_STRING(cmd);
703 size = PyByteArray_GET_SIZE(cmd);
704 }
705 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
706 /* Copy to NUL-terminated buffer. */
707 *cmd_copy = PyBytes_FromStringAndSize(
708 (const char *)view.buf, view.len);
709 PyBuffer_Release(&view);
710 if (*cmd_copy == NULL) {
711 return NULL;
712 }
713 str = PyBytes_AS_STRING(*cmd_copy);
714 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200715 }
716 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyErr_Format(PyExc_TypeError,
718 "%s() arg 1 must be a %s object",
719 funcname, what);
720 return NULL;
721 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200722
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200723 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300724 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000726 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 return NULL;
728 }
729 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000730}
731
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000732/*[clinic input]
733compile as builtin_compile
734
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300735 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000736 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300737 mode: str
738 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200739 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300740 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000741
742Compile source into a code object that can be executed by exec() or eval().
743
744The source code may represent a Python module, statement or expression.
745The filename will be used for run-time error messages.
746The mode must be 'exec' to compile a module, 'single' to compile a
747single (interactive) statement, or 'eval' to compile an expression.
748The flags argument, if present, controls which future statements influence
749the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300750The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000751the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300752compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000753in addition to any features explicitly specified.
754[clinic start generated code]*/
755
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000756static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300757builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
758 const char *mode, int flags, int dont_inherit,
759 int optimize)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200760/*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000761{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000762 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200763 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000764 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 int is_ast;
766 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000768 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000769
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000770 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000771
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000772 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
774 {
775 PyErr_SetString(PyExc_ValueError,
776 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000777 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 }
779 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000780
Georg Brandl8334fd92010-12-04 10:26:46 +0000781 if (optimize < -1 || optimize > 2) {
782 PyErr_SetString(PyExc_ValueError,
783 "compile(): invalid optimize value");
784 goto error;
785 }
786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (!dont_inherit) {
788 PyEval_MergeCompilerFlags(&cf);
789 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000790
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000791 if (strcmp(mode, "exec") == 0)
792 compile_mode = 0;
793 else if (strcmp(mode, "eval") == 0)
794 compile_mode = 1;
795 else if (strcmp(mode, "single") == 0)
796 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 else {
798 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000799 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000800 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000802
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000803 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000805 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000807 if (flags & PyCF_ONLY_AST) {
808 Py_INCREF(source);
809 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 }
811 else {
812 PyArena *arena;
813 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200816 if (arena == NULL)
817 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000818 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (mod == NULL) {
820 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000821 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500823 if (!PyAST_Validate(mod)) {
824 PyArena_Free(arena);
825 goto error;
826 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200827 result = (PyObject*)PyAST_CompileObject(mod, filename,
828 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 PyArena_Free(arena);
830 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000831 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000833
Martin Panter61d6e4a2015-11-07 02:56:11 +0000834 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000836 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000837
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000838 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000839 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000840 goto finally;
841
842error:
843 result = NULL;
844finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200845 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000846 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000847}
848
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000849/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000850static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000851builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
856 return NULL;
857 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000858}
859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000860PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000861"dir([object]) -> list of strings\n"
862"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000863"If called without an argument, return the names in the current scope.\n"
864"Else, return an alphabetized list of names comprising (some of) the attributes\n"
865"of the given object, and of attributes reachable from it.\n"
866"If the object supplies a method named __dir__, it will be used; otherwise\n"
867"the default dir() logic is used and returns:\n"
868" for a module object: the module's attributes.\n"
869" for a class object: its attributes, and recursively the attributes\n"
870" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000871" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000872" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000873
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000874/*[clinic input]
875divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000876
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300877 x: object
878 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000879 /
880
Zachary Ware7f227d92016-04-28 14:39:50 -0500881Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000882[clinic start generated code]*/
883
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000884static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300885builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
886/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000887{
888 return PyNumber_Divmod(x, y);
889}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000890
891
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000892/*[clinic input]
893eval as builtin_eval
894
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300895 source: object
896 globals: object = None
897 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000898 /
899
900Evaluate the given source in the context of globals and locals.
901
902The source may be a string representing a Python expression
903or a code object as returned by compile().
904The globals must be a dictionary and locals can be any mapping,
905defaulting to the current globals and locals.
906If only globals is given, locals defaults to it.
907[clinic start generated code]*/
908
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000909static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300910builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400911 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300912/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000913{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000914 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200915 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (locals != Py_None && !PyMapping_Check(locals)) {
919 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
920 return NULL;
921 }
922 if (globals != Py_None && !PyDict_Check(globals)) {
923 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
924 "globals must be a real dict; try eval(expr, {}, mapping)"
925 : "globals must be a dict");
926 return NULL;
927 }
928 if (globals == Py_None) {
929 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100930 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100932 if (locals == NULL)
933 return NULL;
934 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 }
936 else if (locals == Py_None)
937 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (globals == NULL || locals == NULL) {
940 PyErr_SetString(PyExc_TypeError,
941 "eval must be given globals and locals "
942 "when called without a frame");
943 return NULL;
944 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000945
Victor Stinnerb44562b2013-11-06 19:03:11 +0100946 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
947 if (_PyDict_SetItemId(globals, &PyId___builtins__,
948 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 return NULL;
950 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000951
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000952 if (PyCode_Check(source)) {
953 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 PyErr_SetString(PyExc_TypeError,
955 "code object passed to eval() may not contain free variables");
956 return NULL;
957 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000958 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000962 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (str == NULL)
964 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 while (*str == ' ' || *str == '\t')
967 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 (void)PyEval_MergeCompilerFlags(&cf);
970 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000971 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000973}
974
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000975/*[clinic input]
976exec as builtin_exec
977
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300978 source: object
979 globals: object = None
980 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000981 /
982
983Execute the given source in the context of globals and locals.
984
985The source may be a string representing one or more Python statements
986or a code object as returned by compile().
987The globals must be a dictionary and locals can be any mapping,
988defaulting to the current globals and locals.
989If only globals is given, locals defaults to it.
990[clinic start generated code]*/
991
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000992static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300993builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400994 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300995/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 if (globals == Py_None) {
1000 globals = PyEval_GetGlobals();
1001 if (locals == Py_None) {
1002 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001003 if (locals == NULL)
1004 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 }
1006 if (!globals || !locals) {
1007 PyErr_SetString(PyExc_SystemError,
1008 "globals and locals cannot be NULL");
1009 return NULL;
1010 }
1011 }
1012 else if (locals == Py_None)
1013 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001016 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 globals->ob_type->tp_name);
1018 return NULL;
1019 }
1020 if (!PyMapping_Check(locals)) {
1021 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001022 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 locals->ob_type->tp_name);
1024 return NULL;
1025 }
Victor Stinnerb44562b2013-11-06 19:03:11 +01001026 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
1027 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1028 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 return NULL;
1030 }
1031
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001032 if (PyCode_Check(source)) {
1033 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 PyErr_SetString(PyExc_TypeError,
1035 "code object passed to exec() may not "
1036 "contain free variables");
1037 return NULL;
1038 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001039 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 }
1041 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001042 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001043 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyCompilerFlags cf;
1045 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001046 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001047 "string, bytes or code", &cf,
1048 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (str == NULL)
1050 return NULL;
1051 if (PyEval_MergeCompilerFlags(&cf))
1052 v = PyRun_StringFlags(str, Py_file_input, globals,
1053 locals, &cf);
1054 else
1055 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001056 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 }
1058 if (v == NULL)
1059 return NULL;
1060 Py_DECREF(v);
1061 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001062}
1063
Georg Brandl7cae87c2006-09-06 06:51:57 +00001064
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001065/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001066static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001067builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject *v, *result, *dflt = NULL;
1070 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001071
Sylvain96c7c062017-06-15 17:05:23 +02001072 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
1073 return NULL;
1074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (!PyUnicode_Check(name)) {
1076 PyErr_SetString(PyExc_TypeError,
1077 "getattr(): attribute name must be string");
1078 return NULL;
1079 }
INADA Naoki378edee2018-01-16 20:52:41 +09001080 if (dflt != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001081 if (_PyObject_LookupAttr(v, name, &result) == 0) {
INADA Naoki378edee2018-01-16 20:52:41 +09001082 Py_INCREF(dflt);
1083 return dflt;
1084 }
1085 }
1086 else {
1087 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 }
1089 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001090}
1091
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001092PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001093"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001094\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001095Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1096When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001097exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001098
1099
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001100/*[clinic input]
1101globals as builtin_globals
1102
1103Return the dictionary containing the current scope's global variables.
1104
1105NOTE: Updates to this dictionary *will* affect name lookups in the current
1106global scope and vice-versa.
1107[clinic start generated code]*/
1108
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001109static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001110builtin_globals_impl(PyObject *module)
1111/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 d = PyEval_GetGlobals();
1116 Py_XINCREF(d);
1117 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001118}
1119
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001120
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001121/*[clinic input]
1122hasattr as builtin_hasattr
1123
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001124 obj: object
1125 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001126 /
1127
1128Return whether the object has an attribute with the given name.
1129
1130This is done by calling getattr(obj, name) and catching AttributeError.
1131[clinic start generated code]*/
1132
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001133static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001134builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1135/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001136{
1137 PyObject *v;
1138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 if (!PyUnicode_Check(name)) {
1140 PyErr_SetString(PyExc_TypeError,
1141 "hasattr(): attribute name must be string");
1142 return NULL;
1143 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001144 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001145 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001147 if (v == NULL) {
1148 Py_RETURN_FALSE;
1149 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001151 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001152}
1153
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001154
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001155/* AC: gdb's integration with CPython relies on builtin_id having
1156 * the *exact* parameter names of "self" and "v", so we ensure we
1157 * preserve those name rather than using the AC defaults.
1158 */
1159/*[clinic input]
1160id as builtin_id
1161
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001162 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001163 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001164 /
1165
1166Return the identity of an object.
1167
1168This is guaranteed to be unique among simultaneously existing objects.
1169(CPython uses the object's memory address.)
1170[clinic start generated code]*/
1171
Guido van Rossum79f25d91997-04-29 20:08:16 +00001172static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001173builtin_id(PyModuleDef *self, PyObject *v)
1174/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001177}
1178
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001179
Raymond Hettingera6c60372008-03-13 01:26:19 +00001180/* map object ************************************************************/
1181
1182typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 PyObject_HEAD
1184 PyObject *iters;
1185 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001186} mapobject;
1187
Guido van Rossum79f25d91997-04-29 20:08:16 +00001188static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001189map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 PyObject *it, *iters, *func;
1192 mapobject *lz;
1193 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001194
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001195 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 numargs = PyTuple_Size(args);
1199 if (numargs < 2) {
1200 PyErr_SetString(PyExc_TypeError,
1201 "map() must have at least two arguments.");
1202 return NULL;
1203 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 iters = PyTuple_New(numargs-1);
1206 if (iters == NULL)
1207 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 for (i=1 ; i<numargs ; i++) {
1210 /* Get iterator. */
1211 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1212 if (it == NULL) {
1213 Py_DECREF(iters);
1214 return NULL;
1215 }
1216 PyTuple_SET_ITEM(iters, i-1, it);
1217 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 /* create mapobject structure */
1220 lz = (mapobject *)type->tp_alloc(type, 0);
1221 if (lz == NULL) {
1222 Py_DECREF(iters);
1223 return NULL;
1224 }
1225 lz->iters = iters;
1226 func = PyTuple_GET_ITEM(args, 0);
1227 Py_INCREF(func);
1228 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001231}
1232
1233static void
1234map_dealloc(mapobject *lz)
1235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 PyObject_GC_UnTrack(lz);
1237 Py_XDECREF(lz->iters);
1238 Py_XDECREF(lz->func);
1239 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001240}
1241
1242static int
1243map_traverse(mapobject *lz, visitproc visit, void *arg)
1244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 Py_VISIT(lz->iters);
1246 Py_VISIT(lz->func);
1247 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001248}
1249
1250static PyObject *
1251map_next(mapobject *lz)
1252{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001253 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001254 PyObject **stack;
1255 Py_ssize_t niters, nargs, i;
1256 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001257
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001258 niters = PyTuple_GET_SIZE(lz->iters);
1259 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1260 stack = small_stack;
1261 }
1262 else {
1263 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1264 if (stack == NULL) {
1265 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 return NULL;
1267 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001269
1270 nargs = 0;
1271 for (i=0; i < niters; i++) {
1272 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1273 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1274 if (val == NULL) {
1275 goto exit;
1276 }
1277 stack[i] = val;
1278 nargs++;
1279 }
1280
1281 result = _PyObject_FastCall(lz->func, stack, nargs);
1282
1283exit:
1284 for (i=0; i < nargs; i++) {
1285 Py_DECREF(stack[i]);
1286 }
1287 if (stack != small_stack) {
1288 PyMem_Free(stack);
1289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001291}
1292
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001293static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301294map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001295{
1296 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1297 PyObject *args = PyTuple_New(numargs+1);
1298 Py_ssize_t i;
1299 if (args == NULL)
1300 return NULL;
1301 Py_INCREF(lz->func);
1302 PyTuple_SET_ITEM(args, 0, lz->func);
1303 for (i = 0; i<numargs; i++){
1304 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1305 Py_INCREF(it);
1306 PyTuple_SET_ITEM(args, i+1, it);
1307 }
1308
1309 return Py_BuildValue("ON", Py_TYPE(lz), args);
1310}
1311
1312static PyMethodDef map_methods[] = {
1313 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1314 {NULL, NULL} /* sentinel */
1315};
1316
1317
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001318PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001319"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001320\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001321Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001323
Raymond Hettingera6c60372008-03-13 01:26:19 +00001324PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1326 "map", /* tp_name */
1327 sizeof(mapobject), /* tp_basicsize */
1328 0, /* tp_itemsize */
1329 /* methods */
1330 (destructor)map_dealloc, /* tp_dealloc */
1331 0, /* tp_print */
1332 0, /* tp_getattr */
1333 0, /* tp_setattr */
1334 0, /* tp_reserved */
1335 0, /* tp_repr */
1336 0, /* tp_as_number */
1337 0, /* tp_as_sequence */
1338 0, /* tp_as_mapping */
1339 0, /* tp_hash */
1340 0, /* tp_call */
1341 0, /* tp_str */
1342 PyObject_GenericGetAttr, /* tp_getattro */
1343 0, /* tp_setattro */
1344 0, /* tp_as_buffer */
1345 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1346 Py_TPFLAGS_BASETYPE, /* tp_flags */
1347 map_doc, /* tp_doc */
1348 (traverseproc)map_traverse, /* tp_traverse */
1349 0, /* tp_clear */
1350 0, /* tp_richcompare */
1351 0, /* tp_weaklistoffset */
1352 PyObject_SelfIter, /* tp_iter */
1353 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001354 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 0, /* tp_members */
1356 0, /* tp_getset */
1357 0, /* tp_base */
1358 0, /* tp_dict */
1359 0, /* tp_descr_get */
1360 0, /* tp_descr_set */
1361 0, /* tp_dictoffset */
1362 0, /* tp_init */
1363 PyType_GenericAlloc, /* tp_alloc */
1364 map_new, /* tp_new */
1365 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001366};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001367
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001368
1369/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001370static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001371builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyObject *it, *res;
1374 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001375
Sylvain96c7c062017-06-15 17:05:23 +02001376 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
1377 return NULL;
1378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (!PyIter_Check(it)) {
1380 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001381 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 it->ob_type->tp_name);
1383 return NULL;
1384 }
1385
1386 res = (*it->ob_type->tp_iternext)(it);
1387 if (res != NULL) {
1388 return res;
1389 } else if (def != NULL) {
1390 if (PyErr_Occurred()) {
1391 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1392 return NULL;
1393 PyErr_Clear();
1394 }
1395 Py_INCREF(def);
1396 return def;
1397 } else if (PyErr_Occurred()) {
1398 return NULL;
1399 } else {
1400 PyErr_SetNone(PyExc_StopIteration);
1401 return NULL;
1402 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001403}
1404
1405PyDoc_STRVAR(next_doc,
1406"next(iterator[, default])\n\
1407\n\
1408Return the next item from the iterator. If default is given and the iterator\n\
1409is exhausted, it is returned instead of raising StopIteration.");
1410
1411
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001412/*[clinic input]
1413setattr as builtin_setattr
1414
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001415 obj: object
1416 name: object
1417 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001418 /
1419
1420Sets the named attribute on the given object to the specified value.
1421
1422setattr(x, 'y', v) is equivalent to ``x.y = v''
1423[clinic start generated code]*/
1424
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001425static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001426builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001427 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001428/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001429{
1430 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001432 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001433}
1434
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001435
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001436/*[clinic input]
1437delattr as builtin_delattr
1438
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001439 obj: object
1440 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001441 /
1442
1443Deletes the named attribute from the given object.
1444
1445delattr(x, 'y') is equivalent to ``del x.y''
1446[clinic start generated code]*/
1447
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001448static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001449builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1450/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001451{
1452 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001454 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001455}
1456
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001457
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001458/*[clinic input]
1459hash as builtin_hash
1460
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001461 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001462 /
1463
1464Return the hash value for the given object.
1465
1466Two objects that compare equal must also have the same hash value, but the
1467reverse is not necessarily true.
1468[clinic start generated code]*/
1469
Guido van Rossum79f25d91997-04-29 20:08:16 +00001470static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001471builtin_hash(PyObject *module, PyObject *obj)
1472/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001473{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001474 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001475
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001476 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (x == -1)
1478 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001479 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001480}
1481
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001482
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001483/*[clinic input]
1484hex as builtin_hex
1485
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001486 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001487 /
1488
1489Return the hexadecimal representation of an integer.
1490
1491 >>> hex(12648430)
1492 '0xc0ffee'
1493[clinic start generated code]*/
1494
Guido van Rossum79f25d91997-04-29 20:08:16 +00001495static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001496builtin_hex(PyObject *module, PyObject *number)
1497/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001498{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001499 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001500}
1501
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001502
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001503/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001504static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001505builtin_iter(PyObject *self, PyObject *args)
1506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1510 return NULL;
1511 if (w == NULL)
1512 return PyObject_GetIter(v);
1513 if (!PyCallable_Check(v)) {
1514 PyErr_SetString(PyExc_TypeError,
1515 "iter(v, w): v must be callable");
1516 return NULL;
1517 }
1518 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001519}
1520
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001521PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001522"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001523iter(callable, sentinel) -> iterator\n\
1524\n\
1525Get an iterator from an object. In the first form, the argument must\n\
1526supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001527In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001528
1529
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001530/*[clinic input]
1531len as builtin_len
1532
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001533 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001534 /
1535
1536Return the number of items in a container.
1537[clinic start generated code]*/
1538
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001539static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001540builtin_len(PyObject *module, PyObject *obj)
1541/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001544
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001545 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001546 if (res < 0) {
1547 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001549 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001551}
1552
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001553
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001554/*[clinic input]
1555locals as builtin_locals
1556
1557Return a dictionary containing the current scope's local variables.
1558
1559NOTE: Whether or not updates to this dictionary will affect name lookups in
1560the local scope and vice-versa is *implementation dependent* and not
1561covered by any backwards compatibility guarantees.
1562[clinic start generated code]*/
1563
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001564static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001565builtin_locals_impl(PyObject *module)
1566/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 d = PyEval_GetLocals();
1571 Py_XINCREF(d);
1572 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001573}
1574
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001575
Guido van Rossum79f25d91997-04-29 20:08:16 +00001576static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001577min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001580 PyObject *emptytuple, *defaultval = NULL;
1581 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001583 const int positional = PyTuple_Size(args) > 1;
1584 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001585
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001586 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001588 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001590
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001591 emptytuple = PyTuple_New(0);
1592 if (emptytuple == NULL)
1593 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001594 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1595 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1596 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001597 Py_DECREF(emptytuple);
1598 if (!ret)
1599 return NULL;
1600
1601 if (positional && defaultval != NULL) {
1602 PyErr_Format(PyExc_TypeError,
1603 "Cannot specify a default for %s() with multiple "
1604 "positional arguments", name);
1605 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 it = PyObject_GetIter(v);
1609 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 return NULL;
1611 }
Tim Petersc3074532001-05-03 07:00:32 +00001612
Alexander Marshalove22072f2018-07-24 10:58:21 +07001613 if (keyfunc == Py_None) {
1614 keyfunc = NULL;
1615 }
1616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 maxitem = NULL; /* the result */
1618 maxval = NULL; /* the value associated with the result */
1619 while (( item = PyIter_Next(it) )) {
1620 /* get the value from the key function */
1621 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001622 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (val == NULL)
1624 goto Fail_it_item;
1625 }
1626 /* no key function; the value is the item */
1627 else {
1628 val = item;
1629 Py_INCREF(val);
1630 }
Tim Petersc3074532001-05-03 07:00:32 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 /* maximum value and item are unset; set them */
1633 if (maxval == NULL) {
1634 maxitem = item;
1635 maxval = val;
1636 }
1637 /* maximum value and item are set; update them as necessary */
1638 else {
1639 int cmp = PyObject_RichCompareBool(val, maxval, op);
1640 if (cmp < 0)
1641 goto Fail_it_item_and_val;
1642 else if (cmp > 0) {
1643 Py_DECREF(maxval);
1644 Py_DECREF(maxitem);
1645 maxval = val;
1646 maxitem = item;
1647 }
1648 else {
1649 Py_DECREF(item);
1650 Py_DECREF(val);
1651 }
1652 }
1653 }
1654 if (PyErr_Occurred())
1655 goto Fail_it;
1656 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001658 if (defaultval != NULL) {
1659 Py_INCREF(defaultval);
1660 maxitem = defaultval;
1661 } else {
1662 PyErr_Format(PyExc_ValueError,
1663 "%s() arg is an empty sequence", name);
1664 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 }
1666 else
1667 Py_DECREF(maxval);
1668 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001670
1671Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001673Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001675Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 Py_XDECREF(maxval);
1677 Py_XDECREF(maxitem);
1678 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001680}
1681
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001682/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001683static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001684builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001687}
1688
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001689PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001690"min(iterable, *[, default=obj, key=func]) -> value\n\
1691min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001692\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001693With a single iterable argument, return its smallest item. The\n\
1694default keyword-only argument specifies an object to return if\n\
1695the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001696With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001697
1698
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001699/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001700static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001701builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001704}
1705
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001706PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001707"max(iterable, *[, default=obj, key=func]) -> value\n\
1708max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001709\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001710With a single iterable argument, return its biggest item. The\n\
1711default keyword-only argument specifies an object to return if\n\
1712the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001713With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001714
1715
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001716/*[clinic input]
1717oct as builtin_oct
1718
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001719 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001720 /
1721
1722Return the octal representation of an integer.
1723
1724 >>> oct(342391)
1725 '0o1234567'
1726[clinic start generated code]*/
1727
Guido van Rossum79f25d91997-04-29 20:08:16 +00001728static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001729builtin_oct(PyObject *module, PyObject *number)
1730/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001731{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001732 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001733}
1734
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001735
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001736/*[clinic input]
1737ord as builtin_ord
1738
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001739 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001740 /
1741
1742Return the Unicode code point for a one-character string.
1743[clinic start generated code]*/
1744
Guido van Rossum79f25d91997-04-29 20:08:16 +00001745static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001746builtin_ord(PyObject *module, PyObject *c)
1747/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 long ord;
1750 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001751
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001752 if (PyBytes_Check(c)) {
1753 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001755 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 return PyLong_FromLong(ord);
1757 }
1758 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001759 else if (PyUnicode_Check(c)) {
1760 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001761 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001762 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001764 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 return PyLong_FromLong(ord);
1766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001768 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001770 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001772 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 return PyLong_FromLong(ord);
1774 }
1775 }
1776 else {
1777 PyErr_Format(PyExc_TypeError,
1778 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001779 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 return NULL;
1781 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 PyErr_Format(PyExc_TypeError,
1784 "ord() expected a character, "
1785 "but string of length %zd found",
1786 size);
1787 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001788}
1789
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001790
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001791/*[clinic input]
1792pow as builtin_pow
1793
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001794 x: object
1795 y: object
1796 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001797 /
1798
1799Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1800
1801Some types, such as ints, are able to use a more efficient algorithm when
1802invoked using the three argument form.
1803[clinic start generated code]*/
1804
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001805static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001806builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1807/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001808{
1809 return PyNumber_Power(x, y, z);
1810}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001811
1812
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001813/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001814static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001815builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001816{
INADA Naokibd584f12017-01-19 12:50:34 +01001817 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1818 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001819 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001821
INADA Naokibd584f12017-01-19 12:50:34 +01001822 if (kwnames != NULL &&
1823 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1824 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001825 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001826 }
1827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001829 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001830 if (file == NULL) {
1831 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1832 return NULL;
1833 }
1834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 /* sys.stdout may be None when FILE* stdout isn't connected */
1836 if (file == Py_None)
1837 Py_RETURN_NONE;
1838 }
Guido van Rossum34343512006-11-30 22:13:52 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 if (sep == Py_None) {
1841 sep = NULL;
1842 }
1843 else if (sep && !PyUnicode_Check(sep)) {
1844 PyErr_Format(PyExc_TypeError,
1845 "sep must be None or a string, not %.200s",
1846 sep->ob_type->tp_name);
1847 return NULL;
1848 }
1849 if (end == Py_None) {
1850 end = NULL;
1851 }
1852 else if (end && !PyUnicode_Check(end)) {
1853 PyErr_Format(PyExc_TypeError,
1854 "end must be None or a string, not %.200s",
1855 end->ob_type->tp_name);
1856 return NULL;
1857 }
Guido van Rossum34343512006-11-30 22:13:52 +00001858
INADA Naokibd584f12017-01-19 12:50:34 +01001859 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (i > 0) {
1861 if (sep == NULL)
1862 err = PyFile_WriteString(" ", file);
1863 else
1864 err = PyFile_WriteObject(sep, file,
1865 Py_PRINT_RAW);
1866 if (err)
1867 return NULL;
1868 }
INADA Naokibd584f12017-01-19 12:50:34 +01001869 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 if (err)
1871 return NULL;
1872 }
Guido van Rossum34343512006-11-30 22:13:52 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (end == NULL)
1875 err = PyFile_WriteString("\n", file);
1876 else
1877 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1878 if (err)
1879 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001880
Georg Brandlbc3b6822012-01-13 19:41:25 +01001881 if (flush != NULL) {
1882 PyObject *tmp;
1883 int do_flush = PyObject_IsTrue(flush);
1884 if (do_flush == -1)
1885 return NULL;
1886 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001887 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001888 if (tmp == NULL)
1889 return NULL;
1890 else
1891 Py_DECREF(tmp);
1892 }
1893 }
1894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001896}
1897
1898PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001899"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001900\n\
1901Prints the values to a stream, or to sys.stdout by default.\n\
1902Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001903file: a file-like object (stream); defaults to the current sys.stdout.\n\
1904sep: string inserted between values, default a space.\n\
1905end: string appended after the last value, default a newline.\n\
1906flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001907
1908
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001909/*[clinic input]
1910input as builtin_input
1911
1912 prompt: object(c_default="NULL") = None
1913 /
1914
1915Read a string from standard input. The trailing newline is stripped.
1916
1917The prompt string, if given, is printed to standard output without a
1918trailing newline before reading input.
1919
1920If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1921On *nix systems, readline is used if available.
1922[clinic start generated code]*/
1923
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001924static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001925builtin_input_impl(PyObject *module, PyObject *prompt)
1926/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001927{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001928 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1929 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1930 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 PyObject *tmp;
1932 long fd;
1933 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 /* Check that stdin/out/err are intact */
1936 if (fin == NULL || fin == Py_None) {
1937 PyErr_SetString(PyExc_RuntimeError,
1938 "input(): lost sys.stdin");
1939 return NULL;
1940 }
1941 if (fout == NULL || fout == Py_None) {
1942 PyErr_SetString(PyExc_RuntimeError,
1943 "input(): lost sys.stdout");
1944 return NULL;
1945 }
1946 if (ferr == NULL || ferr == Py_None) {
1947 PyErr_SetString(PyExc_RuntimeError,
1948 "input(): lost sys.stderr");
1949 return NULL;
1950 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001953 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (tmp == NULL)
1955 PyErr_Clear();
1956 else
1957 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 /* We should only use (GNU) readline if Python's sys.stdin and
1960 sys.stdout are the same as C's stdin and stdout, because we
1961 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001962 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (tmp == NULL) {
1964 PyErr_Clear();
1965 tty = 0;
1966 }
1967 else {
1968 fd = PyLong_AsLong(tmp);
1969 Py_DECREF(tmp);
1970 if (fd < 0 && PyErr_Occurred())
1971 return NULL;
1972 tty = fd == fileno(stdin) && isatty(fd);
1973 }
1974 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001975 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001976 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001978 tty = 0;
1979 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 else {
1981 fd = PyLong_AsLong(tmp);
1982 Py_DECREF(tmp);
1983 if (fd < 0 && PyErr_Occurred())
1984 return NULL;
1985 tty = fd == fileno(stdout) && isatty(fd);
1986 }
1987 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 /* If we're interactive, use (GNU) readline */
1990 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001991 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001992 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001993 char *s = NULL;
1994 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1995 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001996 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001998 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001999
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002000 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002001 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002002 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002003 if (!stdin_encoding || !stdin_errors ||
2004 !PyUnicode_Check(stdin_encoding) ||
2005 !PyUnicode_Check(stdin_errors)) {
2006 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002007 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002008 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002009 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2010 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002011 if (!stdin_encoding_str || !stdin_errors_str)
2012 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07002013 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 if (tmp == NULL)
2015 PyErr_Clear();
2016 else
2017 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002018 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002019 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002020 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002022 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002023 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002024 if (!stdout_encoding || !stdout_errors ||
2025 !PyUnicode_Check(stdout_encoding) ||
2026 !PyUnicode_Check(stdout_errors)) {
2027 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002028 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002029 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002030 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2031 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002032 if (!stdout_encoding_str || !stdout_errors_str)
2033 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002034 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002035 if (stringpo == NULL)
2036 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002038 stdout_encoding_str, stdout_errors_str);
2039 Py_CLEAR(stdout_encoding);
2040 Py_CLEAR(stdout_errors);
2041 Py_CLEAR(stringpo);
2042 if (po == NULL)
2043 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002044 assert(PyBytes_Check(po));
2045 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 }
2047 else {
2048 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002049 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002051 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002053 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if (!PyErr_Occurred())
2055 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002056 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002058
2059 len = strlen(s);
2060 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 PyErr_SetNone(PyExc_EOFError);
2062 result = NULL;
2063 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002064 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (len > PY_SSIZE_T_MAX) {
2066 PyErr_SetString(PyExc_OverflowError,
2067 "input: input too long");
2068 result = NULL;
2069 }
2070 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002071 len--; /* strip trailing '\n' */
2072 if (len != 0 && s[len-1] == '\r')
2073 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002074 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2075 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 }
2077 }
2078 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002079 Py_DECREF(stdin_errors);
2080 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 PyMem_FREE(s);
2082 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002083
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002084 _readline_errors:
2085 Py_XDECREF(stdin_encoding);
2086 Py_XDECREF(stdout_encoding);
2087 Py_XDECREF(stdin_errors);
2088 Py_XDECREF(stdout_errors);
2089 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002090 if (tty)
2091 return NULL;
2092
2093 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002097 if (prompt != NULL) {
2098 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 return NULL;
2100 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002101 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 if (tmp == NULL)
2103 PyErr_Clear();
2104 else
2105 Py_DECREF(tmp);
2106 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002107}
2108
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002109
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002110/*[clinic input]
2111repr as builtin_repr
2112
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002113 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002114 /
2115
2116Return the canonical string representation of the object.
2117
2118For many object types, including most builtins, eval(repr(obj)) == obj.
2119[clinic start generated code]*/
2120
Guido van Rossum79f25d91997-04-29 20:08:16 +00002121static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002122builtin_repr(PyObject *module, PyObject *obj)
2123/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002124{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002125 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002126}
2127
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002128
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002129/*[clinic input]
2130round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002131
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002132 number: object
2133 ndigits: object = NULL
2134
2135Round a number to a given precision in decimal digits.
2136
2137The return value is an integer if ndigits is omitted or None. Otherwise
2138the return value has the same type as the number. ndigits may be negative.
2139[clinic start generated code]*/
2140
2141static PyObject *
2142builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2143/*[clinic end generated code: output=ff0d9dd176c02ede input=854bc3a217530c3d]*/
2144{
2145 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 if (Py_TYPE(number)->tp_dict == NULL) {
2148 if (PyType_Ready(Py_TYPE(number)) < 0)
2149 return NULL;
2150 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002151
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002152 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002154 if (!PyErr_Occurred())
2155 PyErr_Format(PyExc_TypeError,
2156 "type %.100s doesn't define __round__ method",
2157 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 return NULL;
2159 }
Alex Martelliae211f92007-08-22 23:21:33 +00002160
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002161 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002162 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002164 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002165 Py_DECREF(round);
2166 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002167}
2168
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002169
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002170/*AC: we need to keep the kwds dict intact to easily call into the
2171 * list.sort method, which isn't currently supported in AC. So we just use
2172 * the initially generated signature with a custom implementation.
2173 */
2174/* [disabled clinic input]
2175sorted as builtin_sorted
2176
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002177 iterable as seq: object
2178 key as keyfunc: object = None
2179 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002180
2181Return a new list containing all items from the iterable in ascending order.
2182
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002183A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002184reverse flag can be set to request the result in descending order.
2185[end disabled clinic input]*/
2186
2187PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002188"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002189"--\n"
2190"\n"
2191"Return a new list containing all items from the iterable in ascending order.\n"
2192"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002193"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002194"reverse flag can be set to request the result in descending order.");
2195
2196#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002197 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002198
Raymond Hettinger64958a12003-12-17 20:43:33 +00002199static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002200builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002201{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002202 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002203
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002204 /* Keyword arguments are passed through list.sort() which will check
2205 them. */
2206 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 newlist = PySequence_List(seq);
2210 if (newlist == NULL)
2211 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002212
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002213 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (callable == NULL) {
2215 Py_DECREF(newlist);
2216 return NULL;
2217 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002218
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002219 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002220 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 Py_DECREF(callable);
2222 if (v == NULL) {
2223 Py_DECREF(newlist);
2224 return NULL;
2225 }
2226 Py_DECREF(v);
2227 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002228}
2229
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002230
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002231/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002232static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002233builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 PyObject *v = NULL;
2236 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2239 return NULL;
2240 if (v == NULL) {
2241 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002242 if (d == NULL)
2243 return NULL;
2244 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 }
2246 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002247 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if (d == NULL) {
2249 PyErr_SetString(PyExc_TypeError,
2250 "vars() argument must have __dict__ attribute");
2251 return NULL;
2252 }
2253 }
2254 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002255}
2256
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002257PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002258"vars([object]) -> dictionary\n\
2259\n\
2260Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002261With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002262
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002263
2264/*[clinic input]
2265sum as builtin_sum
2266
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002267 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002268 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002269 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002270
2271Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2272
2273When the iterable is empty, return the start value.
2274This function is intended specifically for use with numeric values and may
2275reject non-numeric types.
2276[clinic start generated code]*/
2277
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002278static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002279builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002280/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002281{
2282 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002284
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002285 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (iter == NULL)
2287 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 if (result == NULL) {
2290 result = PyLong_FromLong(0);
2291 if (result == NULL) {
2292 Py_DECREF(iter);
2293 return NULL;
2294 }
2295 } else {
2296 /* reject string values for 'start' parameter */
2297 if (PyUnicode_Check(result)) {
2298 PyErr_SetString(PyExc_TypeError,
2299 "sum() can't sum strings [use ''.join(seq) instead]");
2300 Py_DECREF(iter);
2301 return NULL;
2302 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002303 if (PyBytes_Check(result)) {
2304 PyErr_SetString(PyExc_TypeError,
2305 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002306 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002307 return NULL;
2308 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 if (PyByteArray_Check(result)) {
2310 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002311 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 Py_DECREF(iter);
2313 return NULL;
2314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 Py_INCREF(result);
2316 }
Alex Martellia70b1912003-04-22 08:12:33 +00002317
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002318#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2320 Assumes all inputs are the same type. If the assumption fails, default
2321 to the more general routine.
2322 */
2323 if (PyLong_CheckExact(result)) {
2324 int overflow;
2325 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2326 /* If this already overflowed, don't even enter the loop. */
2327 if (overflow == 0) {
2328 Py_DECREF(result);
2329 result = NULL;
2330 }
2331 while(result == NULL) {
2332 item = PyIter_Next(iter);
2333 if (item == NULL) {
2334 Py_DECREF(iter);
2335 if (PyErr_Occurred())
2336 return NULL;
2337 return PyLong_FromLong(i_result);
2338 }
2339 if (PyLong_CheckExact(item)) {
2340 long b = PyLong_AsLongAndOverflow(item, &overflow);
2341 long x = i_result + b;
2342 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2343 i_result = x;
2344 Py_DECREF(item);
2345 continue;
2346 }
2347 }
2348 /* Either overflowed or is not an int. Restore real objects and process normally */
2349 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002350 if (result == NULL) {
2351 Py_DECREF(item);
2352 Py_DECREF(iter);
2353 return NULL;
2354 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 temp = PyNumber_Add(result, item);
2356 Py_DECREF(result);
2357 Py_DECREF(item);
2358 result = temp;
2359 if (result == NULL) {
2360 Py_DECREF(iter);
2361 return NULL;
2362 }
2363 }
2364 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 if (PyFloat_CheckExact(result)) {
2367 double f_result = PyFloat_AS_DOUBLE(result);
2368 Py_DECREF(result);
2369 result = NULL;
2370 while(result == NULL) {
2371 item = PyIter_Next(iter);
2372 if (item == NULL) {
2373 Py_DECREF(iter);
2374 if (PyErr_Occurred())
2375 return NULL;
2376 return PyFloat_FromDouble(f_result);
2377 }
2378 if (PyFloat_CheckExact(item)) {
2379 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2380 f_result += PyFloat_AS_DOUBLE(item);
2381 PyFPE_END_PROTECT(f_result)
2382 Py_DECREF(item);
2383 continue;
2384 }
2385 if (PyLong_CheckExact(item)) {
2386 long value;
2387 int overflow;
2388 value = PyLong_AsLongAndOverflow(item, &overflow);
2389 if (!overflow) {
2390 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2391 f_result += (double)value;
2392 PyFPE_END_PROTECT(f_result)
2393 Py_DECREF(item);
2394 continue;
2395 }
2396 }
2397 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002398 if (result == NULL) {
2399 Py_DECREF(item);
2400 Py_DECREF(iter);
2401 return NULL;
2402 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 temp = PyNumber_Add(result, item);
2404 Py_DECREF(result);
2405 Py_DECREF(item);
2406 result = temp;
2407 if (result == NULL) {
2408 Py_DECREF(iter);
2409 return NULL;
2410 }
2411 }
2412 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002413#endif
2414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 for(;;) {
2416 item = PyIter_Next(iter);
2417 if (item == NULL) {
2418 /* error, or end-of-sequence */
2419 if (PyErr_Occurred()) {
2420 Py_DECREF(result);
2421 result = NULL;
2422 }
2423 break;
2424 }
2425 /* It's tempting to use PyNumber_InPlaceAdd instead of
2426 PyNumber_Add here, to avoid quadratic running time
2427 when doing 'sum(list_of_lists, [])'. However, this
2428 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 empty = []
2431 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 would change the value of empty. */
2434 temp = PyNumber_Add(result, item);
2435 Py_DECREF(result);
2436 Py_DECREF(item);
2437 result = temp;
2438 if (result == NULL)
2439 break;
2440 }
2441 Py_DECREF(iter);
2442 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002443}
2444
Alex Martellia70b1912003-04-22 08:12:33 +00002445
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002446/*[clinic input]
2447isinstance as builtin_isinstance
2448
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002449 obj: object
2450 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002451 /
2452
2453Return whether an object is an instance of a class or of a subclass thereof.
2454
2455A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2456check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2457or ...`` etc.
2458[clinic start generated code]*/
2459
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002460static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002461builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002462 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002463/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002466
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002467 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 if (retval < 0)
2469 return NULL;
2470 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002471}
2472
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002473
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002474/*[clinic input]
2475issubclass as builtin_issubclass
2476
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002477 cls: object
2478 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002479 /
2480
2481Return whether 'cls' is a derived from another class or is the same class.
2482
2483A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2484check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2485or ...`` etc.
2486[clinic start generated code]*/
2487
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002488static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002489builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002490 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002491/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002494
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002495 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (retval < 0)
2497 return NULL;
2498 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002499}
2500
2501
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002502typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 PyObject_HEAD
2504 Py_ssize_t tuplesize;
2505 PyObject *ittuple; /* tuple of iterators */
2506 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002507} zipobject;
2508
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002509static PyObject *
2510zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 zipobject *lz;
2513 Py_ssize_t i;
2514 PyObject *ittuple; /* tuple of iterators */
2515 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002516 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002517
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002518 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 /* args must be a tuple */
2522 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002523 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 /* obtain iterators */
2526 ittuple = PyTuple_New(tuplesize);
2527 if (ittuple == NULL)
2528 return NULL;
2529 for (i=0; i < tuplesize; ++i) {
2530 PyObject *item = PyTuple_GET_ITEM(args, i);
2531 PyObject *it = PyObject_GetIter(item);
2532 if (it == NULL) {
2533 if (PyErr_ExceptionMatches(PyExc_TypeError))
2534 PyErr_Format(PyExc_TypeError,
2535 "zip argument #%zd must support iteration",
2536 i+1);
2537 Py_DECREF(ittuple);
2538 return NULL;
2539 }
2540 PyTuple_SET_ITEM(ittuple, i, it);
2541 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 /* create a result holder */
2544 result = PyTuple_New(tuplesize);
2545 if (result == NULL) {
2546 Py_DECREF(ittuple);
2547 return NULL;
2548 }
2549 for (i=0 ; i < tuplesize ; i++) {
2550 Py_INCREF(Py_None);
2551 PyTuple_SET_ITEM(result, i, Py_None);
2552 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /* create zipobject structure */
2555 lz = (zipobject *)type->tp_alloc(type, 0);
2556 if (lz == NULL) {
2557 Py_DECREF(ittuple);
2558 Py_DECREF(result);
2559 return NULL;
2560 }
2561 lz->ittuple = ittuple;
2562 lz->tuplesize = tuplesize;
2563 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002566}
2567
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002568static void
2569zip_dealloc(zipobject *lz)
2570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 PyObject_GC_UnTrack(lz);
2572 Py_XDECREF(lz->ittuple);
2573 Py_XDECREF(lz->result);
2574 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002575}
2576
2577static int
2578zip_traverse(zipobject *lz, visitproc visit, void *arg)
2579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 Py_VISIT(lz->ittuple);
2581 Py_VISIT(lz->result);
2582 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002583}
2584
2585static PyObject *
2586zip_next(zipobject *lz)
2587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 Py_ssize_t i;
2589 Py_ssize_t tuplesize = lz->tuplesize;
2590 PyObject *result = lz->result;
2591 PyObject *it;
2592 PyObject *item;
2593 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 if (tuplesize == 0)
2596 return NULL;
2597 if (Py_REFCNT(result) == 1) {
2598 Py_INCREF(result);
2599 for (i=0 ; i < tuplesize ; i++) {
2600 it = PyTuple_GET_ITEM(lz->ittuple, i);
2601 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002602 if (item == NULL) {
2603 Py_DECREF(result);
2604 return NULL;
2605 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 olditem = PyTuple_GET_ITEM(result, i);
2607 PyTuple_SET_ITEM(result, i, item);
2608 Py_DECREF(olditem);
2609 }
2610 } else {
2611 result = PyTuple_New(tuplesize);
2612 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002613 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 for (i=0 ; i < tuplesize ; i++) {
2615 it = PyTuple_GET_ITEM(lz->ittuple, i);
2616 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002617 if (item == NULL) {
2618 Py_DECREF(result);
2619 return NULL;
2620 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 PyTuple_SET_ITEM(result, i, item);
2622 }
2623 }
2624 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002625}
Barry Warsawbd599b52000-08-03 15:45:29 +00002626
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002627static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302628zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002629{
2630 /* Just recreate the zip with the internal iterator tuple */
2631 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2632}
2633
2634static PyMethodDef zip_methods[] = {
2635 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2636 {NULL, NULL} /* sentinel */
2637};
2638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002639PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002640"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002641\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002642Return a zip object whose .__next__() method returns a tuple where\n\
2643the i-th element comes from the i-th iterable argument. The .__next__()\n\
2644method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002645is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002646
2647PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2649 "zip", /* tp_name */
2650 sizeof(zipobject), /* tp_basicsize */
2651 0, /* tp_itemsize */
2652 /* methods */
2653 (destructor)zip_dealloc, /* tp_dealloc */
2654 0, /* tp_print */
2655 0, /* tp_getattr */
2656 0, /* tp_setattr */
2657 0, /* tp_reserved */
2658 0, /* tp_repr */
2659 0, /* tp_as_number */
2660 0, /* tp_as_sequence */
2661 0, /* tp_as_mapping */
2662 0, /* tp_hash */
2663 0, /* tp_call */
2664 0, /* tp_str */
2665 PyObject_GenericGetAttr, /* tp_getattro */
2666 0, /* tp_setattro */
2667 0, /* tp_as_buffer */
2668 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2669 Py_TPFLAGS_BASETYPE, /* tp_flags */
2670 zip_doc, /* tp_doc */
2671 (traverseproc)zip_traverse, /* tp_traverse */
2672 0, /* tp_clear */
2673 0, /* tp_richcompare */
2674 0, /* tp_weaklistoffset */
2675 PyObject_SelfIter, /* tp_iter */
2676 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002677 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 0, /* tp_members */
2679 0, /* tp_getset */
2680 0, /* tp_base */
2681 0, /* tp_dict */
2682 0, /* tp_descr_get */
2683 0, /* tp_descr_set */
2684 0, /* tp_dictoffset */
2685 0, /* tp_init */
2686 PyType_GenericAlloc, /* tp_alloc */
2687 zip_new, /* tp_new */
2688 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002689};
Barry Warsawbd599b52000-08-03 15:45:29 +00002690
2691
Guido van Rossum79f25d91997-04-29 20:08:16 +00002692static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 {"__build_class__", (PyCFunction)builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002694 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002696 BUILTIN_ABS_METHODDEF
2697 BUILTIN_ALL_METHODDEF
2698 BUILTIN_ANY_METHODDEF
2699 BUILTIN_ASCII_METHODDEF
2700 BUILTIN_BIN_METHODDEF
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002701 {"breakpoint", (PyCFunction)builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002702 BUILTIN_CALLABLE_METHODDEF
2703 BUILTIN_CHR_METHODDEF
2704 BUILTIN_COMPILE_METHODDEF
2705 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002707 BUILTIN_DIVMOD_METHODDEF
2708 BUILTIN_EVAL_METHODDEF
2709 BUILTIN_EXEC_METHODDEF
2710 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002711 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002712 BUILTIN_GLOBALS_METHODDEF
2713 BUILTIN_HASATTR_METHODDEF
2714 BUILTIN_HASH_METHODDEF
2715 BUILTIN_HEX_METHODDEF
2716 BUILTIN_ID_METHODDEF
2717 BUILTIN_INPUT_METHODDEF
2718 BUILTIN_ISINSTANCE_METHODDEF
2719 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002721 BUILTIN_LEN_METHODDEF
2722 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2724 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002725 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002726 BUILTIN_OCT_METHODDEF
2727 BUILTIN_ORD_METHODDEF
2728 BUILTIN_POW_METHODDEF
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002729 {"print", (PyCFunction)builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002730 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002731 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002732 BUILTIN_SETATTR_METHODDEF
2733 BUILTIN_SORTED_METHODDEF
2734 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2736 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002737};
2738
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002739PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002740"Built-in functions, exceptions, and other objects.\n\
2741\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002742Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002743
Martin v. Löwis1a214512008-06-11 05:26:20 +00002744static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 PyModuleDef_HEAD_INIT,
2746 "builtins",
2747 builtin_doc,
2748 -1, /* multiple "initialization" just copies the module dict. */
2749 builtin_methods,
2750 NULL,
2751 NULL,
2752 NULL,
2753 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002754};
2755
2756
Guido van Rossum25ce5661997-08-02 03:10:38 +00002757PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002758_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002761
Victor Stinnerfbca9082018-08-30 00:50:45 +02002762 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
2763
Benjamin Peterson42124a72012-10-30 23:41:54 -04002764 if (PyType_Ready(&PyFilter_Type) < 0 ||
2765 PyType_Ready(&PyMap_Type) < 0 ||
2766 PyType_Ready(&PyZip_Type) < 0)
2767 return NULL;
2768
Eric Snowd393c1b2017-09-14 12:18:12 -06002769 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 if (mod == NULL)
2771 return NULL;
2772 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002773
Tim Peters7571a0f2003-03-23 17:52:28 +00002774#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 /* "builtins" exposes a number of statically allocated objects
2776 * that, before this code was added in 2.3, never showed up in
2777 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2778 * result, programs leaking references to None and False (etc)
2779 * couldn't be diagnosed by examining sys.getobjects(0).
2780 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002781#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2782#else
2783#define ADD_TO_ALL(OBJECT) (void)0
2784#endif
2785
Tim Peters4b7625e2001-09-13 21:37:17 +00002786#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2788 return NULL; \
2789 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 SETBUILTIN("None", Py_None);
2792 SETBUILTIN("Ellipsis", Py_Ellipsis);
2793 SETBUILTIN("NotImplemented", Py_NotImplemented);
2794 SETBUILTIN("False", Py_False);
2795 SETBUILTIN("True", Py_True);
2796 SETBUILTIN("bool", &PyBool_Type);
2797 SETBUILTIN("memoryview", &PyMemoryView_Type);
2798 SETBUILTIN("bytearray", &PyByteArray_Type);
2799 SETBUILTIN("bytes", &PyBytes_Type);
2800 SETBUILTIN("classmethod", &PyClassMethod_Type);
2801 SETBUILTIN("complex", &PyComplex_Type);
2802 SETBUILTIN("dict", &PyDict_Type);
2803 SETBUILTIN("enumerate", &PyEnum_Type);
2804 SETBUILTIN("filter", &PyFilter_Type);
2805 SETBUILTIN("float", &PyFloat_Type);
2806 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2807 SETBUILTIN("property", &PyProperty_Type);
2808 SETBUILTIN("int", &PyLong_Type);
2809 SETBUILTIN("list", &PyList_Type);
2810 SETBUILTIN("map", &PyMap_Type);
2811 SETBUILTIN("object", &PyBaseObject_Type);
2812 SETBUILTIN("range", &PyRange_Type);
2813 SETBUILTIN("reversed", &PyReversed_Type);
2814 SETBUILTIN("set", &PySet_Type);
2815 SETBUILTIN("slice", &PySlice_Type);
2816 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2817 SETBUILTIN("str", &PyUnicode_Type);
2818 SETBUILTIN("super", &PySuper_Type);
2819 SETBUILTIN("tuple", &PyTuple_Type);
2820 SETBUILTIN("type", &PyType_Type);
2821 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002822 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002824 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 return NULL;
2826 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002827 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002830#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002831#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002832}