blob: 121cbb7f3d525e0dea2f0c2af00977f099e37b82 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Victor Stinnerbd303c12013-11-07 23:07:29 +010035_Py_IDENTIFIER(__builtins__);
36_Py_IDENTIFIER(__dict__);
37_Py_IDENTIFIER(__prepare__);
38_Py_IDENTIFIER(__round__);
39_Py_IDENTIFIER(encoding);
40_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020041_Py_IDENTIFIER(fileno);
42_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010043_Py_IDENTIFIER(metaclass);
44_Py_IDENTIFIER(sort);
45_Py_IDENTIFIER(stdin);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020048
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030049#include "clinic/bltinmodule.c.h"
50
Nick Coghlanf9e227e2014-08-17 14:01:19 +100051/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000052static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000053builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
54{
Nick Coghlande31b192011-10-23 22:04:16 +100055 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020057 Py_ssize_t nargs;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010058 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 assert(args != NULL);
61 if (!PyTuple_Check(args)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: args is not a tuple");
64 return NULL;
65 }
66 nargs = PyTuple_GET_SIZE(args);
67 if (nargs < 2) {
68 PyErr_SetString(PyExc_TypeError,
69 "__build_class__: not enough arguments");
70 return NULL;
71 }
72 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050073 if (!PyFunction_Check(func)) {
74 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050075 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050076 return NULL;
77 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 name = PyTuple_GET_ITEM(args, 1);
79 if (!PyUnicode_Check(name)) {
80 PyErr_SetString(PyExc_TypeError,
81 "__build_class__: name is not a string");
82 return NULL;
83 }
84 bases = PyTuple_GetSlice(args, 2, nargs);
85 if (bases == NULL)
86 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 if (kwds == NULL) {
89 meta = NULL;
90 mkw = NULL;
91 }
92 else {
93 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
94 if (mkw == NULL) {
95 Py_DECREF(bases);
96 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000097 }
Victor Stinnerae9f1612013-11-06 22:46:51 +010098 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 if (meta != NULL) {
100 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100101 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 Py_DECREF(meta);
103 Py_DECREF(mkw);
104 Py_DECREF(bases);
105 return NULL;
106 }
Nick Coghlande31b192011-10-23 22:04:16 +1000107 /* metaclass is explicitly given, check if it's indeed a class */
108 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 }
110 }
111 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000112 /* if there are no bases, use type: */
113 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000115 }
116 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 else {
118 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
119 meta = (PyObject *) (base0->ob_type);
120 }
121 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000122 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000124
Nick Coghlande31b192011-10-23 22:04:16 +1000125 if (isclass) {
126 /* meta is really a class, so check for a more derived
127 metaclass, or possible metaclass conflicts: */
128 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
129 bases);
130 if (winner == NULL) {
131 Py_DECREF(meta);
132 Py_XDECREF(mkw);
133 Py_DECREF(bases);
134 return NULL;
135 }
136 if (winner != meta) {
137 Py_DECREF(meta);
138 meta = winner;
139 Py_INCREF(meta);
140 }
141 }
142 /* else: meta is not a class, so we cannot do the metaclass
143 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200144 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 if (prep == NULL) {
146 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
147 PyErr_Clear();
148 ns = PyDict_New();
149 }
150 else {
151 Py_DECREF(meta);
152 Py_XDECREF(mkw);
153 Py_DECREF(bases);
154 return NULL;
155 }
156 }
157 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200158 PyObject *pargs[2] = {name, bases};
159 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 Py_DECREF(prep);
161 }
162 if (ns == NULL) {
163 Py_DECREF(meta);
164 Py_XDECREF(mkw);
165 Py_DECREF(bases);
166 return NULL;
167 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500168 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
169 NULL, 0, NULL, 0, NULL, 0, NULL,
170 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 if (cell != NULL) {
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200172 PyObject *margs[3] = {name, bases, ns};
173 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700174 if (cls != NULL && PyCell_Check(cell))
175 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 Py_DECREF(cell);
177 }
178 Py_DECREF(ns);
179 Py_DECREF(meta);
180 Py_XDECREF(mkw);
181 Py_DECREF(bases);
182 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000183}
184
185PyDoc_STRVAR(build_class_doc,
186"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
187\n\
188Internal helper function used by the class statement.");
189
190static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
194 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400195 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400196 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000197
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400198 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 kwlist, &name, &globals, &locals, &fromlist, &level))
200 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400201 return PyImport_ImportModuleLevelObject(name, globals, locals,
202 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000203}
204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000205PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400206"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000207\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000208Import a module. Because this function is meant for use by the Python\n\
209interpreter and not for general use it is better to use\n\
210importlib.import_module() to programmatically import a module.\n\
211\n\
212The globals argument is only used to determine the context;\n\
213they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000214should be a list of names to emulate ``from name import ...'', or an\n\
215empty list to emulate ``import name''.\n\
216When importing a module from a package, note that __import__('A.B', ...)\n\
217returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400219absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000221
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000222
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000223/*[clinic input]
224abs as builtin_abs
225
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300226 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000227 /
228
229Return the absolute value of the argument.
230[clinic start generated code]*/
231
Guido van Rossum79f25d91997-04-29 20:08:16 +0000232static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300233builtin_abs(PyObject *module, PyObject *x)
234/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000235{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000236 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000237}
238
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000239/*[clinic input]
240all as builtin_all
241
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300242 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000243 /
244
245Return True if bool(x) is True for all values x in the iterable.
246
247If the iterable is empty, return True.
248[clinic start generated code]*/
249
Raymond Hettinger96229b12005-03-11 06:49:40 +0000250static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300251builtin_all(PyObject *module, PyObject *iterable)
252/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 PyObject *it, *item;
255 PyObject *(*iternext)(PyObject *);
256 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000257
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000258 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 if (it == NULL)
260 return NULL;
261 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 for (;;) {
264 item = iternext(it);
265 if (item == NULL)
266 break;
267 cmp = PyObject_IsTrue(item);
268 Py_DECREF(item);
269 if (cmp < 0) {
270 Py_DECREF(it);
271 return NULL;
272 }
273 if (cmp == 0) {
274 Py_DECREF(it);
275 Py_RETURN_FALSE;
276 }
277 }
278 Py_DECREF(it);
279 if (PyErr_Occurred()) {
280 if (PyErr_ExceptionMatches(PyExc_StopIteration))
281 PyErr_Clear();
282 else
283 return NULL;
284 }
285 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000286}
287
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000288/*[clinic input]
289any as builtin_any
290
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300291 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000292 /
293
294Return True if bool(x) is True for any x in the iterable.
295
296If the iterable is empty, return False.
297[clinic start generated code]*/
298
Raymond Hettinger96229b12005-03-11 06:49:40 +0000299static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300300builtin_any(PyObject *module, PyObject *iterable)
301/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 PyObject *it, *item;
304 PyObject *(*iternext)(PyObject *);
305 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000306
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000307 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 if (it == NULL)
309 return NULL;
310 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 for (;;) {
313 item = iternext(it);
314 if (item == NULL)
315 break;
316 cmp = PyObject_IsTrue(item);
317 Py_DECREF(item);
318 if (cmp < 0) {
319 Py_DECREF(it);
320 return NULL;
321 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400322 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_DECREF(it);
324 Py_RETURN_TRUE;
325 }
326 }
327 Py_DECREF(it);
328 if (PyErr_Occurred()) {
329 if (PyErr_ExceptionMatches(PyExc_StopIteration))
330 PyErr_Clear();
331 else
332 return NULL;
333 }
334 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000335}
336
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000337/*[clinic input]
338ascii as builtin_ascii
339
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300340 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000341 /
342
343Return an ASCII-only representation of an object.
344
345As repr(), return a string containing a printable representation of an
346object, but escape the non-ASCII characters in the string returned by
347repr() using \\x, \\u or \\U escapes. This generates a string similar
348to that returned by repr() in Python 2.
349[clinic start generated code]*/
350
Georg Brandl559e5d72008-06-11 18:37:52 +0000351static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300352builtin_ascii(PyObject *module, PyObject *obj)
353/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000354{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000355 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000356}
357
Georg Brandl559e5d72008-06-11 18:37:52 +0000358
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000359/*[clinic input]
360bin as builtin_bin
361
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300362 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000363 /
364
365Return the binary representation of an integer.
366
367 >>> bin(2796202)
368 '0b1010101010101010101010'
369[clinic start generated code]*/
370
Guido van Rossum79f25d91997-04-29 20:08:16 +0000371static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300372builtin_bin(PyObject *module, PyObject *number)
373/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000374{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000375 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000376}
377
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000378
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000379/*[clinic input]
380callable as builtin_callable
381
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300382 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000383 /
384
385Return whether the object is callable (i.e., some kind of function).
386
387Note that classes are callable, as are instances of classes with a
388__call__() method.
389[clinic start generated code]*/
390
Antoine Pitroue71362d2010-11-27 22:00:11 +0000391static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300392builtin_callable(PyObject *module, PyObject *obj)
393/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000394{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000395 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000396}
397
Antoine Pitroue71362d2010-11-27 22:00:11 +0000398
Raymond Hettinger17301e92008-03-13 00:19:26 +0000399typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 PyObject_HEAD
401 PyObject *func;
402 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000403} filterobject;
404
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000405static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000406filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyObject *func, *seq;
409 PyObject *it;
410 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
413 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
416 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 /* Get iterator. */
419 it = PyObject_GetIter(seq);
420 if (it == NULL)
421 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* create filterobject structure */
424 lz = (filterobject *)type->tp_alloc(type, 0);
425 if (lz == NULL) {
426 Py_DECREF(it);
427 return NULL;
428 }
429 Py_INCREF(func);
430 lz->func = func;
431 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000434}
435
436static void
437filter_dealloc(filterobject *lz)
438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyObject_GC_UnTrack(lz);
440 Py_XDECREF(lz->func);
441 Py_XDECREF(lz->it);
442 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000443}
444
445static int
446filter_traverse(filterobject *lz, visitproc visit, void *arg)
447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 Py_VISIT(lz->it);
449 Py_VISIT(lz->func);
450 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000451}
452
453static PyObject *
454filter_next(filterobject *lz)
455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 PyObject *item;
457 PyObject *it = lz->it;
458 long ok;
459 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400460 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 iternext = *Py_TYPE(it)->tp_iternext;
463 for (;;) {
464 item = iternext(it);
465 if (item == NULL)
466 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000467
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400468 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 ok = PyObject_IsTrue(item);
470 } else {
471 PyObject *good;
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400472 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (good == NULL) {
474 Py_DECREF(item);
475 return NULL;
476 }
477 ok = PyObject_IsTrue(good);
478 Py_DECREF(good);
479 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200480 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 return item;
482 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200483 if (ok < 0)
484 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000486}
487
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000488static PyObject *
489filter_reduce(filterobject *lz)
490{
491 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
492}
493
494PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
495
496static PyMethodDef filter_methods[] = {
497 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
498 {NULL, NULL} /* sentinel */
499};
500
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000501PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000502"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000503\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000504Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000505is true. If function is None, return the items that are true.");
506
507PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyVarObject_HEAD_INIT(&PyType_Type, 0)
509 "filter", /* tp_name */
510 sizeof(filterobject), /* tp_basicsize */
511 0, /* tp_itemsize */
512 /* methods */
513 (destructor)filter_dealloc, /* tp_dealloc */
514 0, /* tp_print */
515 0, /* tp_getattr */
516 0, /* tp_setattr */
517 0, /* tp_reserved */
518 0, /* tp_repr */
519 0, /* tp_as_number */
520 0, /* tp_as_sequence */
521 0, /* tp_as_mapping */
522 0, /* tp_hash */
523 0, /* tp_call */
524 0, /* tp_str */
525 PyObject_GenericGetAttr, /* tp_getattro */
526 0, /* tp_setattro */
527 0, /* tp_as_buffer */
528 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
529 Py_TPFLAGS_BASETYPE, /* tp_flags */
530 filter_doc, /* tp_doc */
531 (traverseproc)filter_traverse, /* tp_traverse */
532 0, /* tp_clear */
533 0, /* tp_richcompare */
534 0, /* tp_weaklistoffset */
535 PyObject_SelfIter, /* tp_iter */
536 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000537 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 0, /* tp_members */
539 0, /* tp_getset */
540 0, /* tp_base */
541 0, /* tp_dict */
542 0, /* tp_descr_get */
543 0, /* tp_descr_set */
544 0, /* tp_dictoffset */
545 0, /* tp_init */
546 PyType_GenericAlloc, /* tp_alloc */
547 filter_new, /* tp_new */
548 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000549};
550
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000551
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000552/*[clinic input]
553format as builtin_format
554
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300555 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000556 format_spec: unicode(c_default="NULL") = ''
557 /
558
559Return value.__format__(format_spec)
560
561format_spec defaults to the empty string
562[clinic start generated code]*/
563
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000564static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300565builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
566/*[clinic end generated code: output=2f40bdfa4954b077 input=6325e751a1b29b86]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000567{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000568 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000569}
570
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000571/*[clinic input]
572chr as builtin_chr
573
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300574 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000575 /
576
577Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
578[clinic start generated code]*/
579
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000580static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300581builtin_chr_impl(PyObject *module, int i)
582/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000583{
584 return PyUnicode_FromOrdinal(i);
585}
Guido van Rossum09095f32000-03-10 23:00:52 +0000586
587
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200588static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000589source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000590{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200591 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000593 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000594
Martin Pantereeb896c2015-11-07 02:32:21 +0000595 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (PyUnicode_Check(cmd)) {
597 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200598 str = PyUnicode_AsUTF8AndSize(cmd, &size);
599 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 return NULL;
601 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000602 else if (PyBytes_Check(cmd)) {
603 str = PyBytes_AS_STRING(cmd);
604 size = PyBytes_GET_SIZE(cmd);
605 }
606 else if (PyByteArray_Check(cmd)) {
607 str = PyByteArray_AS_STRING(cmd);
608 size = PyByteArray_GET_SIZE(cmd);
609 }
610 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
611 /* Copy to NUL-terminated buffer. */
612 *cmd_copy = PyBytes_FromStringAndSize(
613 (const char *)view.buf, view.len);
614 PyBuffer_Release(&view);
615 if (*cmd_copy == NULL) {
616 return NULL;
617 }
618 str = PyBytes_AS_STRING(*cmd_copy);
619 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200620 }
621 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 PyErr_Format(PyExc_TypeError,
623 "%s() arg 1 must be a %s object",
624 funcname, what);
625 return NULL;
626 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200627
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200628 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300629 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000631 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return NULL;
633 }
634 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000635}
636
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000637/*[clinic input]
638compile as builtin_compile
639
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300640 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000641 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300642 mode: str
643 flags: int = 0
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300644 dont_inherit: int(c_default="0") = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300645 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000646
647Compile source into a code object that can be executed by exec() or eval().
648
649The source code may represent a Python module, statement or expression.
650The filename will be used for run-time error messages.
651The mode must be 'exec' to compile a module, 'single' to compile a
652single (interactive) statement, or 'eval' to compile an expression.
653The flags argument, if present, controls which future statements influence
654the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300655The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000656the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300657compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000658in addition to any features explicitly specified.
659[clinic start generated code]*/
660
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000661static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300662builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
663 const char *mode, int flags, int dont_inherit,
664 int optimize)
665/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000666{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000667 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200668 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000669 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 int is_ast;
671 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000673 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000674
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000675 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000676
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000677 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
679 {
680 PyErr_SetString(PyExc_ValueError,
681 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000682 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 }
684 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000685
Georg Brandl8334fd92010-12-04 10:26:46 +0000686 if (optimize < -1 || optimize > 2) {
687 PyErr_SetString(PyExc_ValueError,
688 "compile(): invalid optimize value");
689 goto error;
690 }
691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (!dont_inherit) {
693 PyEval_MergeCompilerFlags(&cf);
694 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000695
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000696 if (strcmp(mode, "exec") == 0)
697 compile_mode = 0;
698 else if (strcmp(mode, "eval") == 0)
699 compile_mode = 1;
700 else if (strcmp(mode, "single") == 0)
701 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 else {
703 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000704 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000705 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000707
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000708 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000710 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000712 if (flags & PyCF_ONLY_AST) {
713 Py_INCREF(source);
714 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 }
716 else {
717 PyArena *arena;
718 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200721 if (arena == NULL)
722 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000723 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (mod == NULL) {
725 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000726 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500728 if (!PyAST_Validate(mod)) {
729 PyArena_Free(arena);
730 goto error;
731 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200732 result = (PyObject*)PyAST_CompileObject(mod, filename,
733 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyArena_Free(arena);
735 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000736 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000738
Martin Panter61d6e4a2015-11-07 02:56:11 +0000739 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000741 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000742
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000743 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000744 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000745 goto finally;
746
747error:
748 result = NULL;
749finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200750 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000751 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000752}
753
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000754/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000755static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000756builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
761 return NULL;
762 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000763}
764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000765PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000766"dir([object]) -> list of strings\n"
767"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000768"If called without an argument, return the names in the current scope.\n"
769"Else, return an alphabetized list of names comprising (some of) the attributes\n"
770"of the given object, and of attributes reachable from it.\n"
771"If the object supplies a method named __dir__, it will be used; otherwise\n"
772"the default dir() logic is used and returns:\n"
773" for a module object: the module's attributes.\n"
774" for a class object: its attributes, and recursively the attributes\n"
775" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000776" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000777" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000778
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000779/*[clinic input]
780divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000781
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300782 x: object
783 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000784 /
785
Zachary Ware7f227d92016-04-28 14:39:50 -0500786Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000787[clinic start generated code]*/
788
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000789static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300790builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
791/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000792{
793 return PyNumber_Divmod(x, y);
794}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000795
796
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000797/*[clinic input]
798eval as builtin_eval
799
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300800 source: object
801 globals: object = None
802 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000803 /
804
805Evaluate the given source in the context of globals and locals.
806
807The source may be a string representing a Python expression
808or a code object as returned by compile().
809The globals must be a dictionary and locals can be any mapping,
810defaulting to the current globals and locals.
811If only globals is given, locals defaults to it.
812[clinic start generated code]*/
813
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000814static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300815builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400816 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300817/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000818{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000819 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200820 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (locals != Py_None && !PyMapping_Check(locals)) {
824 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
825 return NULL;
826 }
827 if (globals != Py_None && !PyDict_Check(globals)) {
828 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
829 "globals must be a real dict; try eval(expr, {}, mapping)"
830 : "globals must be a dict");
831 return NULL;
832 }
833 if (globals == Py_None) {
834 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100835 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100837 if (locals == NULL)
838 return NULL;
839 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
841 else if (locals == Py_None)
842 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (globals == NULL || locals == NULL) {
845 PyErr_SetString(PyExc_TypeError,
846 "eval must be given globals and locals "
847 "when called without a frame");
848 return NULL;
849 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000850
Victor Stinnerb44562b2013-11-06 19:03:11 +0100851 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
852 if (_PyDict_SetItemId(globals, &PyId___builtins__,
853 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return NULL;
855 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000856
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000857 if (PyCode_Check(source)) {
858 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyErr_SetString(PyExc_TypeError,
860 "code object passed to eval() may not contain free variables");
861 return NULL;
862 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000863 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000867 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (str == NULL)
869 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 while (*str == ' ' || *str == '\t')
872 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 (void)PyEval_MergeCompilerFlags(&cf);
875 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000876 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000878}
879
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000880/*[clinic input]
881exec as builtin_exec
882
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300883 source: object
884 globals: object = None
885 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000886 /
887
888Execute the given source in the context of globals and locals.
889
890The source may be a string representing one or more Python statements
891or a code object as returned by compile().
892The globals must be a dictionary and locals can be any mapping,
893defaulting to the current globals and locals.
894If only globals is given, locals defaults to it.
895[clinic start generated code]*/
896
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000897static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300898builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400899 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300900/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (globals == Py_None) {
905 globals = PyEval_GetGlobals();
906 if (locals == Py_None) {
907 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100908 if (locals == NULL)
909 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 }
911 if (!globals || !locals) {
912 PyErr_SetString(PyExc_SystemError,
913 "globals and locals cannot be NULL");
914 return NULL;
915 }
916 }
917 else if (locals == Py_None)
918 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000921 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 globals->ob_type->tp_name);
923 return NULL;
924 }
925 if (!PyMapping_Check(locals)) {
926 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000927 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 locals->ob_type->tp_name);
929 return NULL;
930 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100931 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
932 if (_PyDict_SetItemId(globals, &PyId___builtins__,
933 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 return NULL;
935 }
936
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000937 if (PyCode_Check(source)) {
938 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyErr_SetString(PyExc_TypeError,
940 "code object passed to exec() may not "
941 "contain free variables");
942 return NULL;
943 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000944 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 }
946 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000947 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200948 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyCompilerFlags cf;
950 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000951 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000952 "string, bytes or code", &cf,
953 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (str == NULL)
955 return NULL;
956 if (PyEval_MergeCompilerFlags(&cf))
957 v = PyRun_StringFlags(str, Py_file_input, globals,
958 locals, &cf);
959 else
960 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000961 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 }
963 if (v == NULL)
964 return NULL;
965 Py_DECREF(v);
966 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000967}
968
Georg Brandl7cae87c2006-09-06 06:51:57 +0000969
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000970/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000971static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000972builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyObject *v, *result, *dflt = NULL;
975 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
978 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (!PyUnicode_Check(name)) {
981 PyErr_SetString(PyExc_TypeError,
982 "getattr(): attribute name must be string");
983 return NULL;
984 }
985 result = PyObject_GetAttr(v, name);
986 if (result == NULL && dflt != NULL &&
987 PyErr_ExceptionMatches(PyExc_AttributeError))
988 {
989 PyErr_Clear();
990 Py_INCREF(dflt);
991 result = dflt;
992 }
993 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000994}
995
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000996PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000997"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000998\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000999Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1000When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001001exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001002
1003
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001004/*[clinic input]
1005globals as builtin_globals
1006
1007Return the dictionary containing the current scope's global variables.
1008
1009NOTE: Updates to this dictionary *will* affect name lookups in the current
1010global scope and vice-versa.
1011[clinic start generated code]*/
1012
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001013static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001014builtin_globals_impl(PyObject *module)
1015/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 d = PyEval_GetGlobals();
1020 Py_XINCREF(d);
1021 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001022}
1023
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001024
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001025/*[clinic input]
1026hasattr as builtin_hasattr
1027
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001028 obj: object
1029 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001030 /
1031
1032Return whether the object has an attribute with the given name.
1033
1034This is done by calling getattr(obj, name) and catching AttributeError.
1035[clinic start generated code]*/
1036
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001037static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001038builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1039/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001040{
1041 PyObject *v;
1042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (!PyUnicode_Check(name)) {
1044 PyErr_SetString(PyExc_TypeError,
1045 "hasattr(): attribute name must be string");
1046 return NULL;
1047 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001048 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001050 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001052 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001054 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 }
1056 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001057 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001058}
1059
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001060
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001061/* AC: gdb's integration with CPython relies on builtin_id having
1062 * the *exact* parameter names of "self" and "v", so we ensure we
1063 * preserve those name rather than using the AC defaults.
1064 */
1065/*[clinic input]
1066id as builtin_id
1067
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001068 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001069 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001070 /
1071
1072Return the identity of an object.
1073
1074This is guaranteed to be unique among simultaneously existing objects.
1075(CPython uses the object's memory address.)
1076[clinic start generated code]*/
1077
Guido van Rossum79f25d91997-04-29 20:08:16 +00001078static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001079builtin_id(PyModuleDef *self, PyObject *v)
1080/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001083}
1084
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001085
Raymond Hettingera6c60372008-03-13 01:26:19 +00001086/* map object ************************************************************/
1087
1088typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyObject_HEAD
1090 PyObject *iters;
1091 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001092} mapobject;
1093
Guido van Rossum79f25d91997-04-29 20:08:16 +00001094static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001095map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyObject *it, *iters, *func;
1098 mapobject *lz;
1099 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1102 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 numargs = PyTuple_Size(args);
1105 if (numargs < 2) {
1106 PyErr_SetString(PyExc_TypeError,
1107 "map() must have at least two arguments.");
1108 return NULL;
1109 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 iters = PyTuple_New(numargs-1);
1112 if (iters == NULL)
1113 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 for (i=1 ; i<numargs ; i++) {
1116 /* Get iterator. */
1117 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1118 if (it == NULL) {
1119 Py_DECREF(iters);
1120 return NULL;
1121 }
1122 PyTuple_SET_ITEM(iters, i-1, it);
1123 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 /* create mapobject structure */
1126 lz = (mapobject *)type->tp_alloc(type, 0);
1127 if (lz == NULL) {
1128 Py_DECREF(iters);
1129 return NULL;
1130 }
1131 lz->iters = iters;
1132 func = PyTuple_GET_ITEM(args, 0);
1133 Py_INCREF(func);
1134 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001137}
1138
1139static void
1140map_dealloc(mapobject *lz)
1141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PyObject_GC_UnTrack(lz);
1143 Py_XDECREF(lz->iters);
1144 Py_XDECREF(lz->func);
1145 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001146}
1147
1148static int
1149map_traverse(mapobject *lz, visitproc visit, void *arg)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 Py_VISIT(lz->iters);
1152 Py_VISIT(lz->func);
1153 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001154}
1155
1156static PyObject *
1157map_next(mapobject *lz)
1158{
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001159 PyObject *small_stack[5];
1160 PyObject **stack;
1161 Py_ssize_t niters, nargs, i;
1162 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001163
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001164 niters = PyTuple_GET_SIZE(lz->iters);
1165 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1166 stack = small_stack;
1167 }
1168 else {
1169 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1170 if (stack == NULL) {
1171 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 return NULL;
1173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001175
1176 nargs = 0;
1177 for (i=0; i < niters; i++) {
1178 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1179 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1180 if (val == NULL) {
1181 goto exit;
1182 }
1183 stack[i] = val;
1184 nargs++;
1185 }
1186
1187 result = _PyObject_FastCall(lz->func, stack, nargs);
1188
1189exit:
1190 for (i=0; i < nargs; i++) {
1191 Py_DECREF(stack[i]);
1192 }
1193 if (stack != small_stack) {
1194 PyMem_Free(stack);
1195 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001197}
1198
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001199static PyObject *
1200map_reduce(mapobject *lz)
1201{
1202 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1203 PyObject *args = PyTuple_New(numargs+1);
1204 Py_ssize_t i;
1205 if (args == NULL)
1206 return NULL;
1207 Py_INCREF(lz->func);
1208 PyTuple_SET_ITEM(args, 0, lz->func);
1209 for (i = 0; i<numargs; i++){
1210 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1211 Py_INCREF(it);
1212 PyTuple_SET_ITEM(args, i+1, it);
1213 }
1214
1215 return Py_BuildValue("ON", Py_TYPE(lz), args);
1216}
1217
1218static PyMethodDef map_methods[] = {
1219 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1220 {NULL, NULL} /* sentinel */
1221};
1222
1223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001224PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001225"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001226\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001227Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001229
Raymond Hettingera6c60372008-03-13 01:26:19 +00001230PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1232 "map", /* tp_name */
1233 sizeof(mapobject), /* tp_basicsize */
1234 0, /* tp_itemsize */
1235 /* methods */
1236 (destructor)map_dealloc, /* tp_dealloc */
1237 0, /* tp_print */
1238 0, /* tp_getattr */
1239 0, /* tp_setattr */
1240 0, /* tp_reserved */
1241 0, /* tp_repr */
1242 0, /* tp_as_number */
1243 0, /* tp_as_sequence */
1244 0, /* tp_as_mapping */
1245 0, /* tp_hash */
1246 0, /* tp_call */
1247 0, /* tp_str */
1248 PyObject_GenericGetAttr, /* tp_getattro */
1249 0, /* tp_setattro */
1250 0, /* tp_as_buffer */
1251 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1252 Py_TPFLAGS_BASETYPE, /* tp_flags */
1253 map_doc, /* tp_doc */
1254 (traverseproc)map_traverse, /* tp_traverse */
1255 0, /* tp_clear */
1256 0, /* tp_richcompare */
1257 0, /* tp_weaklistoffset */
1258 PyObject_SelfIter, /* tp_iter */
1259 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001260 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 0, /* tp_members */
1262 0, /* tp_getset */
1263 0, /* tp_base */
1264 0, /* tp_dict */
1265 0, /* tp_descr_get */
1266 0, /* tp_descr_set */
1267 0, /* tp_dictoffset */
1268 0, /* tp_init */
1269 PyType_GenericAlloc, /* tp_alloc */
1270 map_new, /* tp_new */
1271 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001272};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001273
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001274
1275/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001276static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001277builtin_next(PyObject *self, PyObject *args)
1278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 PyObject *it, *res;
1280 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1283 return NULL;
1284 if (!PyIter_Check(it)) {
1285 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001286 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 it->ob_type->tp_name);
1288 return NULL;
1289 }
1290
1291 res = (*it->ob_type->tp_iternext)(it);
1292 if (res != NULL) {
1293 return res;
1294 } else if (def != NULL) {
1295 if (PyErr_Occurred()) {
1296 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1297 return NULL;
1298 PyErr_Clear();
1299 }
1300 Py_INCREF(def);
1301 return def;
1302 } else if (PyErr_Occurred()) {
1303 return NULL;
1304 } else {
1305 PyErr_SetNone(PyExc_StopIteration);
1306 return NULL;
1307 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001308}
1309
1310PyDoc_STRVAR(next_doc,
1311"next(iterator[, default])\n\
1312\n\
1313Return the next item from the iterator. If default is given and the iterator\n\
1314is exhausted, it is returned instead of raising StopIteration.");
1315
1316
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001317/*[clinic input]
1318setattr as builtin_setattr
1319
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001320 obj: object
1321 name: object
1322 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001323 /
1324
1325Sets the named attribute on the given object to the specified value.
1326
1327setattr(x, 'y', v) is equivalent to ``x.y = v''
1328[clinic start generated code]*/
1329
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001330static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001331builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001332 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001333/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001334{
1335 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 return NULL;
1337 Py_INCREF(Py_None);
1338 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001339}
1340
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001341
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001342/*[clinic input]
1343delattr as builtin_delattr
1344
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001345 obj: object
1346 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001347 /
1348
1349Deletes the named attribute from the given object.
1350
1351delattr(x, 'y') is equivalent to ``del x.y''
1352[clinic start generated code]*/
1353
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001354static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001355builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1356/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001357{
1358 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 return NULL;
1360 Py_INCREF(Py_None);
1361 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001362}
1363
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001364
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001365/*[clinic input]
1366hash as builtin_hash
1367
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001368 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001369 /
1370
1371Return the hash value for the given object.
1372
1373Two objects that compare equal must also have the same hash value, but the
1374reverse is not necessarily true.
1375[clinic start generated code]*/
1376
Guido van Rossum79f25d91997-04-29 20:08:16 +00001377static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001378builtin_hash(PyObject *module, PyObject *obj)
1379/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001380{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001381 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001382
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001383 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 if (x == -1)
1385 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001386 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001387}
1388
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001389
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001390/*[clinic input]
1391hex as builtin_hex
1392
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001393 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001394 /
1395
1396Return the hexadecimal representation of an integer.
1397
1398 >>> hex(12648430)
1399 '0xc0ffee'
1400[clinic start generated code]*/
1401
Guido van Rossum79f25d91997-04-29 20:08:16 +00001402static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001403builtin_hex(PyObject *module, PyObject *number)
1404/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001405{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001406 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001407}
1408
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001409
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001410/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001411static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001412builtin_iter(PyObject *self, PyObject *args)
1413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1417 return NULL;
1418 if (w == NULL)
1419 return PyObject_GetIter(v);
1420 if (!PyCallable_Check(v)) {
1421 PyErr_SetString(PyExc_TypeError,
1422 "iter(v, w): v must be callable");
1423 return NULL;
1424 }
1425 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001426}
1427
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001428PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001429"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001430iter(callable, sentinel) -> iterator\n\
1431\n\
1432Get an iterator from an object. In the first form, the argument must\n\
1433supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001434In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001435
1436
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001437/*[clinic input]
1438len as builtin_len
1439
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001440 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001441 /
1442
1443Return the number of items in a container.
1444[clinic start generated code]*/
1445
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001446static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001447builtin_len(PyObject *module, PyObject *obj)
1448/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001451
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001452 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (res < 0 && PyErr_Occurred())
1454 return NULL;
1455 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001456}
1457
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001458
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001459/*[clinic input]
1460locals as builtin_locals
1461
1462Return a dictionary containing the current scope's local variables.
1463
1464NOTE: Whether or not updates to this dictionary will affect name lookups in
1465the local scope and vice-versa is *implementation dependent* and not
1466covered by any backwards compatibility guarantees.
1467[clinic start generated code]*/
1468
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001469static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001470builtin_locals_impl(PyObject *module)
1471/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 d = PyEval_GetLocals();
1476 Py_XINCREF(d);
1477 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001478}
1479
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001480
Guido van Rossum79f25d91997-04-29 20:08:16 +00001481static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001482min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001485 PyObject *emptytuple, *defaultval = NULL;
1486 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001488 const int positional = PyTuple_Size(args) > 1;
1489 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001490
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001491 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001493 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001495
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001496 emptytuple = PyTuple_New(0);
1497 if (emptytuple == NULL)
1498 return NULL;
1499 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1500 &keyfunc, &defaultval);
1501 Py_DECREF(emptytuple);
1502 if (!ret)
1503 return NULL;
1504
1505 if (positional && defaultval != NULL) {
1506 PyErr_Format(PyExc_TypeError,
1507 "Cannot specify a default for %s() with multiple "
1508 "positional arguments", name);
1509 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 it = PyObject_GetIter(v);
1513 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 return NULL;
1515 }
Tim Petersc3074532001-05-03 07:00:32 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 maxitem = NULL; /* the result */
1518 maxval = NULL; /* the value associated with the result */
1519 while (( item = PyIter_Next(it) )) {
1520 /* get the value from the key function */
1521 if (keyfunc != NULL) {
1522 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1523 if (val == NULL)
1524 goto Fail_it_item;
1525 }
1526 /* no key function; the value is the item */
1527 else {
1528 val = item;
1529 Py_INCREF(val);
1530 }
Tim Petersc3074532001-05-03 07:00:32 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 /* maximum value and item are unset; set them */
1533 if (maxval == NULL) {
1534 maxitem = item;
1535 maxval = val;
1536 }
1537 /* maximum value and item are set; update them as necessary */
1538 else {
1539 int cmp = PyObject_RichCompareBool(val, maxval, op);
1540 if (cmp < 0)
1541 goto Fail_it_item_and_val;
1542 else if (cmp > 0) {
1543 Py_DECREF(maxval);
1544 Py_DECREF(maxitem);
1545 maxval = val;
1546 maxitem = item;
1547 }
1548 else {
1549 Py_DECREF(item);
1550 Py_DECREF(val);
1551 }
1552 }
1553 }
1554 if (PyErr_Occurred())
1555 goto Fail_it;
1556 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001558 if (defaultval != NULL) {
1559 Py_INCREF(defaultval);
1560 maxitem = defaultval;
1561 } else {
1562 PyErr_Format(PyExc_ValueError,
1563 "%s() arg is an empty sequence", name);
1564 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 }
1566 else
1567 Py_DECREF(maxval);
1568 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001570
1571Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001573Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001575Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 Py_XDECREF(maxval);
1577 Py_XDECREF(maxitem);
1578 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001580}
1581
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001582/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001583static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001584builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001587}
1588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001589PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001590"min(iterable, *[, default=obj, key=func]) -> value\n\
1591min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001592\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001593With a single iterable argument, return its smallest item. The\n\
1594default keyword-only argument specifies an object to return if\n\
1595the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001596With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001597
1598
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001599/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001600static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001601builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001604}
1605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001606PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001607"max(iterable, *[, default=obj, key=func]) -> value\n\
1608max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001609\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001610With a single iterable argument, return its biggest item. The\n\
1611default keyword-only argument specifies an object to return if\n\
1612the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001613With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001614
1615
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001616/*[clinic input]
1617oct as builtin_oct
1618
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001619 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001620 /
1621
1622Return the octal representation of an integer.
1623
1624 >>> oct(342391)
1625 '0o1234567'
1626[clinic start generated code]*/
1627
Guido van Rossum79f25d91997-04-29 20:08:16 +00001628static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001629builtin_oct(PyObject *module, PyObject *number)
1630/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001631{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001632 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001633}
1634
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001635
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001636/*[clinic input]
1637ord as builtin_ord
1638
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001639 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001640 /
1641
1642Return the Unicode code point for a one-character string.
1643[clinic start generated code]*/
1644
Guido van Rossum79f25d91997-04-29 20:08:16 +00001645static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001646builtin_ord(PyObject *module, PyObject *c)
1647/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 long ord;
1650 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001651
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001652 if (PyBytes_Check(c)) {
1653 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001655 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 return PyLong_FromLong(ord);
1657 }
1658 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001659 else if (PyUnicode_Check(c)) {
1660 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001662 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001664 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 return PyLong_FromLong(ord);
1666 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001668 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001670 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001672 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 return PyLong_FromLong(ord);
1674 }
1675 }
1676 else {
1677 PyErr_Format(PyExc_TypeError,
1678 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001679 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 return NULL;
1681 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 PyErr_Format(PyExc_TypeError,
1684 "ord() expected a character, "
1685 "but string of length %zd found",
1686 size);
1687 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001688}
1689
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001690
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001691/*[clinic input]
1692pow as builtin_pow
1693
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001694 x: object
1695 y: object
1696 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001697 /
1698
1699Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1700
1701Some types, such as ints, are able to use a more efficient algorithm when
1702invoked using the three argument form.
1703[clinic start generated code]*/
1704
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001705static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001706builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1707/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001708{
1709 return PyNumber_Power(x, y, z);
1710}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001711
1712
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001713/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001714static PyObject *
1715builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1716{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001717 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001719 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001721
Benjamin Peterson00102562012-01-11 21:00:16 -05001722 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001723 return NULL;
1724 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1725 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 return NULL;
1727 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001728 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001729 if (file == NULL) {
1730 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1731 return NULL;
1732 }
1733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 /* sys.stdout may be None when FILE* stdout isn't connected */
1735 if (file == Py_None)
1736 Py_RETURN_NONE;
1737 }
Guido van Rossum34343512006-11-30 22:13:52 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 if (sep == Py_None) {
1740 sep = NULL;
1741 }
1742 else if (sep && !PyUnicode_Check(sep)) {
1743 PyErr_Format(PyExc_TypeError,
1744 "sep must be None or a string, not %.200s",
1745 sep->ob_type->tp_name);
1746 return NULL;
1747 }
1748 if (end == Py_None) {
1749 end = NULL;
1750 }
1751 else if (end && !PyUnicode_Check(end)) {
1752 PyErr_Format(PyExc_TypeError,
1753 "end must be None or a string, not %.200s",
1754 end->ob_type->tp_name);
1755 return NULL;
1756 }
Guido van Rossum34343512006-11-30 22:13:52 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 for (i = 0; i < PyTuple_Size(args); i++) {
1759 if (i > 0) {
1760 if (sep == NULL)
1761 err = PyFile_WriteString(" ", file);
1762 else
1763 err = PyFile_WriteObject(sep, file,
1764 Py_PRINT_RAW);
1765 if (err)
1766 return NULL;
1767 }
1768 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1769 Py_PRINT_RAW);
1770 if (err)
1771 return NULL;
1772 }
Guido van Rossum34343512006-11-30 22:13:52 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (end == NULL)
1775 err = PyFile_WriteString("\n", file);
1776 else
1777 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1778 if (err)
1779 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001780
Georg Brandlbc3b6822012-01-13 19:41:25 +01001781 if (flush != NULL) {
1782 PyObject *tmp;
1783 int do_flush = PyObject_IsTrue(flush);
1784 if (do_flush == -1)
1785 return NULL;
1786 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001787 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001788 if (tmp == NULL)
1789 return NULL;
1790 else
1791 Py_DECREF(tmp);
1792 }
1793 }
1794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001796}
1797
1798PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001799"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001800\n\
1801Prints the values to a stream, or to sys.stdout by default.\n\
1802Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001803file: a file-like object (stream); defaults to the current sys.stdout.\n\
1804sep: string inserted between values, default a space.\n\
1805end: string appended after the last value, default a newline.\n\
1806flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001807
1808
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001809/*[clinic input]
1810input as builtin_input
1811
1812 prompt: object(c_default="NULL") = None
1813 /
1814
1815Read a string from standard input. The trailing newline is stripped.
1816
1817The prompt string, if given, is printed to standard output without a
1818trailing newline before reading input.
1819
1820If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1821On *nix systems, readline is used if available.
1822[clinic start generated code]*/
1823
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001824static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001825builtin_input_impl(PyObject *module, PyObject *prompt)
1826/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001827{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001828 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1829 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1830 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 PyObject *tmp;
1832 long fd;
1833 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 /* Check that stdin/out/err are intact */
1836 if (fin == NULL || fin == Py_None) {
1837 PyErr_SetString(PyExc_RuntimeError,
1838 "input(): lost sys.stdin");
1839 return NULL;
1840 }
1841 if (fout == NULL || fout == Py_None) {
1842 PyErr_SetString(PyExc_RuntimeError,
1843 "input(): lost sys.stdout");
1844 return NULL;
1845 }
1846 if (ferr == NULL || ferr == Py_None) {
1847 PyErr_SetString(PyExc_RuntimeError,
1848 "input(): lost sys.stderr");
1849 return NULL;
1850 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001853 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 if (tmp == NULL)
1855 PyErr_Clear();
1856 else
1857 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 /* We should only use (GNU) readline if Python's sys.stdin and
1860 sys.stdout are the same as C's stdin and stdout, because we
1861 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001862 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 if (tmp == NULL) {
1864 PyErr_Clear();
1865 tty = 0;
1866 }
1867 else {
1868 fd = PyLong_AsLong(tmp);
1869 Py_DECREF(tmp);
1870 if (fd < 0 && PyErr_Occurred())
1871 return NULL;
1872 tty = fd == fileno(stdin) && isatty(fd);
1873 }
1874 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001875 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Martin Panterc9a6ab52015-10-10 01:25:38 +00001876 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001878 tty = 0;
1879 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 else {
1881 fd = PyLong_AsLong(tmp);
1882 Py_DECREF(tmp);
1883 if (fd < 0 && PyErr_Occurred())
1884 return NULL;
1885 tty = fd == fileno(stdout) && isatty(fd);
1886 }
1887 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 /* If we're interactive, use (GNU) readline */
1890 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001891 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001892 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001893 char *s = NULL;
1894 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1895 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1896 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001898 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001899
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001900 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001901 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001902 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* stdin is a text stream, so it must have an
1904 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001905 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001906 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001907 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1908 if (!stdin_encoding_str || !stdin_errors_str)
1909 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001910 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 if (tmp == NULL)
1912 PyErr_Clear();
1913 else
1914 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001915 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001916 /* We have a prompt, encode it as stdout would */
1917 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001919 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001920 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001921 if (!stdout_encoding || !stdout_errors)
1922 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001923 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001924 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1925 if (!stdout_encoding_str || !stdout_errors_str)
1926 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001927 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001928 if (stringpo == NULL)
1929 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001931 stdout_encoding_str, stdout_errors_str);
1932 Py_CLEAR(stdout_encoding);
1933 Py_CLEAR(stdout_errors);
1934 Py_CLEAR(stringpo);
1935 if (po == NULL)
1936 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001937 assert(PyBytes_Check(po));
1938 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 }
1940 else {
1941 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001942 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001944 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001946 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 if (!PyErr_Occurred())
1948 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001949 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001951
1952 len = strlen(s);
1953 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 PyErr_SetNone(PyExc_EOFError);
1955 result = NULL;
1956 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001957 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (len > PY_SSIZE_T_MAX) {
1959 PyErr_SetString(PyExc_OverflowError,
1960 "input: input too long");
1961 result = NULL;
1962 }
1963 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001964 len--; /* strip trailing '\n' */
1965 if (len != 0 && s[len-1] == '\r')
1966 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001967 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1968 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 }
1970 }
1971 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001972 Py_DECREF(stdin_errors);
1973 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 PyMem_FREE(s);
1975 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001976 _readline_errors:
1977 Py_XDECREF(stdin_encoding);
1978 Py_XDECREF(stdout_encoding);
1979 Py_XDECREF(stdin_errors);
1980 Py_XDECREF(stdout_errors);
1981 Py_XDECREF(po);
1982 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001986 if (prompt != NULL) {
1987 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 return NULL;
1989 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001990 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 if (tmp == NULL)
1992 PyErr_Clear();
1993 else
1994 Py_DECREF(tmp);
1995 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001996}
1997
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001998
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001999/*[clinic input]
2000repr as builtin_repr
2001
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002002 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002003 /
2004
2005Return the canonical string representation of the object.
2006
2007For many object types, including most builtins, eval(repr(obj)) == obj.
2008[clinic start generated code]*/
2009
Guido van Rossum79f25d91997-04-29 20:08:16 +00002010static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002011builtin_repr(PyObject *module, PyObject *obj)
2012/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002013{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002014 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002015}
2016
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002017
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002018/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2019 * or a semantic change to accept None for "ndigits"
2020 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002021static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002022builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyObject *ndigits = NULL;
2025 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002026 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2029 kwlist, &number, &ndigits))
2030 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (Py_TYPE(number)->tp_dict == NULL) {
2033 if (PyType_Ready(Py_TYPE(number)) < 0)
2034 return NULL;
2035 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002036
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002037 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002039 if (!PyErr_Occurred())
2040 PyErr_Format(PyExc_TypeError,
2041 "type %.100s doesn't define __round__ method",
2042 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 return NULL;
2044 }
Alex Martelliae211f92007-08-22 23:21:33 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002047 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002049 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2050 Py_DECREF(round);
2051 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002052}
2053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002054PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002055"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002056\n\
2057Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002058This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002059same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002060
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002061
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002062/*AC: we need to keep the kwds dict intact to easily call into the
2063 * list.sort method, which isn't currently supported in AC. So we just use
2064 * the initially generated signature with a custom implementation.
2065 */
2066/* [disabled clinic input]
2067sorted as builtin_sorted
2068
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002069 iterable as seq: object
2070 key as keyfunc: object = None
2071 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002072
2073Return a new list containing all items from the iterable in ascending order.
2074
2075A custom key function can be supplied to customise the sort order, and the
2076reverse flag can be set to request the result in descending order.
2077[end disabled clinic input]*/
2078
2079PyDoc_STRVAR(builtin_sorted__doc__,
2080"sorted($module, iterable, key=None, reverse=False)\n"
2081"--\n"
2082"\n"
2083"Return a new list containing all items from the iterable in ascending order.\n"
2084"\n"
2085"A custom key function can be supplied to customise the sort order, and the\n"
2086"reverse flag can be set to request the result in descending order.");
2087
2088#define BUILTIN_SORTED_METHODDEF \
2089 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
2090
Raymond Hettinger64958a12003-12-17 20:43:33 +00002091static PyObject *
2092builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2093{
Victor Stinner2990fa12016-08-22 23:21:55 +02002094 PyObject *newlist, *v, *seq, *keyfunc=NULL, **newargs;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 PyObject *callable;
2096 static char *kwlist[] = {"iterable", "key", "reverse", 0};
2097 int reverse;
Victor Stinner2990fa12016-08-22 23:21:55 +02002098 int nargs;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 /* args 1-3 should match listsort in Objects/listobject.c */
2101 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
2102 kwlist, &seq, &keyfunc, &reverse))
2103 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 newlist = PySequence_List(seq);
2106 if (newlist == NULL)
2107 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002108
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002109 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 if (callable == NULL) {
2111 Py_DECREF(newlist);
2112 return NULL;
2113 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002114
Victor Stinner2990fa12016-08-22 23:21:55 +02002115 newargs = &PyTuple_GET_ITEM(args, 1);
2116 nargs = PyTuple_GET_SIZE(args) - 1;
2117 v = _PyObject_FastCallDict(callable, newargs, nargs, kwds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 Py_DECREF(callable);
2119 if (v == NULL) {
2120 Py_DECREF(newlist);
2121 return NULL;
2122 }
2123 Py_DECREF(v);
2124 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002125}
2126
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002127
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002128/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002129static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002130builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 PyObject *v = NULL;
2133 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2136 return NULL;
2137 if (v == NULL) {
2138 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002139 if (d == NULL)
2140 return NULL;
2141 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 }
2143 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002144 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (d == NULL) {
2146 PyErr_SetString(PyExc_TypeError,
2147 "vars() argument must have __dict__ attribute");
2148 return NULL;
2149 }
2150 }
2151 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002152}
2153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002154PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002155"vars([object]) -> dictionary\n\
2156\n\
2157Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002158With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002159
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002160
2161/*[clinic input]
2162sum as builtin_sum
2163
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002164 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002165 start: object(c_default="NULL") = 0
2166 /
2167
2168Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2169
2170When the iterable is empty, return the start value.
2171This function is intended specifically for use with numeric values and may
2172reject non-numeric types.
2173[clinic start generated code]*/
2174
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002175static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002176builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2177/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002178{
2179 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002181
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002182 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 if (iter == NULL)
2184 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (result == NULL) {
2187 result = PyLong_FromLong(0);
2188 if (result == NULL) {
2189 Py_DECREF(iter);
2190 return NULL;
2191 }
2192 } else {
2193 /* reject string values for 'start' parameter */
2194 if (PyUnicode_Check(result)) {
2195 PyErr_SetString(PyExc_TypeError,
2196 "sum() can't sum strings [use ''.join(seq) instead]");
2197 Py_DECREF(iter);
2198 return NULL;
2199 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002200 if (PyBytes_Check(result)) {
2201 PyErr_SetString(PyExc_TypeError,
2202 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002203 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002204 return NULL;
2205 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 if (PyByteArray_Check(result)) {
2207 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002208 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 Py_DECREF(iter);
2210 return NULL;
2211 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 Py_INCREF(result);
2213 }
Alex Martellia70b1912003-04-22 08:12:33 +00002214
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002215#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2217 Assumes all inputs are the same type. If the assumption fails, default
2218 to the more general routine.
2219 */
2220 if (PyLong_CheckExact(result)) {
2221 int overflow;
2222 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2223 /* If this already overflowed, don't even enter the loop. */
2224 if (overflow == 0) {
2225 Py_DECREF(result);
2226 result = NULL;
2227 }
2228 while(result == NULL) {
2229 item = PyIter_Next(iter);
2230 if (item == NULL) {
2231 Py_DECREF(iter);
2232 if (PyErr_Occurred())
2233 return NULL;
2234 return PyLong_FromLong(i_result);
2235 }
2236 if (PyLong_CheckExact(item)) {
2237 long b = PyLong_AsLongAndOverflow(item, &overflow);
2238 long x = i_result + b;
2239 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2240 i_result = x;
2241 Py_DECREF(item);
2242 continue;
2243 }
2244 }
2245 /* Either overflowed or is not an int. Restore real objects and process normally */
2246 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002247 if (result == NULL) {
2248 Py_DECREF(item);
2249 Py_DECREF(iter);
2250 return NULL;
2251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 temp = PyNumber_Add(result, item);
2253 Py_DECREF(result);
2254 Py_DECREF(item);
2255 result = temp;
2256 if (result == NULL) {
2257 Py_DECREF(iter);
2258 return NULL;
2259 }
2260 }
2261 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 if (PyFloat_CheckExact(result)) {
2264 double f_result = PyFloat_AS_DOUBLE(result);
2265 Py_DECREF(result);
2266 result = NULL;
2267 while(result == NULL) {
2268 item = PyIter_Next(iter);
2269 if (item == NULL) {
2270 Py_DECREF(iter);
2271 if (PyErr_Occurred())
2272 return NULL;
2273 return PyFloat_FromDouble(f_result);
2274 }
2275 if (PyFloat_CheckExact(item)) {
2276 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2277 f_result += PyFloat_AS_DOUBLE(item);
2278 PyFPE_END_PROTECT(f_result)
2279 Py_DECREF(item);
2280 continue;
2281 }
2282 if (PyLong_CheckExact(item)) {
2283 long value;
2284 int overflow;
2285 value = PyLong_AsLongAndOverflow(item, &overflow);
2286 if (!overflow) {
2287 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2288 f_result += (double)value;
2289 PyFPE_END_PROTECT(f_result)
2290 Py_DECREF(item);
2291 continue;
2292 }
2293 }
2294 result = PyFloat_FromDouble(f_result);
2295 temp = PyNumber_Add(result, item);
2296 Py_DECREF(result);
2297 Py_DECREF(item);
2298 result = temp;
2299 if (result == NULL) {
2300 Py_DECREF(iter);
2301 return NULL;
2302 }
2303 }
2304 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002305#endif
2306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 for(;;) {
2308 item = PyIter_Next(iter);
2309 if (item == NULL) {
2310 /* error, or end-of-sequence */
2311 if (PyErr_Occurred()) {
2312 Py_DECREF(result);
2313 result = NULL;
2314 }
2315 break;
2316 }
2317 /* It's tempting to use PyNumber_InPlaceAdd instead of
2318 PyNumber_Add here, to avoid quadratic running time
2319 when doing 'sum(list_of_lists, [])'. However, this
2320 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 empty = []
2323 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 would change the value of empty. */
2326 temp = PyNumber_Add(result, item);
2327 Py_DECREF(result);
2328 Py_DECREF(item);
2329 result = temp;
2330 if (result == NULL)
2331 break;
2332 }
2333 Py_DECREF(iter);
2334 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002335}
2336
Alex Martellia70b1912003-04-22 08:12:33 +00002337
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002338/*[clinic input]
2339isinstance as builtin_isinstance
2340
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002341 obj: object
2342 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002343 /
2344
2345Return whether an object is an instance of a class or of a subclass thereof.
2346
2347A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2348check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2349or ...`` etc.
2350[clinic start generated code]*/
2351
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002352static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002353builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002354 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002355/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002358
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002359 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 if (retval < 0)
2361 return NULL;
2362 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002363}
2364
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002365
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002366/*[clinic input]
2367issubclass as builtin_issubclass
2368
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002369 cls: object
2370 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002371 /
2372
2373Return whether 'cls' is a derived from another class or is the same class.
2374
2375A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2376check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2377or ...`` etc.
2378[clinic start generated code]*/
2379
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002380static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002381builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002382 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002383/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002386
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002387 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 if (retval < 0)
2389 return NULL;
2390 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002391}
2392
2393
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002394typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 PyObject_HEAD
2396 Py_ssize_t tuplesize;
2397 PyObject *ittuple; /* tuple of iterators */
2398 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002399} zipobject;
2400
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002401static PyObject *
2402zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 zipobject *lz;
2405 Py_ssize_t i;
2406 PyObject *ittuple; /* tuple of iterators */
2407 PyObject *result;
2408 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2411 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 /* args must be a tuple */
2414 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 /* obtain iterators */
2417 ittuple = PyTuple_New(tuplesize);
2418 if (ittuple == NULL)
2419 return NULL;
2420 for (i=0; i < tuplesize; ++i) {
2421 PyObject *item = PyTuple_GET_ITEM(args, i);
2422 PyObject *it = PyObject_GetIter(item);
2423 if (it == NULL) {
2424 if (PyErr_ExceptionMatches(PyExc_TypeError))
2425 PyErr_Format(PyExc_TypeError,
2426 "zip argument #%zd must support iteration",
2427 i+1);
2428 Py_DECREF(ittuple);
2429 return NULL;
2430 }
2431 PyTuple_SET_ITEM(ittuple, i, it);
2432 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 /* create a result holder */
2435 result = PyTuple_New(tuplesize);
2436 if (result == NULL) {
2437 Py_DECREF(ittuple);
2438 return NULL;
2439 }
2440 for (i=0 ; i < tuplesize ; i++) {
2441 Py_INCREF(Py_None);
2442 PyTuple_SET_ITEM(result, i, Py_None);
2443 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 /* create zipobject structure */
2446 lz = (zipobject *)type->tp_alloc(type, 0);
2447 if (lz == NULL) {
2448 Py_DECREF(ittuple);
2449 Py_DECREF(result);
2450 return NULL;
2451 }
2452 lz->ittuple = ittuple;
2453 lz->tuplesize = tuplesize;
2454 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002457}
2458
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002459static void
2460zip_dealloc(zipobject *lz)
2461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 PyObject_GC_UnTrack(lz);
2463 Py_XDECREF(lz->ittuple);
2464 Py_XDECREF(lz->result);
2465 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002466}
2467
2468static int
2469zip_traverse(zipobject *lz, visitproc visit, void *arg)
2470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 Py_VISIT(lz->ittuple);
2472 Py_VISIT(lz->result);
2473 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002474}
2475
2476static PyObject *
2477zip_next(zipobject *lz)
2478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 Py_ssize_t i;
2480 Py_ssize_t tuplesize = lz->tuplesize;
2481 PyObject *result = lz->result;
2482 PyObject *it;
2483 PyObject *item;
2484 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 if (tuplesize == 0)
2487 return NULL;
2488 if (Py_REFCNT(result) == 1) {
2489 Py_INCREF(result);
2490 for (i=0 ; i < tuplesize ; i++) {
2491 it = PyTuple_GET_ITEM(lz->ittuple, i);
2492 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002493 if (item == NULL) {
2494 Py_DECREF(result);
2495 return NULL;
2496 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 olditem = PyTuple_GET_ITEM(result, i);
2498 PyTuple_SET_ITEM(result, i, item);
2499 Py_DECREF(olditem);
2500 }
2501 } else {
2502 result = PyTuple_New(tuplesize);
2503 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002504 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 for (i=0 ; i < tuplesize ; i++) {
2506 it = PyTuple_GET_ITEM(lz->ittuple, i);
2507 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002508 if (item == NULL) {
2509 Py_DECREF(result);
2510 return NULL;
2511 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 PyTuple_SET_ITEM(result, i, item);
2513 }
2514 }
2515 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002516}
Barry Warsawbd599b52000-08-03 15:45:29 +00002517
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002518static PyObject *
2519zip_reduce(zipobject *lz)
2520{
2521 /* Just recreate the zip with the internal iterator tuple */
2522 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2523}
2524
2525static PyMethodDef zip_methods[] = {
2526 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2527 {NULL, NULL} /* sentinel */
2528};
2529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002530PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002531"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002532\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002533Return a zip object whose .__next__() method returns a tuple where\n\
2534the i-th element comes from the i-th iterable argument. The .__next__()\n\
2535method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002536is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002537
2538PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2540 "zip", /* tp_name */
2541 sizeof(zipobject), /* tp_basicsize */
2542 0, /* tp_itemsize */
2543 /* methods */
2544 (destructor)zip_dealloc, /* tp_dealloc */
2545 0, /* tp_print */
2546 0, /* tp_getattr */
2547 0, /* tp_setattr */
2548 0, /* tp_reserved */
2549 0, /* tp_repr */
2550 0, /* tp_as_number */
2551 0, /* tp_as_sequence */
2552 0, /* tp_as_mapping */
2553 0, /* tp_hash */
2554 0, /* tp_call */
2555 0, /* tp_str */
2556 PyObject_GenericGetAttr, /* tp_getattro */
2557 0, /* tp_setattro */
2558 0, /* tp_as_buffer */
2559 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2560 Py_TPFLAGS_BASETYPE, /* tp_flags */
2561 zip_doc, /* tp_doc */
2562 (traverseproc)zip_traverse, /* tp_traverse */
2563 0, /* tp_clear */
2564 0, /* tp_richcompare */
2565 0, /* tp_weaklistoffset */
2566 PyObject_SelfIter, /* tp_iter */
2567 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002568 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 0, /* tp_members */
2570 0, /* tp_getset */
2571 0, /* tp_base */
2572 0, /* tp_dict */
2573 0, /* tp_descr_get */
2574 0, /* tp_descr_set */
2575 0, /* tp_dictoffset */
2576 0, /* tp_init */
2577 PyType_GenericAlloc, /* tp_alloc */
2578 zip_new, /* tp_new */
2579 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002580};
Barry Warsawbd599b52000-08-03 15:45:29 +00002581
2582
Guido van Rossum79f25d91997-04-29 20:08:16 +00002583static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 {"__build_class__", (PyCFunction)builtin___build_class__,
2585 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2586 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002587 BUILTIN_ABS_METHODDEF
2588 BUILTIN_ALL_METHODDEF
2589 BUILTIN_ANY_METHODDEF
2590 BUILTIN_ASCII_METHODDEF
2591 BUILTIN_BIN_METHODDEF
2592 BUILTIN_CALLABLE_METHODDEF
2593 BUILTIN_CHR_METHODDEF
2594 BUILTIN_COMPILE_METHODDEF
2595 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002597 BUILTIN_DIVMOD_METHODDEF
2598 BUILTIN_EVAL_METHODDEF
2599 BUILTIN_EXEC_METHODDEF
2600 BUILTIN_FORMAT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002602 BUILTIN_GLOBALS_METHODDEF
2603 BUILTIN_HASATTR_METHODDEF
2604 BUILTIN_HASH_METHODDEF
2605 BUILTIN_HEX_METHODDEF
2606 BUILTIN_ID_METHODDEF
2607 BUILTIN_INPUT_METHODDEF
2608 BUILTIN_ISINSTANCE_METHODDEF
2609 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002611 BUILTIN_LEN_METHODDEF
2612 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2614 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2615 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002616 BUILTIN_OCT_METHODDEF
2617 BUILTIN_ORD_METHODDEF
2618 BUILTIN_POW_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002620 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002622 BUILTIN_SETATTR_METHODDEF
2623 BUILTIN_SORTED_METHODDEF
2624 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2626 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002627};
2628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002629PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002630"Built-in functions, exceptions, and other objects.\n\
2631\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002632Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002633
Martin v. Löwis1a214512008-06-11 05:26:20 +00002634static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 PyModuleDef_HEAD_INIT,
2636 "builtins",
2637 builtin_doc,
2638 -1, /* multiple "initialization" just copies the module dict. */
2639 builtin_methods,
2640 NULL,
2641 NULL,
2642 NULL,
2643 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002644};
2645
2646
Guido van Rossum25ce5661997-08-02 03:10:38 +00002647PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002648_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002651
2652 if (PyType_Ready(&PyFilter_Type) < 0 ||
2653 PyType_Ready(&PyMap_Type) < 0 ||
2654 PyType_Ready(&PyZip_Type) < 0)
2655 return NULL;
2656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 mod = PyModule_Create(&builtinsmodule);
2658 if (mod == NULL)
2659 return NULL;
2660 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002661
Tim Peters7571a0f2003-03-23 17:52:28 +00002662#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 /* "builtins" exposes a number of statically allocated objects
2664 * that, before this code was added in 2.3, never showed up in
2665 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2666 * result, programs leaking references to None and False (etc)
2667 * couldn't be diagnosed by examining sys.getobjects(0).
2668 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002669#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2670#else
2671#define ADD_TO_ALL(OBJECT) (void)0
2672#endif
2673
Tim Peters4b7625e2001-09-13 21:37:17 +00002674#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2676 return NULL; \
2677 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 SETBUILTIN("None", Py_None);
2680 SETBUILTIN("Ellipsis", Py_Ellipsis);
2681 SETBUILTIN("NotImplemented", Py_NotImplemented);
2682 SETBUILTIN("False", Py_False);
2683 SETBUILTIN("True", Py_True);
2684 SETBUILTIN("bool", &PyBool_Type);
2685 SETBUILTIN("memoryview", &PyMemoryView_Type);
2686 SETBUILTIN("bytearray", &PyByteArray_Type);
2687 SETBUILTIN("bytes", &PyBytes_Type);
2688 SETBUILTIN("classmethod", &PyClassMethod_Type);
2689 SETBUILTIN("complex", &PyComplex_Type);
2690 SETBUILTIN("dict", &PyDict_Type);
2691 SETBUILTIN("enumerate", &PyEnum_Type);
2692 SETBUILTIN("filter", &PyFilter_Type);
2693 SETBUILTIN("float", &PyFloat_Type);
2694 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2695 SETBUILTIN("property", &PyProperty_Type);
2696 SETBUILTIN("int", &PyLong_Type);
2697 SETBUILTIN("list", &PyList_Type);
2698 SETBUILTIN("map", &PyMap_Type);
2699 SETBUILTIN("object", &PyBaseObject_Type);
2700 SETBUILTIN("range", &PyRange_Type);
2701 SETBUILTIN("reversed", &PyReversed_Type);
2702 SETBUILTIN("set", &PySet_Type);
2703 SETBUILTIN("slice", &PySlice_Type);
2704 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2705 SETBUILTIN("str", &PyUnicode_Type);
2706 SETBUILTIN("super", &PySuper_Type);
2707 SETBUILTIN("tuple", &PyTuple_Type);
2708 SETBUILTIN("type", &PyType_Type);
2709 SETBUILTIN("zip", &PyZip_Type);
2710 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2711 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002712 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 return NULL;
2714 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002715 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002718#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002719#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002720}