blob: b0162e5e87217a7d0bea0d5399a50214cfc2c1a3 [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 Stinnereec8e612021-03-18 14:57:49 +01005#include "pycore_ast.h" // _PyAST_Validate()
Victor Stinnera81fca62021-03-24 00:51:50 +01006#include "pycore_compile.h" // _PyAST_Compile()
Victor Stinnerc96d00e2020-06-22 18:02:49 +02007#include "pycore_object.h" // _Py_AddToAllObjects()
Victor Stinner384621c2020-06-22 17:27:35 +02008#include "pycore_pyerrors.h" // _PyErr_NoMemory()
9#include "pycore_pystate.h" // _PyThreadState_GET()
10#include "pycore_tuple.h" // _PyTuple_FromArray()
Mark Shannon0332e562021-02-01 10:42:03 +000011#include "pycore_ceval.h" // _PyEval_Vector()
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012
Victor Stinnerbd303c12013-11-07 23:07:29 +010013_Py_IDENTIFIER(__builtins__);
14_Py_IDENTIFIER(__dict__);
15_Py_IDENTIFIER(__prepare__);
16_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010017_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010018_Py_IDENTIFIER(encoding);
19_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020020_Py_IDENTIFIER(fileno);
21_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010022_Py_IDENTIFIER(metaclass);
23_Py_IDENTIFIER(sort);
24_Py_IDENTIFIER(stdin);
25_Py_IDENTIFIER(stdout);
26_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020027
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030028#include "clinic/bltinmodule.c.h"
29
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010030static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010031update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010032{
Victor Stinner05d68a82018-01-18 11:15:25 +010033 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010034 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010035 assert(PyTuple_Check(bases));
36
37 for (i = 0; i < nargs; i++) {
38 base = args[i];
39 if (PyType_Check(base)) {
40 if (new_bases) {
41 /* If we already have made a replacement, then we append every normal base,
42 otherwise just skip it. */
43 if (PyList_Append(new_bases, base) < 0) {
44 goto error;
45 }
46 }
47 continue;
48 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020049 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
50 goto error;
51 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010052 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010053 if (new_bases) {
54 if (PyList_Append(new_bases, base) < 0) {
55 goto error;
56 }
57 }
58 continue;
59 }
Petr Viktorinffd97532020-02-11 17:46:57 +010060 new_base = PyObject_CallOneArg(meth, bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010061 Py_DECREF(meth);
62 if (!new_base) {
63 goto error;
64 }
65 if (!PyTuple_Check(new_base)) {
66 PyErr_SetString(PyExc_TypeError,
67 "__mro_entries__ must return a tuple");
68 Py_DECREF(new_base);
69 goto error;
70 }
71 if (!new_bases) {
72 /* If this is a first successful replacement, create new_bases list and
73 copy previously encountered bases. */
74 if (!(new_bases = PyList_New(i))) {
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -070075 Py_DECREF(new_base);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010076 goto error;
77 }
78 for (j = 0; j < i; j++) {
79 base = args[j];
80 PyList_SET_ITEM(new_bases, j, base);
81 Py_INCREF(base);
82 }
83 }
84 j = PyList_GET_SIZE(new_bases);
85 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -070086 Py_DECREF(new_base);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010087 goto error;
88 }
89 Py_DECREF(new_base);
90 }
91 if (!new_bases) {
92 return bases;
93 }
94 result = PyList_AsTuple(new_bases);
95 Py_DECREF(new_bases);
96 return result;
97
98error:
99 Py_XDECREF(new_bases);
100 return NULL;
101}
102
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000103/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000104static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200105builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100106 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000107{
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -0700108 PyObject *func, *name, *winner, *prep;
109 PyObject *cls = NULL, *cell = NULL, *ns = NULL, *meta = NULL, *orig_bases = NULL;
110 PyObject *mkw = NULL, *bases = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100111 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 if (nargs < 2) {
114 PyErr_SetString(PyExc_TypeError,
115 "__build_class__: not enough arguments");
116 return NULL;
117 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100118 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500119 if (!PyFunction_Check(func)) {
120 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500121 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500122 return NULL;
123 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100124 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 if (!PyUnicode_Check(name)) {
126 PyErr_SetString(PyExc_TypeError,
127 "__build_class__: name is not a string");
128 return NULL;
129 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500130 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100131 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000133
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100134 bases = update_bases(orig_bases, args + 2, nargs - 2);
135 if (bases == NULL) {
136 Py_DECREF(orig_bases);
137 return NULL;
138 }
139
Victor Stinner773dc6d2017-01-16 23:46:26 +0100140 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 meta = NULL;
142 mkw = NULL;
143 }
144 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100145 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 if (mkw == NULL) {
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -0700147 goto error;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000148 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100149
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200150 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (meta != NULL) {
152 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100153 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -0700154 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 }
Nick Coghlande31b192011-10-23 22:04:16 +1000156 /* metaclass is explicitly given, check if it's indeed a class */
157 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200159 else if (PyErr_Occurred()) {
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -0700160 goto error;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200161 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 }
163 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000164 /* if there are no bases, use type: */
165 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000167 }
168 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 else {
170 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
Victor Stinnera102ed72020-02-07 02:24:48 +0100171 meta = (PyObject *)Py_TYPE(base0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 }
173 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000174 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000176
Nick Coghlande31b192011-10-23 22:04:16 +1000177 if (isclass) {
178 /* meta is really a class, so check for a more derived
179 metaclass, or possible metaclass conflicts: */
180 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
181 bases);
182 if (winner == NULL) {
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -0700183 goto error;
Nick Coghlande31b192011-10-23 22:04:16 +1000184 }
185 if (winner != meta) {
186 Py_DECREF(meta);
187 meta = winner;
188 Py_INCREF(meta);
189 }
190 }
191 /* else: meta is not a class, so we cannot do the metaclass
192 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200193 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
194 ns = NULL;
195 }
196 else if (prep == NULL) {
197 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 }
199 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200200 PyObject *pargs[2] = {name, bases};
Petr Viktorinffd97532020-02-11 17:46:57 +0100201 ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 Py_DECREF(prep);
203 }
204 if (ns == NULL) {
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -0700205 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 }
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 }
Mark Shannon0332e562021-02-01 10:42:03 +0000214 PyFrameConstructor *f = PyFunction_AS_FRAME_CONSTRUCTOR(func);
215 PyThreadState *tstate = PyThreadState_GET();
216 cell = _PyEval_Vector(tstate, f, ns, NULL, 0, NULL);
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};
Petr Viktorinffd97532020-02-11 17:46:57 +0100224 cls = PyObject_VectorcallDict(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);
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -0700246 Py_XDECREF(ns);
247 Py_XDECREF(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_XDECREF(mkw);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100249 if (bases != orig_bases) {
250 Py_DECREF(orig_bases);
251 }
Miss Islington (bot)ac8f72c2021-08-07 07:03:17 -0700252 Py_DECREF(bases);
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,
Pablo Galindoe3babbd2019-10-13 16:35:41 +0100257"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000258\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 }
Steve Dower60419a72019-06-24 08:42:54 -0700478
479 if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
480 return NULL;
481 }
482
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400483 Py_INCREF(hook);
Petr Viktorinffd97532020-02-11 17:46:57 +0100484 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400485 Py_DECREF(hook);
486 return retval;
487}
488
489PyDoc_STRVAR(breakpoint_doc,
490"breakpoint(*args, **kws)\n\
491\n\
492Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
493whatever arguments are passed.\n\
494\n\
495By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000496
Raymond Hettinger17301e92008-03-13 00:19:26 +0000497typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 PyObject_HEAD
499 PyObject *func;
500 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000501} filterobject;
502
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000503static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000504filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 PyObject *func, *seq;
507 PyObject *it;
508 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000509
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300510 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
514 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* Get iterator. */
517 it = PyObject_GetIter(seq);
518 if (it == NULL)
519 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 /* create filterobject structure */
522 lz = (filterobject *)type->tp_alloc(type, 0);
523 if (lz == NULL) {
524 Py_DECREF(it);
525 return NULL;
526 }
Dong-hee Na9a9c11a2021-03-11 01:39:52 +0900527
528 lz->func = Py_NewRef(func);
529 lz->it = it;
530
531 return (PyObject *)lz;
532}
533
534static PyObject *
535filter_vectorcall(PyObject *type, PyObject * const*args,
536 size_t nargsf, PyObject *kwnames)
537{
538 PyTypeObject *tp = (PyTypeObject *)type;
539 if (tp == &PyFilter_Type && !_PyArg_NoKwnames("filter", kwnames)) {
540 return NULL;
541 }
542
543 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
544 if (!_PyArg_CheckPositional("filter", nargs, 2, 2)) {
545 return NULL;
546 }
547
548 PyObject *it = PyObject_GetIter(args[1]);
549 if (it == NULL) {
550 return NULL;
551 }
552
553 filterobject *lz = (filterobject *)tp->tp_alloc(tp, 0);
554
555 if (lz == NULL) {
556 Py_DECREF(it);
557 return NULL;
558 }
559
560 lz->func = Py_NewRef(args[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000564}
565
566static void
567filter_dealloc(filterobject *lz)
568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 PyObject_GC_UnTrack(lz);
570 Py_XDECREF(lz->func);
571 Py_XDECREF(lz->it);
572 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000573}
574
575static int
576filter_traverse(filterobject *lz, visitproc visit, void *arg)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 Py_VISIT(lz->it);
579 Py_VISIT(lz->func);
580 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000581}
582
583static PyObject *
584filter_next(filterobject *lz)
585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 PyObject *item;
587 PyObject *it = lz->it;
588 long ok;
589 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400590 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 iternext = *Py_TYPE(it)->tp_iternext;
593 for (;;) {
594 item = iternext(it);
595 if (item == NULL)
596 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000597
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400598 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 ok = PyObject_IsTrue(item);
600 } else {
601 PyObject *good;
Petr Viktorinffd97532020-02-11 17:46:57 +0100602 good = PyObject_CallOneArg(lz->func, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (good == NULL) {
604 Py_DECREF(item);
605 return NULL;
606 }
607 ok = PyObject_IsTrue(good);
608 Py_DECREF(good);
609 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200610 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return item;
612 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200613 if (ok < 0)
614 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000616}
617
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000618static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530619filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000620{
621 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
622}
623
624PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
625
626static PyMethodDef filter_methods[] = {
627 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
628 {NULL, NULL} /* sentinel */
629};
630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000631PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000632"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000633\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000634Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000635is true. If function is None, return the items that are true.");
636
637PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyVarObject_HEAD_INIT(&PyType_Type, 0)
639 "filter", /* tp_name */
640 sizeof(filterobject), /* tp_basicsize */
641 0, /* tp_itemsize */
642 /* methods */
643 (destructor)filter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200644 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 0, /* tp_getattr */
646 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200647 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 0, /* tp_repr */
649 0, /* tp_as_number */
650 0, /* tp_as_sequence */
651 0, /* tp_as_mapping */
652 0, /* tp_hash */
653 0, /* tp_call */
654 0, /* tp_str */
655 PyObject_GenericGetAttr, /* tp_getattro */
656 0, /* tp_setattro */
657 0, /* tp_as_buffer */
658 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
659 Py_TPFLAGS_BASETYPE, /* tp_flags */
660 filter_doc, /* tp_doc */
661 (traverseproc)filter_traverse, /* tp_traverse */
662 0, /* tp_clear */
663 0, /* tp_richcompare */
664 0, /* tp_weaklistoffset */
665 PyObject_SelfIter, /* tp_iter */
666 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000667 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 0, /* tp_members */
669 0, /* tp_getset */
670 0, /* tp_base */
671 0, /* tp_dict */
672 0, /* tp_descr_get */
673 0, /* tp_descr_set */
674 0, /* tp_dictoffset */
675 0, /* tp_init */
676 PyType_GenericAlloc, /* tp_alloc */
677 filter_new, /* tp_new */
678 PyObject_GC_Del, /* tp_free */
Dong-hee Na9a9c11a2021-03-11 01:39:52 +0900679 .tp_vectorcall = (vectorcallfunc)filter_vectorcall
Raymond Hettinger17301e92008-03-13 00:19:26 +0000680};
681
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000682
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000683/*[clinic input]
684format as builtin_format
685
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300686 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000687 format_spec: unicode(c_default="NULL") = ''
688 /
689
690Return value.__format__(format_spec)
691
Amit Kumar2e6bb442017-05-29 06:32:26 +0530692format_spec defaults to the empty string.
693See the Format Specification Mini-Language section of help('FORMATTING') for
694details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000695[clinic start generated code]*/
696
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000697static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300698builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530699/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000700{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000701 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000702}
703
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000704/*[clinic input]
705chr as builtin_chr
706
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300707 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000708 /
709
710Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
711[clinic start generated code]*/
712
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000713static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300714builtin_chr_impl(PyObject *module, int i)
715/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000716{
717 return PyUnicode_FromOrdinal(i);
718}
Guido van Rossum09095f32000-03-10 23:00:52 +0000719
720
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000721/*[clinic input]
722compile as builtin_compile
723
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300724 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000725 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300726 mode: str
727 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200728 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300729 optimize: int = -1
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200730 *
731 _feature_version as feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000732
733Compile source into a code object that can be executed by exec() or eval().
734
735The source code may represent a Python module, statement or expression.
736The filename will be used for run-time error messages.
737The mode must be 'exec' to compile a module, 'single' to compile a
738single (interactive) statement, or 'eval' to compile an expression.
739The flags argument, if present, controls which future statements influence
740the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300741The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000742the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300743compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000744in addition to any features explicitly specified.
745[clinic start generated code]*/
746
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000747static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300748builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
749 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800750 int optimize, int feature_version)
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200751/*[clinic end generated code: output=b0c09c84f116d3d7 input=40171fb92c1d580d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000752{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000753 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200754 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000755 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 int is_ast;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800757 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000758 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759
Victor Stinner37d66d72019-06-13 02:16:41 +0200760 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000761 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800762 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
763 cf.cf_feature_version = feature_version;
764 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000765
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000766 if (flags &
Batuhan Taşkaya44540572020-04-22 19:09:03 +0300767 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 {
769 PyErr_SetString(PyExc_ValueError,
770 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000771 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 }
773 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000774
Georg Brandl8334fd92010-12-04 10:26:46 +0000775 if (optimize < -1 || optimize > 2) {
776 PyErr_SetString(PyExc_ValueError,
777 "compile(): invalid optimize value");
778 goto error;
779 }
780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (!dont_inherit) {
782 PyEval_MergeCompilerFlags(&cf);
783 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000784
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000785 if (strcmp(mode, "exec") == 0)
786 compile_mode = 0;
787 else if (strcmp(mode, "eval") == 0)
788 compile_mode = 1;
789 else if (strcmp(mode, "single") == 0)
790 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800791 else if (strcmp(mode, "func_type") == 0) {
792 if (!(flags & PyCF_ONLY_AST)) {
793 PyErr_SetString(PyExc_ValueError,
794 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
795 goto error;
796 }
797 compile_mode = 3;
798 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800800 const char *msg;
801 if (flags & PyCF_ONLY_AST)
802 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
803 else
804 msg = "compile() mode must be 'exec', 'eval' or 'single'";
805 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000806 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000808
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000809 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000811 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000813 if (flags & PyCF_ONLY_AST) {
814 Py_INCREF(source);
815 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 }
817 else {
818 PyArena *arena;
819 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000820
Victor Stinner8370e072021-03-24 02:23:01 +0100821 arena = _PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200822 if (arena == NULL)
823 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000824 mod = PyAST_obj2mod(source, arena, compile_mode);
Nick Coghlan1e7b8582021-04-29 15:58:44 +1000825 if (mod == NULL || !_PyAST_Validate(mod)) {
Victor Stinner8370e072021-03-24 02:23:01 +0100826 _PyArena_Free(arena);
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500827 goto error;
828 }
Victor Stinnera81fca62021-03-24 00:51:50 +0100829 result = (PyObject*)_PyAST_Compile(mod, filename,
830 &cf, optimize, arena);
Victor Stinner8370e072021-03-24 02:23:01 +0100831 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000833 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000835
Dino Viehland41540692019-05-28 16:21:17 -0700836 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000838 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000839
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000840 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Guido van Rossumc001c092020-04-30 12:12:19 -0700841
Martin Panter61d6e4a2015-11-07 02:56:11 +0000842 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000843 goto finally;
844
845error:
846 result = NULL;
847finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200848 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000849 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000850}
851
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000852/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000853static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000854builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
859 return NULL;
860 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000861}
862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000863PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000864"dir([object]) -> list of strings\n"
865"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000866"If called without an argument, return the names in the current scope.\n"
867"Else, return an alphabetized list of names comprising (some of) the attributes\n"
868"of the given object, and of attributes reachable from it.\n"
869"If the object supplies a method named __dir__, it will be used; otherwise\n"
870"the default dir() logic is used and returns:\n"
871" for a module object: the module's attributes.\n"
872" for a class object: its attributes, and recursively the attributes\n"
873" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000874" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000875" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000876
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000877/*[clinic input]
878divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000879
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300880 x: object
881 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000882 /
883
Zachary Ware7f227d92016-04-28 14:39:50 -0500884Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000885[clinic start generated code]*/
886
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000887static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300888builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
889/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000890{
891 return PyNumber_Divmod(x, y);
892}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000893
894
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000895/*[clinic input]
896eval as builtin_eval
897
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300898 source: object
899 globals: object = None
900 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000901 /
902
903Evaluate the given source in the context of globals and locals.
904
905The source may be a string representing a Python expression
906or a code object as returned by compile().
907The globals must be a dictionary and locals can be any mapping,
908defaulting to the current globals and locals.
909If only globals is given, locals defaults to it.
910[clinic start generated code]*/
911
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000912static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300913builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400914 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300915/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000916{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000917 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200918 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (locals != Py_None && !PyMapping_Check(locals)) {
921 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
922 return NULL;
923 }
924 if (globals != Py_None && !PyDict_Check(globals)) {
925 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
926 "globals must be a real dict; try eval(expr, {}, mapping)"
927 : "globals must be a dict");
928 return NULL;
929 }
930 if (globals == Py_None) {
931 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100932 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100934 if (locals == NULL)
935 return NULL;
936 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 }
938 else if (locals == Py_None)
939 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (globals == NULL || locals == NULL) {
942 PyErr_SetString(PyExc_TypeError,
943 "eval must be given globals and locals "
944 "when called without a frame");
945 return NULL;
946 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000947
Serhiy Storchakab510e102020-10-26 12:47:57 +0200948 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
949 if (r == 0) {
950 r = _PyDict_SetItemId(globals, &PyId___builtins__,
951 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 }
Serhiy Storchakab510e102020-10-26 12:47:57 +0200953 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200954 return NULL;
955 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000956
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000957 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700958 if (PySys_Audit("exec", "O", source) < 0) {
959 return NULL;
960 }
961
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000962 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700964 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 return NULL;
966 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000967 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000969
Victor Stinner37d66d72019-06-13 02:16:41 +0200970 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700972 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 if (str == NULL)
974 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 while (*str == ' ' || *str == '\t')
977 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 (void)PyEval_MergeCompilerFlags(&cf);
980 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000981 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000983}
984
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000985/*[clinic input]
986exec as builtin_exec
987
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300988 source: object
989 globals: object = None
990 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000991 /
992
993Execute the given source in the context of globals and locals.
994
995The source may be a string representing one or more Python statements
996or a code object as returned by compile().
997The globals must be a dictionary and locals can be any mapping,
998defaulting to the current globals and locals.
999If only globals is given, locals defaults to it.
1000[clinic start generated code]*/
1001
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001002static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001003builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -04001004 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001005/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (globals == Py_None) {
1010 globals = PyEval_GetGlobals();
1011 if (locals == Py_None) {
1012 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001013 if (locals == NULL)
1014 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 }
1016 if (!globals || !locals) {
1017 PyErr_SetString(PyExc_SystemError,
1018 "globals and locals cannot be NULL");
1019 return NULL;
1020 }
1021 }
1022 else if (locals == Py_None)
1023 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001026 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001027 Py_TYPE(globals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 return NULL;
1029 }
1030 if (!PyMapping_Check(locals)) {
1031 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001032 "locals must be a mapping or None, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001033 Py_TYPE(locals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 return NULL;
1035 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001036 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
1037 if (r == 0) {
1038 r = _PyDict_SetItemId(globals, &PyId___builtins__,
1039 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001041 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001042 return NULL;
1043 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001045 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001046 if (PySys_Audit("exec", "O", source) < 0) {
1047 return NULL;
1048 }
1049
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001050 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 PyErr_SetString(PyExc_TypeError,
1052 "code object passed to exec() may not "
1053 "contain free variables");
1054 return NULL;
1055 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001056 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 }
1058 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001059 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001060 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001061 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001063 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001064 "string, bytes or code", &cf,
1065 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 if (str == NULL)
1067 return NULL;
1068 if (PyEval_MergeCompilerFlags(&cf))
1069 v = PyRun_StringFlags(str, Py_file_input, globals,
1070 locals, &cf);
1071 else
1072 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001073 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 }
1075 if (v == NULL)
1076 return NULL;
1077 Py_DECREF(v);
1078 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001079}
1080
Georg Brandl7cae87c2006-09-06 06:51:57 +00001081
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001082/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001083static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001084builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001085{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001086 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001087
Serhiy Storchaka79342662019-01-12 08:25:41 +02001088 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001089 return NULL;
1090
Serhiy Storchaka79342662019-01-12 08:25:41 +02001091 v = args[0];
1092 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (!PyUnicode_Check(name)) {
1094 PyErr_SetString(PyExc_TypeError,
1095 "getattr(): attribute name must be string");
1096 return NULL;
1097 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001098 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001099 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001100 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001101 Py_INCREF(dflt);
1102 return dflt;
1103 }
1104 }
1105 else {
1106 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 }
1108 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001109}
1110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001111PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001112"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001113\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001114Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1115When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001116exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001117
1118
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001119/*[clinic input]
1120globals as builtin_globals
1121
1122Return the dictionary containing the current scope's global variables.
1123
1124NOTE: Updates to this dictionary *will* affect name lookups in the current
1125global scope and vice-versa.
1126[clinic start generated code]*/
1127
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001128static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001129builtin_globals_impl(PyObject *module)
1130/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 d = PyEval_GetGlobals();
1135 Py_XINCREF(d);
1136 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001137}
1138
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001139
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001140/*[clinic input]
1141hasattr as builtin_hasattr
1142
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001143 obj: object
1144 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001145 /
1146
1147Return whether the object has an attribute with the given name.
1148
1149This is done by calling getattr(obj, name) and catching AttributeError.
1150[clinic start generated code]*/
1151
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001152static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001153builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1154/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001155{
1156 PyObject *v;
1157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (!PyUnicode_Check(name)) {
1159 PyErr_SetString(PyExc_TypeError,
1160 "hasattr(): attribute name must be string");
1161 return NULL;
1162 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001163 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001164 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001166 if (v == NULL) {
1167 Py_RETURN_FALSE;
1168 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001170 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001171}
1172
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001173
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001174/* AC: gdb's integration with CPython relies on builtin_id having
1175 * the *exact* parameter names of "self" and "v", so we ensure we
1176 * preserve those name rather than using the AC defaults.
1177 */
1178/*[clinic input]
1179id as builtin_id
1180
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001181 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001182 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001183 /
1184
1185Return the identity of an object.
1186
1187This is guaranteed to be unique among simultaneously existing objects.
1188(CPython uses the object's memory address.)
1189[clinic start generated code]*/
1190
Guido van Rossum79f25d91997-04-29 20:08:16 +00001191static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001192builtin_id(PyModuleDef *self, PyObject *v)
1193/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001194{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001195 PyObject *id = PyLong_FromVoidPtr(v);
1196
1197 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1198 Py_DECREF(id);
1199 return NULL;
1200 }
1201
1202 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001203}
1204
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001205
Raymond Hettingera6c60372008-03-13 01:26:19 +00001206/* map object ************************************************************/
1207
1208typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyObject_HEAD
1210 PyObject *iters;
1211 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001212} mapobject;
1213
Guido van Rossum79f25d91997-04-29 20:08:16 +00001214static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001215map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 PyObject *it, *iters, *func;
1218 mapobject *lz;
1219 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001220
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001221 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 numargs = PyTuple_Size(args);
1225 if (numargs < 2) {
1226 PyErr_SetString(PyExc_TypeError,
1227 "map() must have at least two arguments.");
1228 return NULL;
1229 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 iters = PyTuple_New(numargs-1);
1232 if (iters == NULL)
1233 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 for (i=1 ; i<numargs ; i++) {
1236 /* Get iterator. */
1237 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1238 if (it == NULL) {
1239 Py_DECREF(iters);
1240 return NULL;
1241 }
1242 PyTuple_SET_ITEM(iters, i-1, it);
1243 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 /* create mapobject structure */
1246 lz = (mapobject *)type->tp_alloc(type, 0);
1247 if (lz == NULL) {
1248 Py_DECREF(iters);
1249 return NULL;
1250 }
1251 lz->iters = iters;
1252 func = PyTuple_GET_ITEM(args, 0);
Dong-hee Na86883d42021-03-22 19:01:14 +09001253 lz->func = Py_NewRef(func);
1254
1255 return (PyObject *)lz;
1256}
1257
1258static PyObject *
1259map_vectorcall(PyObject *type, PyObject * const*args,
1260 size_t nargsf, PyObject *kwnames)
1261{
1262 PyTypeObject *tp = (PyTypeObject *)type;
1263 if (tp == &PyMap_Type && !_PyArg_NoKwnames("map", kwnames)) {
1264 return NULL;
1265 }
1266
1267 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1268 if (nargs < 2) {
1269 PyErr_SetString(PyExc_TypeError,
1270 "map() must have at least two arguments.");
1271 return NULL;
1272 }
1273
1274 PyObject *iters = PyTuple_New(nargs-1);
1275 if (iters == NULL) {
1276 return NULL;
1277 }
1278
1279 for (int i=1; i<nargs; i++) {
1280 PyObject *it = PyObject_GetIter(args[i]);
1281 if (it == NULL) {
1282 Py_DECREF(iters);
1283 return NULL;
1284 }
1285 PyTuple_SET_ITEM(iters, i-1, it);
1286 }
1287
1288 mapobject *lz = (mapobject *)tp->tp_alloc(tp, 0);
1289 if (lz == NULL) {
1290 Py_DECREF(iters);
1291 return NULL;
1292 }
1293 lz->iters = iters;
1294 lz->func = Py_NewRef(args[0]);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001297}
1298
1299static void
1300map_dealloc(mapobject *lz)
1301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 PyObject_GC_UnTrack(lz);
1303 Py_XDECREF(lz->iters);
1304 Py_XDECREF(lz->func);
1305 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001306}
1307
1308static int
1309map_traverse(mapobject *lz, visitproc visit, void *arg)
1310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 Py_VISIT(lz->iters);
1312 Py_VISIT(lz->func);
1313 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001314}
1315
1316static PyObject *
1317map_next(mapobject *lz)
1318{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001319 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001320 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001321 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001322 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001323
Victor Stinner4d231bc2019-11-14 13:36:21 +01001324 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001325 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1326 stack = small_stack;
1327 }
1328 else {
1329 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1330 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001331 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 return NULL;
1333 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001335
Victor Stinner4d231bc2019-11-14 13:36:21 +01001336 Py_ssize_t nargs = 0;
1337 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001338 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1339 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1340 if (val == NULL) {
1341 goto exit;
1342 }
1343 stack[i] = val;
1344 nargs++;
1345 }
1346
Victor Stinner4d231bc2019-11-14 13:36:21 +01001347 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001348
1349exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001350 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001351 Py_DECREF(stack[i]);
1352 }
1353 if (stack != small_stack) {
1354 PyMem_Free(stack);
1355 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001357}
1358
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001359static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301360map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001361{
1362 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1363 PyObject *args = PyTuple_New(numargs+1);
1364 Py_ssize_t i;
1365 if (args == NULL)
1366 return NULL;
1367 Py_INCREF(lz->func);
1368 PyTuple_SET_ITEM(args, 0, lz->func);
1369 for (i = 0; i<numargs; i++){
1370 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1371 Py_INCREF(it);
1372 PyTuple_SET_ITEM(args, i+1, it);
1373 }
1374
1375 return Py_BuildValue("ON", Py_TYPE(lz), args);
1376}
1377
1378static PyMethodDef map_methods[] = {
1379 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1380 {NULL, NULL} /* sentinel */
1381};
1382
1383
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001384PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001385"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001386\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001387Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001389
Raymond Hettingera6c60372008-03-13 01:26:19 +00001390PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1392 "map", /* tp_name */
1393 sizeof(mapobject), /* tp_basicsize */
1394 0, /* tp_itemsize */
1395 /* methods */
1396 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001397 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 0, /* tp_getattr */
1399 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001400 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 0, /* tp_repr */
1402 0, /* tp_as_number */
1403 0, /* tp_as_sequence */
1404 0, /* tp_as_mapping */
1405 0, /* tp_hash */
1406 0, /* tp_call */
1407 0, /* tp_str */
1408 PyObject_GenericGetAttr, /* tp_getattro */
1409 0, /* tp_setattro */
1410 0, /* tp_as_buffer */
1411 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1412 Py_TPFLAGS_BASETYPE, /* tp_flags */
1413 map_doc, /* tp_doc */
1414 (traverseproc)map_traverse, /* tp_traverse */
1415 0, /* tp_clear */
1416 0, /* tp_richcompare */
1417 0, /* tp_weaklistoffset */
1418 PyObject_SelfIter, /* tp_iter */
1419 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001420 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 0, /* tp_members */
1422 0, /* tp_getset */
1423 0, /* tp_base */
1424 0, /* tp_dict */
1425 0, /* tp_descr_get */
1426 0, /* tp_descr_set */
1427 0, /* tp_dictoffset */
1428 0, /* tp_init */
1429 PyType_GenericAlloc, /* tp_alloc */
1430 map_new, /* tp_new */
1431 PyObject_GC_Del, /* tp_free */
Dong-hee Na86883d42021-03-22 19:01:14 +09001432 .tp_vectorcall = (vectorcallfunc)map_vectorcall
Raymond Hettingera6c60372008-03-13 01:26:19 +00001433};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001434
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001435
1436/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001437static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001438builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001441
Serhiy Storchaka79342662019-01-12 08:25:41 +02001442 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001443 return NULL;
1444
Serhiy Storchaka79342662019-01-12 08:25:41 +02001445 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!PyIter_Check(it)) {
1447 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001448 "'%.200s' object is not an iterator",
Victor Stinnera102ed72020-02-07 02:24:48 +01001449 Py_TYPE(it)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 return NULL;
1451 }
1452
Victor Stinnera102ed72020-02-07 02:24:48 +01001453 res = (*Py_TYPE(it)->tp_iternext)(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 if (res != NULL) {
1455 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001456 } else if (nargs > 1) {
1457 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 if (PyErr_Occurred()) {
1459 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1460 return NULL;
1461 PyErr_Clear();
1462 }
1463 Py_INCREF(def);
1464 return def;
1465 } else if (PyErr_Occurred()) {
1466 return NULL;
1467 } else {
1468 PyErr_SetNone(PyExc_StopIteration);
1469 return NULL;
1470 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001471}
1472
1473PyDoc_STRVAR(next_doc,
1474"next(iterator[, default])\n\
1475\n\
1476Return the next item from the iterator. If default is given and the iterator\n\
1477is exhausted, it is returned instead of raising StopIteration.");
1478
1479
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001480/*[clinic input]
1481setattr as builtin_setattr
1482
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001483 obj: object
1484 name: object
1485 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001486 /
1487
1488Sets the named attribute on the given object to the specified value.
1489
1490setattr(x, 'y', v) is equivalent to ``x.y = v''
1491[clinic start generated code]*/
1492
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001493static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001494builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001495 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001496/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001497{
1498 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001500 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001501}
1502
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001503
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001504/*[clinic input]
1505delattr as builtin_delattr
1506
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001507 obj: object
1508 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001509 /
1510
1511Deletes the named attribute from the given object.
1512
1513delattr(x, 'y') is equivalent to ``del x.y''
1514[clinic start generated code]*/
1515
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001516static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001517builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1518/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001519{
1520 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001522 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001523}
1524
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001525
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001526/*[clinic input]
1527hash as builtin_hash
1528
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001529 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001530 /
1531
1532Return the hash value for the given object.
1533
1534Two objects that compare equal must also have the same hash value, but the
1535reverse is not necessarily true.
1536[clinic start generated code]*/
1537
Guido van Rossum79f25d91997-04-29 20:08:16 +00001538static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001539builtin_hash(PyObject *module, PyObject *obj)
1540/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001541{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001542 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001543
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001544 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (x == -1)
1546 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001547 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001548}
1549
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001550
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001551/*[clinic input]
1552hex as builtin_hex
1553
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001554 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001555 /
1556
1557Return the hexadecimal representation of an integer.
1558
1559 >>> hex(12648430)
1560 '0xc0ffee'
1561[clinic start generated code]*/
1562
Guido van Rossum79f25d91997-04-29 20:08:16 +00001563static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001564builtin_hex(PyObject *module, PyObject *number)
1565/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001566{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001567 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001568}
1569
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001570
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001571/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001572static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001573builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001574{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001575 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001576
Serhiy Storchaka79342662019-01-12 08:25:41 +02001577 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001579 v = args[0];
1580 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 return PyObject_GetIter(v);
1582 if (!PyCallable_Check(v)) {
1583 PyErr_SetString(PyExc_TypeError,
1584 "iter(v, w): v must be callable");
1585 return NULL;
1586 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001587 PyObject *sentinel = args[1];
1588 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001589}
1590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001591PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001592"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001593iter(callable, sentinel) -> iterator\n\
1594\n\
1595Get an iterator from an object. In the first form, the argument must\n\
1596supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001597In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001598
1599
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001600/*[clinic input]
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04001601aiter as builtin_aiter
1602
1603 async_iterable: object
1604 /
1605
1606Return an AsyncIterator for an AsyncIterable object.
1607[clinic start generated code]*/
1608
1609static PyObject *
1610builtin_aiter(PyObject *module, PyObject *async_iterable)
1611/*[clinic end generated code: output=1bae108d86f7960e input=473993d0cacc7d23]*/
1612{
Miss Islington (bot)53257cf2021-09-07 04:43:33 -07001613 return PyObject_GetAIter(async_iterable);
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04001614}
1615
1616PyObject *PyAnextAwaitable_New(PyObject *, PyObject *);
1617
1618/*[clinic input]
1619anext as builtin_anext
1620
1621 aiterator: object
1622 default: object = NULL
1623 /
1624
1625Return the next item from the async iterator.
1626[clinic start generated code]*/
1627
1628static PyObject *
1629builtin_anext_impl(PyObject *module, PyObject *aiterator,
1630 PyObject *default_value)
1631/*[clinic end generated code: output=f02c060c163a81fa input=699d11f4e38eca24]*/
1632{
1633 PyTypeObject *t;
1634 PyObject *awaitable;
1635
1636 t = Py_TYPE(aiterator);
1637 if (t->tp_as_async == NULL || t->tp_as_async->am_anext == NULL) {
1638 PyErr_Format(PyExc_TypeError,
1639 "'%.200s' object is not an async iterator",
1640 t->tp_name);
1641 return NULL;
1642 }
1643
1644 awaitable = (*t->tp_as_async->am_anext)(aiterator);
1645 if (default_value == NULL) {
1646 return awaitable;
1647 }
1648
Pablo Galindoa02683a2021-03-24 01:42:13 +00001649 PyObject* new_awaitable = PyAnextAwaitable_New(
1650 awaitable, default_value);
1651 Py_DECREF(awaitable);
1652 return new_awaitable;
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04001653}
1654
1655
1656/*[clinic input]
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001657len as builtin_len
1658
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001659 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001660 /
1661
1662Return the number of items in a container.
1663[clinic start generated code]*/
1664
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001665static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001666builtin_len(PyObject *module, PyObject *obj)
1667/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001670
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001671 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001672 if (res < 0) {
1673 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001677}
1678
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001679
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001680/*[clinic input]
1681locals as builtin_locals
1682
1683Return a dictionary containing the current scope's local variables.
1684
1685NOTE: Whether or not updates to this dictionary will affect name lookups in
1686the local scope and vice-versa is *implementation dependent* and not
1687covered by any backwards compatibility guarantees.
1688[clinic start generated code]*/
1689
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001690static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001691builtin_locals_impl(PyObject *module)
1692/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 d = PyEval_GetLocals();
1697 Py_XINCREF(d);
1698 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001699}
1700
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001701
Guido van Rossum79f25d91997-04-29 20:08:16 +00001702static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001703min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001706 PyObject *emptytuple, *defaultval = NULL;
1707 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001709 const int positional = PyTuple_Size(args) > 1;
1710 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001711
Dong-hee Naabdc6342020-01-11 01:31:43 +09001712 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001714 }
1715 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1716 if (PyExceptionClass_Check(PyExc_TypeError)) {
1717 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1718 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001720 }
Tim Peters67d687a2002-04-29 21:27:32 +00001721
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001722 emptytuple = PyTuple_New(0);
1723 if (emptytuple == NULL)
1724 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001725 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1726 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1727 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001728 Py_DECREF(emptytuple);
1729 if (!ret)
1730 return NULL;
1731
1732 if (positional && defaultval != NULL) {
1733 PyErr_Format(PyExc_TypeError,
1734 "Cannot specify a default for %s() with multiple "
1735 "positional arguments", name);
1736 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 it = PyObject_GetIter(v);
1740 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 return NULL;
1742 }
Tim Petersc3074532001-05-03 07:00:32 +00001743
Alexander Marshalove22072f2018-07-24 10:58:21 +07001744 if (keyfunc == Py_None) {
1745 keyfunc = NULL;
1746 }
1747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 maxitem = NULL; /* the result */
1749 maxval = NULL; /* the value associated with the result */
1750 while (( item = PyIter_Next(it) )) {
1751 /* get the value from the key function */
1752 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001753 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (val == NULL)
1755 goto Fail_it_item;
1756 }
1757 /* no key function; the value is the item */
1758 else {
1759 val = item;
1760 Py_INCREF(val);
1761 }
Tim Petersc3074532001-05-03 07:00:32 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 /* maximum value and item are unset; set them */
1764 if (maxval == NULL) {
1765 maxitem = item;
1766 maxval = val;
1767 }
1768 /* maximum value and item are set; update them as necessary */
1769 else {
1770 int cmp = PyObject_RichCompareBool(val, maxval, op);
1771 if (cmp < 0)
1772 goto Fail_it_item_and_val;
1773 else if (cmp > 0) {
1774 Py_DECREF(maxval);
1775 Py_DECREF(maxitem);
1776 maxval = val;
1777 maxitem = item;
1778 }
1779 else {
1780 Py_DECREF(item);
1781 Py_DECREF(val);
1782 }
1783 }
1784 }
1785 if (PyErr_Occurred())
1786 goto Fail_it;
1787 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001789 if (defaultval != NULL) {
1790 Py_INCREF(defaultval);
1791 maxitem = defaultval;
1792 } else {
1793 PyErr_Format(PyExc_ValueError,
1794 "%s() arg is an empty sequence", name);
1795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 }
1797 else
1798 Py_DECREF(maxval);
1799 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001801
1802Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001804Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001806Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 Py_XDECREF(maxval);
1808 Py_XDECREF(maxitem);
1809 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001811}
1812
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001813/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001814static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001815builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001818}
1819
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001820PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001821"min(iterable, *[, default=obj, key=func]) -> value\n\
1822min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001823\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001824With a single iterable argument, return its smallest item. The\n\
1825default keyword-only argument specifies an object to return if\n\
1826the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001827With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001828
1829
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001830/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001831static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001832builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001835}
1836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001837PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001838"max(iterable, *[, default=obj, key=func]) -> value\n\
1839max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001840\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001841With a single iterable argument, return its biggest item. The\n\
1842default keyword-only argument specifies an object to return if\n\
1843the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001844With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001845
1846
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001847/*[clinic input]
1848oct as builtin_oct
1849
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001850 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001851 /
1852
1853Return the octal representation of an integer.
1854
1855 >>> oct(342391)
1856 '0o1234567'
1857[clinic start generated code]*/
1858
Guido van Rossum79f25d91997-04-29 20:08:16 +00001859static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001860builtin_oct(PyObject *module, PyObject *number)
1861/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001862{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001863 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001864}
1865
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001866
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001867/*[clinic input]
1868ord as builtin_ord
1869
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001870 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001871 /
1872
1873Return the Unicode code point for a one-character string.
1874[clinic start generated code]*/
1875
Guido van Rossum79f25d91997-04-29 20:08:16 +00001876static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001877builtin_ord(PyObject *module, PyObject *c)
1878/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 long ord;
1881 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001882
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001883 if (PyBytes_Check(c)) {
1884 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001886 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 return PyLong_FromLong(ord);
1888 }
1889 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001890 else if (PyUnicode_Check(c)) {
1891 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001892 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001893 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001895 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 return PyLong_FromLong(ord);
1897 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001899 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001901 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001903 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 return PyLong_FromLong(ord);
1905 }
1906 }
1907 else {
1908 PyErr_Format(PyExc_TypeError,
1909 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001910 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 return NULL;
1912 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 PyErr_Format(PyExc_TypeError,
1915 "ord() expected a character, "
1916 "but string of length %zd found",
1917 size);
1918 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001919}
1920
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001921
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001922/*[clinic input]
1923pow as builtin_pow
1924
Ammar Askar87d6cd32019-09-21 00:28:49 -04001925 base: object
1926 exp: object
1927 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001928
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001929Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001930
1931Some types, such as ints, are able to use a more efficient algorithm when
1932invoked using the three argument form.
1933[clinic start generated code]*/
1934
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001935static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001936builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1937 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001938/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001939{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001940 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001941}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001942
1943
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001944/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001945static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001946builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001947{
INADA Naokibd584f12017-01-19 12:50:34 +01001948 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001949 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1950 PyObject *sep = NULL, *end = NULL, *file = NULL;
1951 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001953
INADA Naokibd584f12017-01-19 12:50:34 +01001954 if (kwnames != NULL &&
1955 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1956 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001957 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001958 }
1959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001961 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001962 if (file == NULL) {
1963 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1964 return NULL;
1965 }
1966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 /* sys.stdout may be None when FILE* stdout isn't connected */
1968 if (file == Py_None)
1969 Py_RETURN_NONE;
1970 }
Guido van Rossum34343512006-11-30 22:13:52 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 if (sep == Py_None) {
1973 sep = NULL;
1974 }
1975 else if (sep && !PyUnicode_Check(sep)) {
1976 PyErr_Format(PyExc_TypeError,
1977 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001978 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 return NULL;
1980 }
1981 if (end == Py_None) {
1982 end = NULL;
1983 }
1984 else if (end && !PyUnicode_Check(end)) {
1985 PyErr_Format(PyExc_TypeError,
1986 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001987 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 return NULL;
1989 }
Guido van Rossum34343512006-11-30 22:13:52 +00001990
INADA Naokibd584f12017-01-19 12:50:34 +01001991 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 if (i > 0) {
1993 if (sep == NULL)
1994 err = PyFile_WriteString(" ", file);
1995 else
1996 err = PyFile_WriteObject(sep, file,
1997 Py_PRINT_RAW);
1998 if (err)
1999 return NULL;
2000 }
INADA Naokibd584f12017-01-19 12:50:34 +01002001 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 if (err)
2003 return NULL;
2004 }
Guido van Rossum34343512006-11-30 22:13:52 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (end == NULL)
2007 err = PyFile_WriteString("\n", file);
2008 else
2009 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
2010 if (err)
2011 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00002012
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002013 if (flush) {
2014 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
2015 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01002016 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002017 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01002018 }
2019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00002021}
2022
2023PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002024"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00002025\n\
2026Prints the values to a stream, or to sys.stdout by default.\n\
2027Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002028file: a file-like object (stream); defaults to the current sys.stdout.\n\
2029sep: string inserted between values, default a space.\n\
2030end: string appended after the last value, default a newline.\n\
2031flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00002032
2033
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002034/*[clinic input]
2035input as builtin_input
2036
2037 prompt: object(c_default="NULL") = None
2038 /
2039
2040Read a string from standard input. The trailing newline is stripped.
2041
2042The prompt string, if given, is printed to standard output without a
2043trailing newline before reading input.
2044
2045If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
2046On *nix systems, readline is used if available.
2047[clinic start generated code]*/
2048
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002049static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002050builtin_input_impl(PyObject *module, PyObject *prompt)
2051/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002052{
Victor Stinnerbd303c12013-11-07 23:07:29 +01002053 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
2054 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
2055 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 PyObject *tmp;
2057 long fd;
2058 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 /* Check that stdin/out/err are intact */
2061 if (fin == NULL || fin == Py_None) {
2062 PyErr_SetString(PyExc_RuntimeError,
2063 "input(): lost sys.stdin");
2064 return NULL;
2065 }
2066 if (fout == NULL || fout == Py_None) {
2067 PyErr_SetString(PyExc_RuntimeError,
2068 "input(): lost sys.stdout");
2069 return NULL;
2070 }
2071 if (ferr == NULL || ferr == Py_None) {
2072 PyErr_SetString(PyExc_RuntimeError,
2073 "input(): lost sys.stderr");
2074 return NULL;
2075 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002076
Steve Dowerb82e17e2019-05-23 08:45:22 -07002077 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
2078 return NULL;
2079 }
2080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002082 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 if (tmp == NULL)
2084 PyErr_Clear();
2085 else
2086 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 /* We should only use (GNU) readline if Python's sys.stdin and
2089 sys.stdout are the same as C's stdin and stdout, because we
2090 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002091 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (tmp == NULL) {
2093 PyErr_Clear();
2094 tty = 0;
2095 }
2096 else {
2097 fd = PyLong_AsLong(tmp);
2098 Py_DECREF(tmp);
2099 if (fd < 0 && PyErr_Occurred())
2100 return NULL;
2101 tty = fd == fileno(stdin) && isatty(fd);
2102 }
2103 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002104 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002105 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002107 tty = 0;
2108 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 else {
2110 fd = PyLong_AsLong(tmp);
2111 Py_DECREF(tmp);
2112 if (fd < 0 && PyErr_Occurred())
2113 return NULL;
2114 tty = fd == fileno(stdout) && isatty(fd);
2115 }
2116 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 /* If we're interactive, use (GNU) readline */
2119 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002120 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002121 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002122 char *s = NULL;
2123 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2124 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002125 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002127 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002128
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002129 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002130 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002131 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002132 if (!stdin_encoding || !stdin_errors ||
2133 !PyUnicode_Check(stdin_encoding) ||
2134 !PyUnicode_Check(stdin_errors)) {
2135 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002136 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002137 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002138 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2139 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002140 if (!stdin_encoding_str || !stdin_errors_str)
2141 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002142 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 if (tmp == NULL)
2144 PyErr_Clear();
2145 else
2146 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002147 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002148 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002149 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002151 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002152 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002153 if (!stdout_encoding || !stdout_errors ||
2154 !PyUnicode_Check(stdout_encoding) ||
2155 !PyUnicode_Check(stdout_errors)) {
2156 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002157 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002158 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002159 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2160 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002161 if (!stdout_encoding_str || !stdout_errors_str)
2162 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002163 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002164 if (stringpo == NULL)
2165 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002167 stdout_encoding_str, stdout_errors_str);
2168 Py_CLEAR(stdout_encoding);
2169 Py_CLEAR(stdout_errors);
2170 Py_CLEAR(stringpo);
2171 if (po == NULL)
2172 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002173 assert(PyBytes_Check(po));
2174 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 }
2176 else {
2177 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002178 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002180 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002182 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 if (!PyErr_Occurred())
2184 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002185 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002187
2188 len = strlen(s);
2189 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 PyErr_SetNone(PyExc_EOFError);
2191 result = NULL;
2192 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002193 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 if (len > PY_SSIZE_T_MAX) {
2195 PyErr_SetString(PyExc_OverflowError,
2196 "input: input too long");
2197 result = NULL;
2198 }
2199 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002200 len--; /* strip trailing '\n' */
2201 if (len != 0 && s[len-1] == '\r')
2202 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002203 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2204 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 }
2206 }
2207 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002208 Py_DECREF(stdin_errors);
2209 Py_XDECREF(po);
Victor Stinner00d7abd2020-12-01 09:56:42 +01002210 PyMem_Free(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002211
2212 if (result != NULL) {
2213 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2214 return NULL;
2215 }
2216 }
2217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002219
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002220 _readline_errors:
2221 Py_XDECREF(stdin_encoding);
2222 Py_XDECREF(stdout_encoding);
2223 Py_XDECREF(stdin_errors);
2224 Py_XDECREF(stdout_errors);
2225 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002226 if (tty)
2227 return NULL;
2228
2229 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002233 if (prompt != NULL) {
2234 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 return NULL;
2236 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002237 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (tmp == NULL)
2239 PyErr_Clear();
2240 else
2241 Py_DECREF(tmp);
2242 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002243}
2244
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002245
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002246/*[clinic input]
2247repr as builtin_repr
2248
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002249 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002250 /
2251
2252Return the canonical string representation of the object.
2253
2254For many object types, including most builtins, eval(repr(obj)) == obj.
2255[clinic start generated code]*/
2256
Guido van Rossum79f25d91997-04-29 20:08:16 +00002257static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002258builtin_repr(PyObject *module, PyObject *obj)
2259/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002260{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002261 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002262}
2263
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002264
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002265/*[clinic input]
2266round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002267
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002268 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002269 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002270
2271Round a number to a given precision in decimal digits.
2272
2273The return value is an integer if ndigits is omitted or None. Otherwise
2274the return value has the same type as the number. ndigits may be negative.
2275[clinic start generated code]*/
2276
2277static PyObject *
2278builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002279/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002280{
2281 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 if (Py_TYPE(number)->tp_dict == NULL) {
2284 if (PyType_Ready(Py_TYPE(number)) < 0)
2285 return NULL;
2286 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002287
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002288 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002290 if (!PyErr_Occurred())
2291 PyErr_Format(PyExc_TypeError,
2292 "type %.100s doesn't define __round__ method",
2293 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 return NULL;
2295 }
Alex Martelliae211f92007-08-22 23:21:33 +00002296
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002297 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002298 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002300 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002301 Py_DECREF(round);
2302 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002303}
2304
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002305
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002306/*AC: we need to keep the kwds dict intact to easily call into the
2307 * list.sort method, which isn't currently supported in AC. So we just use
2308 * the initially generated signature with a custom implementation.
2309 */
2310/* [disabled clinic input]
2311sorted as builtin_sorted
2312
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002313 iterable as seq: object
2314 key as keyfunc: object = None
2315 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002316
2317Return a new list containing all items from the iterable in ascending order.
2318
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002319A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002320reverse flag can be set to request the result in descending order.
2321[end disabled clinic input]*/
2322
2323PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002324"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002325"--\n"
2326"\n"
2327"Return a new list containing all items from the iterable in ascending order.\n"
2328"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002329"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002330"reverse flag can be set to request the result in descending order.");
2331
2332#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002333 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002334
Raymond Hettinger64958a12003-12-17 20:43:33 +00002335static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002336builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002337{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002338 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002339
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002340 /* Keyword arguments are passed through list.sort() which will check
2341 them. */
2342 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 newlist = PySequence_List(seq);
2346 if (newlist == NULL)
2347 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002348
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002349 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 if (callable == NULL) {
2351 Py_DECREF(newlist);
2352 return NULL;
2353 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002354
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002355 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002356 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 Py_DECREF(callable);
2358 if (v == NULL) {
2359 Py_DECREF(newlist);
2360 return NULL;
2361 }
2362 Py_DECREF(v);
2363 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002364}
2365
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002366
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002367/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002368static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002369builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 PyObject *v = NULL;
2372 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2375 return NULL;
2376 if (v == NULL) {
2377 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002378 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 }
2380 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002381 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 PyErr_SetString(PyExc_TypeError,
2383 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 }
2385 }
2386 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002387}
2388
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002389PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002390"vars([object]) -> dictionary\n\
2391\n\
2392Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002393With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002394
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002395
2396/*[clinic input]
2397sum as builtin_sum
2398
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002399 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002400 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002401 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002402
2403Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2404
2405When the iterable is empty, return the start value.
2406This function is intended specifically for use with numeric values and may
2407reject non-numeric types.
2408[clinic start generated code]*/
2409
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002410static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002411builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002412/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002413{
2414 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002416
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002417 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (iter == NULL)
2419 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 if (result == NULL) {
2422 result = PyLong_FromLong(0);
2423 if (result == NULL) {
2424 Py_DECREF(iter);
2425 return NULL;
2426 }
2427 } else {
2428 /* reject string values for 'start' parameter */
2429 if (PyUnicode_Check(result)) {
2430 PyErr_SetString(PyExc_TypeError,
2431 "sum() can't sum strings [use ''.join(seq) instead]");
2432 Py_DECREF(iter);
2433 return NULL;
2434 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002435 if (PyBytes_Check(result)) {
2436 PyErr_SetString(PyExc_TypeError,
2437 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002438 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002439 return NULL;
2440 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 if (PyByteArray_Check(result)) {
2442 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002443 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 Py_DECREF(iter);
2445 return NULL;
2446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 Py_INCREF(result);
2448 }
Alex Martellia70b1912003-04-22 08:12:33 +00002449
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002450#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2452 Assumes all inputs are the same type. If the assumption fails, default
2453 to the more general routine.
2454 */
2455 if (PyLong_CheckExact(result)) {
2456 int overflow;
2457 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2458 /* If this already overflowed, don't even enter the loop. */
2459 if (overflow == 0) {
2460 Py_DECREF(result);
2461 result = NULL;
2462 }
2463 while(result == NULL) {
2464 item = PyIter_Next(iter);
2465 if (item == NULL) {
2466 Py_DECREF(iter);
2467 if (PyErr_Occurred())
2468 return NULL;
2469 return PyLong_FromLong(i_result);
2470 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002471 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002473 if (overflow == 0 &&
2474 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2475 : (b >= LONG_MIN - i_result)))
2476 {
2477 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 Py_DECREF(item);
2479 continue;
2480 }
2481 }
2482 /* Either overflowed or is not an int. Restore real objects and process normally */
2483 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002484 if (result == NULL) {
2485 Py_DECREF(item);
2486 Py_DECREF(iter);
2487 return NULL;
2488 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 temp = PyNumber_Add(result, item);
2490 Py_DECREF(result);
2491 Py_DECREF(item);
2492 result = temp;
2493 if (result == NULL) {
2494 Py_DECREF(iter);
2495 return NULL;
2496 }
2497 }
2498 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 if (PyFloat_CheckExact(result)) {
2501 double f_result = PyFloat_AS_DOUBLE(result);
2502 Py_DECREF(result);
2503 result = NULL;
2504 while(result == NULL) {
2505 item = PyIter_Next(iter);
2506 if (item == NULL) {
2507 Py_DECREF(iter);
2508 if (PyErr_Occurred())
2509 return NULL;
2510 return PyFloat_FromDouble(f_result);
2511 }
2512 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 Py_DECREF(item);
2515 continue;
2516 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002517 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 long value;
2519 int overflow;
2520 value = PyLong_AsLongAndOverflow(item, &overflow);
2521 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 Py_DECREF(item);
2524 continue;
2525 }
2526 }
2527 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002528 if (result == NULL) {
2529 Py_DECREF(item);
2530 Py_DECREF(iter);
2531 return NULL;
2532 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 temp = PyNumber_Add(result, item);
2534 Py_DECREF(result);
2535 Py_DECREF(item);
2536 result = temp;
2537 if (result == NULL) {
2538 Py_DECREF(iter);
2539 return NULL;
2540 }
2541 }
2542 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002543#endif
2544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 for(;;) {
2546 item = PyIter_Next(iter);
2547 if (item == NULL) {
2548 /* error, or end-of-sequence */
2549 if (PyErr_Occurred()) {
2550 Py_DECREF(result);
2551 result = NULL;
2552 }
2553 break;
2554 }
2555 /* It's tempting to use PyNumber_InPlaceAdd instead of
2556 PyNumber_Add here, to avoid quadratic running time
2557 when doing 'sum(list_of_lists, [])'. However, this
2558 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 empty = []
2561 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002562
Brandt Bucherabb9a442020-02-01 03:08:34 -08002563 would change the value of empty. In fact, using
2564 in-place addition rather that binary addition for
2565 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002566
Brandt Bucherabb9a442020-02-01 03:08:34 -08002567 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 temp = PyNumber_Add(result, item);
2569 Py_DECREF(result);
2570 Py_DECREF(item);
2571 result = temp;
2572 if (result == NULL)
2573 break;
2574 }
2575 Py_DECREF(iter);
2576 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002577}
2578
Alex Martellia70b1912003-04-22 08:12:33 +00002579
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002580/*[clinic input]
2581isinstance as builtin_isinstance
2582
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002583 obj: object
2584 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002585 /
2586
2587Return whether an object is an instance of a class or of a subclass thereof.
2588
2589A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2590check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2591or ...`` etc.
2592[clinic start generated code]*/
2593
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002594static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002595builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002596 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002597/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002600
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002601 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 if (retval < 0)
2603 return NULL;
2604 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002605}
2606
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002607
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002608/*[clinic input]
2609issubclass as builtin_issubclass
2610
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002611 cls: object
2612 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002613 /
2614
Alex Poveldf773f82020-06-03 15:19:45 +02002615Return whether 'cls' is derived from another class or is the same class.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002616
2617A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2618check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
Alex Poveldf773f82020-06-03 15:19:45 +02002619or ...``.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002620[clinic start generated code]*/
2621
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002622static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002623builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002624 PyObject *class_or_tuple)
Alex Poveldf773f82020-06-03 15:19:45 +02002625/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002628
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002629 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 if (retval < 0)
2631 return NULL;
2632 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002633}
2634
2635
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002636typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 PyObject_HEAD
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002638 Py_ssize_t tuplesize;
2639 PyObject *ittuple; /* tuple of iterators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 PyObject *result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002641 int strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002642} zipobject;
2643
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002644static PyObject *
2645zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 zipobject *lz;
2648 Py_ssize_t i;
2649 PyObject *ittuple; /* tuple of iterators */
2650 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002651 Py_ssize_t tuplesize;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002652 int strict = 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002653
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002654 if (kwds) {
2655 PyObject *empty = PyTuple_New(0);
2656 if (empty == NULL) {
2657 return NULL;
2658 }
2659 static char *kwlist[] = {"strict", NULL};
2660 int parsed = PyArg_ParseTupleAndKeywords(
2661 empty, kwds, "|$p:zip", kwlist, &strict);
2662 Py_DECREF(empty);
2663 if (!parsed) {
2664 return NULL;
2665 }
2666 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 /* args must be a tuple */
2669 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002670 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 /* obtain iterators */
2673 ittuple = PyTuple_New(tuplesize);
2674 if (ittuple == NULL)
2675 return NULL;
2676 for (i=0; i < tuplesize; ++i) {
2677 PyObject *item = PyTuple_GET_ITEM(args, i);
2678 PyObject *it = PyObject_GetIter(item);
2679 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 Py_DECREF(ittuple);
2681 return NULL;
2682 }
2683 PyTuple_SET_ITEM(ittuple, i, it);
2684 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 /* create a result holder */
2687 result = PyTuple_New(tuplesize);
2688 if (result == NULL) {
2689 Py_DECREF(ittuple);
2690 return NULL;
2691 }
2692 for (i=0 ; i < tuplesize ; i++) {
2693 Py_INCREF(Py_None);
2694 PyTuple_SET_ITEM(result, i, Py_None);
2695 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 /* create zipobject structure */
2698 lz = (zipobject *)type->tp_alloc(type, 0);
2699 if (lz == NULL) {
2700 Py_DECREF(ittuple);
2701 Py_DECREF(result);
2702 return NULL;
2703 }
2704 lz->ittuple = ittuple;
2705 lz->tuplesize = tuplesize;
2706 lz->result = result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002707 lz->strict = strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002710}
2711
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002712static void
2713zip_dealloc(zipobject *lz)
2714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 PyObject_GC_UnTrack(lz);
2716 Py_XDECREF(lz->ittuple);
2717 Py_XDECREF(lz->result);
2718 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002719}
2720
2721static int
2722zip_traverse(zipobject *lz, visitproc visit, void *arg)
2723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 Py_VISIT(lz->ittuple);
2725 Py_VISIT(lz->result);
2726 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002727}
2728
2729static PyObject *
2730zip_next(zipobject *lz)
2731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 Py_ssize_t i;
2733 Py_ssize_t tuplesize = lz->tuplesize;
2734 PyObject *result = lz->result;
2735 PyObject *it;
2736 PyObject *item;
2737 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 if (tuplesize == 0)
2740 return NULL;
2741 if (Py_REFCNT(result) == 1) {
2742 Py_INCREF(result);
2743 for (i=0 ; i < tuplesize ; i++) {
2744 it = PyTuple_GET_ITEM(lz->ittuple, i);
2745 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002746 if (item == NULL) {
2747 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002748 if (lz->strict) {
2749 goto check;
2750 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002751 return NULL;
2752 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 olditem = PyTuple_GET_ITEM(result, i);
2754 PyTuple_SET_ITEM(result, i, item);
2755 Py_DECREF(olditem);
2756 }
Brandt Bucher226a0122020-12-04 19:45:57 -08002757 // bpo-42536: The GC may have untracked this result tuple. Since we're
2758 // recycling it, make sure it's tracked again:
2759 if (!_PyObject_GC_IS_TRACKED(result)) {
2760 _PyObject_GC_TRACK(result);
2761 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 } else {
2763 result = PyTuple_New(tuplesize);
2764 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002765 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 for (i=0 ; i < tuplesize ; i++) {
2767 it = PyTuple_GET_ITEM(lz->ittuple, i);
2768 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002769 if (item == NULL) {
2770 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002771 if (lz->strict) {
2772 goto check;
2773 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002774 return NULL;
2775 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 PyTuple_SET_ITEM(result, i, item);
2777 }
2778 }
2779 return result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002780check:
2781 if (PyErr_Occurred()) {
2782 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2783 // next() on argument i raised an exception (not StopIteration)
2784 return NULL;
2785 }
2786 PyErr_Clear();
2787 }
2788 if (i) {
2789 // ValueError: zip() argument 2 is shorter than argument 1
2790 // ValueError: zip() argument 3 is shorter than arguments 1-2
2791 const char* plural = i == 1 ? " " : "s 1-";
2792 return PyErr_Format(PyExc_ValueError,
2793 "zip() argument %d is shorter than argument%s%d",
2794 i + 1, plural, i);
2795 }
2796 for (i = 1; i < tuplesize; i++) {
2797 it = PyTuple_GET_ITEM(lz->ittuple, i);
2798 item = (*Py_TYPE(it)->tp_iternext)(it);
2799 if (item) {
2800 Py_DECREF(item);
2801 const char* plural = i == 1 ? " " : "s 1-";
2802 return PyErr_Format(PyExc_ValueError,
2803 "zip() argument %d is longer than argument%s%d",
2804 i + 1, plural, i);
2805 }
2806 if (PyErr_Occurred()) {
2807 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2808 // next() on argument i raised an exception (not StopIteration)
2809 return NULL;
2810 }
2811 PyErr_Clear();
2812 }
2813 // Argument i is exhausted. So far so good...
2814 }
2815 // All arguments are exhausted. Success!
2816 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002817}
Barry Warsawbd599b52000-08-03 15:45:29 +00002818
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002819static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302820zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002821{
2822 /* Just recreate the zip with the internal iterator tuple */
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002823 if (lz->strict) {
2824 return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
2825 }
2826 return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
2827}
2828
2829PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2830
2831static PyObject *
2832zip_setstate(zipobject *lz, PyObject *state)
2833{
2834 int strict = PyObject_IsTrue(state);
2835 if (strict < 0) {
2836 return NULL;
2837 }
2838 lz->strict = strict;
2839 Py_RETURN_NONE;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002840}
2841
2842static PyMethodDef zip_methods[] = {
2843 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002844 {"__setstate__", (PyCFunction)zip_setstate, METH_O, setstate_doc},
2845 {NULL} /* sentinel */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002846};
2847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002848PyDoc_STRVAR(zip_doc,
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002849"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002850\n\
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -07002851 >>> list(zip('abcdefg', range(3), range(4)))\n\
2852 [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
2853\n\
2854The zip object yields n-length tuples, where n is the number of iterables\n\
2855passed as positional arguments to zip(). The i-th element in every tuple\n\
2856comes from the i-th iterable argument to zip(). This continues until the\n\
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002857shortest argument is exhausted.\n\
2858\n\
2859If strict is true and one of the arguments is exhausted before the others,\n\
2860raise a ValueError.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002861
2862PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2864 "zip", /* tp_name */
2865 sizeof(zipobject), /* tp_basicsize */
2866 0, /* tp_itemsize */
2867 /* methods */
2868 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002869 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 0, /* tp_getattr */
2871 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002872 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 0, /* tp_repr */
2874 0, /* tp_as_number */
2875 0, /* tp_as_sequence */
2876 0, /* tp_as_mapping */
2877 0, /* tp_hash */
2878 0, /* tp_call */
2879 0, /* tp_str */
2880 PyObject_GenericGetAttr, /* tp_getattro */
2881 0, /* tp_setattro */
2882 0, /* tp_as_buffer */
2883 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2884 Py_TPFLAGS_BASETYPE, /* tp_flags */
2885 zip_doc, /* tp_doc */
2886 (traverseproc)zip_traverse, /* tp_traverse */
2887 0, /* tp_clear */
2888 0, /* tp_richcompare */
2889 0, /* tp_weaklistoffset */
2890 PyObject_SelfIter, /* tp_iter */
2891 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002892 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 0, /* tp_members */
2894 0, /* tp_getset */
2895 0, /* tp_base */
2896 0, /* tp_dict */
2897 0, /* tp_descr_get */
2898 0, /* tp_descr_set */
2899 0, /* tp_dictoffset */
2900 0, /* tp_init */
2901 PyType_GenericAlloc, /* tp_alloc */
2902 zip_new, /* tp_new */
2903 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002904};
Barry Warsawbd599b52000-08-03 15:45:29 +00002905
2906
Guido van Rossum79f25d91997-04-29 20:08:16 +00002907static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002908 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002909 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002910 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002911 BUILTIN_ABS_METHODDEF
2912 BUILTIN_ALL_METHODDEF
2913 BUILTIN_ANY_METHODDEF
2914 BUILTIN_ASCII_METHODDEF
2915 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002916 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002917 BUILTIN_CALLABLE_METHODDEF
2918 BUILTIN_CHR_METHODDEF
2919 BUILTIN_COMPILE_METHODDEF
2920 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002922 BUILTIN_DIVMOD_METHODDEF
2923 BUILTIN_EVAL_METHODDEF
2924 BUILTIN_EXEC_METHODDEF
2925 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002926 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002927 BUILTIN_GLOBALS_METHODDEF
2928 BUILTIN_HASATTR_METHODDEF
2929 BUILTIN_HASH_METHODDEF
2930 BUILTIN_HEX_METHODDEF
2931 BUILTIN_ID_METHODDEF
2932 BUILTIN_INPUT_METHODDEF
2933 BUILTIN_ISINSTANCE_METHODDEF
2934 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002935 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04002936 BUILTIN_AITER_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002937 BUILTIN_LEN_METHODDEF
2938 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002939 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2940 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2941 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04002942 BUILTIN_ANEXT_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002943 BUILTIN_OCT_METHODDEF
2944 BUILTIN_ORD_METHODDEF
2945 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002946 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002947 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002948 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002949 BUILTIN_SETATTR_METHODDEF
2950 BUILTIN_SORTED_METHODDEF
2951 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2953 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002954};
2955
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002956PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002957"Built-in functions, exceptions, and other objects.\n\
2958\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002959Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002960
Martin v. Löwis1a214512008-06-11 05:26:20 +00002961static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 PyModuleDef_HEAD_INIT,
2963 "builtins",
2964 builtin_doc,
2965 -1, /* multiple "initialization" just copies the module dict. */
2966 builtin_methods,
2967 NULL,
2968 NULL,
2969 NULL,
2970 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002971};
2972
2973
Guido van Rossum25ce5661997-08-02 03:10:38 +00002974PyObject *
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002975_PyBuiltin_Init(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002978
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002979 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002980
Benjamin Peterson42124a72012-10-30 23:41:54 -04002981 if (PyType_Ready(&PyFilter_Type) < 0 ||
2982 PyType_Ready(&PyMap_Type) < 0 ||
2983 PyType_Ready(&PyZip_Type) < 0)
2984 return NULL;
2985
Eric Snowd393c1b2017-09-14 12:18:12 -06002986 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 if (mod == NULL)
2988 return NULL;
2989 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002990
Tim Peters7571a0f2003-03-23 17:52:28 +00002991#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 /* "builtins" exposes a number of statically allocated objects
2993 * that, before this code was added in 2.3, never showed up in
2994 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2995 * result, programs leaking references to None and False (etc)
2996 * couldn't be diagnosed by examining sys.getobjects(0).
2997 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002998#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2999#else
3000#define ADD_TO_ALL(OBJECT) (void)0
3001#endif
3002
Tim Peters4b7625e2001-09-13 21:37:17 +00003003#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
3005 return NULL; \
3006 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00003007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 SETBUILTIN("None", Py_None);
3009 SETBUILTIN("Ellipsis", Py_Ellipsis);
3010 SETBUILTIN("NotImplemented", Py_NotImplemented);
3011 SETBUILTIN("False", Py_False);
3012 SETBUILTIN("True", Py_True);
3013 SETBUILTIN("bool", &PyBool_Type);
3014 SETBUILTIN("memoryview", &PyMemoryView_Type);
3015 SETBUILTIN("bytearray", &PyByteArray_Type);
3016 SETBUILTIN("bytes", &PyBytes_Type);
3017 SETBUILTIN("classmethod", &PyClassMethod_Type);
3018 SETBUILTIN("complex", &PyComplex_Type);
3019 SETBUILTIN("dict", &PyDict_Type);
3020 SETBUILTIN("enumerate", &PyEnum_Type);
3021 SETBUILTIN("filter", &PyFilter_Type);
3022 SETBUILTIN("float", &PyFloat_Type);
3023 SETBUILTIN("frozenset", &PyFrozenSet_Type);
3024 SETBUILTIN("property", &PyProperty_Type);
3025 SETBUILTIN("int", &PyLong_Type);
3026 SETBUILTIN("list", &PyList_Type);
3027 SETBUILTIN("map", &PyMap_Type);
3028 SETBUILTIN("object", &PyBaseObject_Type);
3029 SETBUILTIN("range", &PyRange_Type);
3030 SETBUILTIN("reversed", &PyReversed_Type);
3031 SETBUILTIN("set", &PySet_Type);
3032 SETBUILTIN("slice", &PySlice_Type);
3033 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
3034 SETBUILTIN("str", &PyUnicode_Type);
3035 SETBUILTIN("super", &PySuper_Type);
3036 SETBUILTIN("tuple", &PyTuple_Type);
3037 SETBUILTIN("type", &PyType_Type);
3038 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02003039 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03003041 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 return NULL;
3043 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03003044 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00003045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00003047#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00003048#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00003049}