blob: da9ad55ce8b867221c98a3afb42b2665477d11f4 [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*/
Steve Dowercc16be82016-09-08 10:35:16 -070024#if defined(__APPLE__)
25const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Steve Dowercc16be82016-09-08 10:35:16 -070027#elif defined(MS_WINDOWS)
28/* may be changed by initfsencoding(), but should never be free()d */
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000029const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000030int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020031#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000032const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000033int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000034#endif
Steve Dowercc16be82016-09-08 10:35:16 -070035const char *Py_FileSystemDefaultEncodeErrors = "surrogateescape";
Mark Hammondef8b6542001-05-13 08:04:26 +000036
Victor Stinnerbd303c12013-11-07 23:07:29 +010037_Py_IDENTIFIER(__builtins__);
38_Py_IDENTIFIER(__dict__);
39_Py_IDENTIFIER(__prepare__);
40_Py_IDENTIFIER(__round__);
41_Py_IDENTIFIER(encoding);
42_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020043_Py_IDENTIFIER(fileno);
44_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(metaclass);
46_Py_IDENTIFIER(sort);
47_Py_IDENTIFIER(stdin);
48_Py_IDENTIFIER(stdout);
49_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020050
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030051#include "clinic/bltinmodule.c.h"
52
Nick Coghlanf9e227e2014-08-17 14:01:19 +100053/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000054static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000055builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
56{
Nick Coghlande31b192011-10-23 22:04:16 +100057 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020059 Py_ssize_t nargs;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010060 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 assert(args != NULL);
63 if (!PyTuple_Check(args)) {
64 PyErr_SetString(PyExc_TypeError,
65 "__build_class__: args is not a tuple");
66 return NULL;
67 }
68 nargs = PyTuple_GET_SIZE(args);
69 if (nargs < 2) {
70 PyErr_SetString(PyExc_TypeError,
71 "__build_class__: not enough arguments");
72 return NULL;
73 }
74 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050075 if (!PyFunction_Check(func)) {
76 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050077 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050078 return NULL;
79 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 name = PyTuple_GET_ITEM(args, 1);
81 if (!PyUnicode_Check(name)) {
82 PyErr_SetString(PyExc_TypeError,
83 "__build_class__: name is not a string");
84 return NULL;
85 }
86 bases = PyTuple_GetSlice(args, 2, nargs);
87 if (bases == NULL)
88 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 if (kwds == NULL) {
91 meta = NULL;
92 mkw = NULL;
93 }
94 else {
95 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
96 if (mkw == NULL) {
97 Py_DECREF(bases);
98 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000099 }
Victor Stinnerae9f1612013-11-06 22:46:51 +0100100 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 if (meta != NULL) {
102 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100103 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 Py_DECREF(meta);
105 Py_DECREF(mkw);
106 Py_DECREF(bases);
107 return NULL;
108 }
Nick Coghlande31b192011-10-23 22:04:16 +1000109 /* metaclass is explicitly given, check if it's indeed a class */
110 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 }
112 }
113 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000114 /* if there are no bases, use type: */
115 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000117 }
118 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 else {
120 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
121 meta = (PyObject *) (base0->ob_type);
122 }
123 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000124 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000126
Nick Coghlande31b192011-10-23 22:04:16 +1000127 if (isclass) {
128 /* meta is really a class, so check for a more derived
129 metaclass, or possible metaclass conflicts: */
130 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
131 bases);
132 if (winner == NULL) {
133 Py_DECREF(meta);
134 Py_XDECREF(mkw);
135 Py_DECREF(bases);
136 return NULL;
137 }
138 if (winner != meta) {
139 Py_DECREF(meta);
140 meta = winner;
141 Py_INCREF(meta);
142 }
143 }
144 /* else: meta is not a class, so we cannot do the metaclass
145 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200146 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (prep == NULL) {
148 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
149 PyErr_Clear();
Eric Snow4f29e752016-09-08 15:11:11 -0700150 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 }
152 else {
153 Py_DECREF(meta);
154 Py_XDECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
158 }
159 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200160 PyObject *pargs[2] = {name, bases};
161 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 Py_DECREF(prep);
163 }
164 if (ns == NULL) {
165 Py_DECREF(meta);
166 Py_XDECREF(mkw);
167 Py_DECREF(bases);
168 return NULL;
169 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500170 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
171 NULL, 0, NULL, 0, NULL, 0, NULL,
172 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 if (cell != NULL) {
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200174 PyObject *margs[3] = {name, bases, ns};
175 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700176 if (cls != NULL && PyCell_Check(cell))
177 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 Py_DECREF(cell);
179 }
180 Py_DECREF(ns);
181 Py_DECREF(meta);
182 Py_XDECREF(mkw);
183 Py_DECREF(bases);
184 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000185}
186
187PyDoc_STRVAR(build_class_doc,
188"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
189\n\
190Internal helper function used by the class statement.");
191
192static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000193builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
196 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400197 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400198 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000199
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400200 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 kwlist, &name, &globals, &locals, &fromlist, &level))
202 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400203 return PyImport_ImportModuleLevelObject(name, globals, locals,
204 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000205}
206
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000207PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400208"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000209\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000210Import a module. Because this function is meant for use by the Python\n\
211interpreter and not for general use it is better to use\n\
212importlib.import_module() to programmatically import a module.\n\
213\n\
214The globals argument is only used to determine the context;\n\
215they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000216should be a list of names to emulate ``from name import ...'', or an\n\
217empty list to emulate ``import name''.\n\
218When importing a module from a package, note that __import__('A.B', ...)\n\
219returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400221absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000222is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000223
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000224
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000225/*[clinic input]
226abs as builtin_abs
227
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300228 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000229 /
230
231Return the absolute value of the argument.
232[clinic start generated code]*/
233
Guido van Rossum79f25d91997-04-29 20:08:16 +0000234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300235builtin_abs(PyObject *module, PyObject *x)
236/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000237{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000238 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000239}
240
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000241/*[clinic input]
242all as builtin_all
243
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300244 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000245 /
246
247Return True if bool(x) is True for all values x in the iterable.
248
249If the iterable is empty, return True.
250[clinic start generated code]*/
251
Raymond Hettinger96229b12005-03-11 06:49:40 +0000252static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300253builtin_all(PyObject *module, PyObject *iterable)
254/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 PyObject *it, *item;
257 PyObject *(*iternext)(PyObject *);
258 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000259
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000260 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 if (it == NULL)
262 return NULL;
263 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 for (;;) {
266 item = iternext(it);
267 if (item == NULL)
268 break;
269 cmp = PyObject_IsTrue(item);
270 Py_DECREF(item);
271 if (cmp < 0) {
272 Py_DECREF(it);
273 return NULL;
274 }
275 if (cmp == 0) {
276 Py_DECREF(it);
277 Py_RETURN_FALSE;
278 }
279 }
280 Py_DECREF(it);
281 if (PyErr_Occurred()) {
282 if (PyErr_ExceptionMatches(PyExc_StopIteration))
283 PyErr_Clear();
284 else
285 return NULL;
286 }
287 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000288}
289
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000290/*[clinic input]
291any as builtin_any
292
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300293 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000294 /
295
296Return True if bool(x) is True for any x in the iterable.
297
298If the iterable is empty, return False.
299[clinic start generated code]*/
300
Raymond Hettinger96229b12005-03-11 06:49:40 +0000301static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300302builtin_any(PyObject *module, PyObject *iterable)
303/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 PyObject *it, *item;
306 PyObject *(*iternext)(PyObject *);
307 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000308
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000309 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (it == NULL)
311 return NULL;
312 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 for (;;) {
315 item = iternext(it);
316 if (item == NULL)
317 break;
318 cmp = PyObject_IsTrue(item);
319 Py_DECREF(item);
320 if (cmp < 0) {
321 Py_DECREF(it);
322 return NULL;
323 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400324 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 Py_DECREF(it);
326 Py_RETURN_TRUE;
327 }
328 }
329 Py_DECREF(it);
330 if (PyErr_Occurred()) {
331 if (PyErr_ExceptionMatches(PyExc_StopIteration))
332 PyErr_Clear();
333 else
334 return NULL;
335 }
336 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000337}
338
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000339/*[clinic input]
340ascii as builtin_ascii
341
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300342 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000343 /
344
345Return an ASCII-only representation of an object.
346
347As repr(), return a string containing a printable representation of an
348object, but escape the non-ASCII characters in the string returned by
349repr() using \\x, \\u or \\U escapes. This generates a string similar
350to that returned by repr() in Python 2.
351[clinic start generated code]*/
352
Georg Brandl559e5d72008-06-11 18:37:52 +0000353static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300354builtin_ascii(PyObject *module, PyObject *obj)
355/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000356{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000357 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000358}
359
Georg Brandl559e5d72008-06-11 18:37:52 +0000360
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000361/*[clinic input]
362bin as builtin_bin
363
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300364 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000365 /
366
367Return the binary representation of an integer.
368
369 >>> bin(2796202)
370 '0b1010101010101010101010'
371[clinic start generated code]*/
372
Guido van Rossum79f25d91997-04-29 20:08:16 +0000373static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300374builtin_bin(PyObject *module, PyObject *number)
375/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000376{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000377 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000378}
379
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000380
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000381/*[clinic input]
382callable as builtin_callable
383
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300384 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000385 /
386
387Return whether the object is callable (i.e., some kind of function).
388
389Note that classes are callable, as are instances of classes with a
390__call__() method.
391[clinic start generated code]*/
392
Antoine Pitroue71362d2010-11-27 22:00:11 +0000393static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300394builtin_callable(PyObject *module, PyObject *obj)
395/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000396{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000397 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000398}
399
Antoine Pitroue71362d2010-11-27 22:00:11 +0000400
Raymond Hettinger17301e92008-03-13 00:19:26 +0000401typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 PyObject_HEAD
403 PyObject *func;
404 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000405} filterobject;
406
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000407static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000408filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyObject *func, *seq;
411 PyObject *it;
412 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
415 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
418 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 /* Get iterator. */
421 it = PyObject_GetIter(seq);
422 if (it == NULL)
423 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* create filterobject structure */
426 lz = (filterobject *)type->tp_alloc(type, 0);
427 if (lz == NULL) {
428 Py_DECREF(it);
429 return NULL;
430 }
431 Py_INCREF(func);
432 lz->func = func;
433 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000436}
437
438static void
439filter_dealloc(filterobject *lz)
440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PyObject_GC_UnTrack(lz);
442 Py_XDECREF(lz->func);
443 Py_XDECREF(lz->it);
444 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000445}
446
447static int
448filter_traverse(filterobject *lz, visitproc visit, void *arg)
449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 Py_VISIT(lz->it);
451 Py_VISIT(lz->func);
452 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000453}
454
455static PyObject *
456filter_next(filterobject *lz)
457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyObject *item;
459 PyObject *it = lz->it;
460 long ok;
461 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400462 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 iternext = *Py_TYPE(it)->tp_iternext;
465 for (;;) {
466 item = iternext(it);
467 if (item == NULL)
468 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000469
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400470 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 ok = PyObject_IsTrue(item);
472 } else {
473 PyObject *good;
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400474 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (good == NULL) {
476 Py_DECREF(item);
477 return NULL;
478 }
479 ok = PyObject_IsTrue(good);
480 Py_DECREF(good);
481 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200482 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return item;
484 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200485 if (ok < 0)
486 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000488}
489
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000490static PyObject *
491filter_reduce(filterobject *lz)
492{
493 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
494}
495
496PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
497
498static PyMethodDef filter_methods[] = {
499 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
500 {NULL, NULL} /* sentinel */
501};
502
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000503PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000504"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000505\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000506Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000507is true. If function is None, return the items that are true.");
508
509PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyVarObject_HEAD_INIT(&PyType_Type, 0)
511 "filter", /* tp_name */
512 sizeof(filterobject), /* tp_basicsize */
513 0, /* tp_itemsize */
514 /* methods */
515 (destructor)filter_dealloc, /* tp_dealloc */
516 0, /* tp_print */
517 0, /* tp_getattr */
518 0, /* tp_setattr */
519 0, /* tp_reserved */
520 0, /* tp_repr */
521 0, /* tp_as_number */
522 0, /* tp_as_sequence */
523 0, /* tp_as_mapping */
524 0, /* tp_hash */
525 0, /* tp_call */
526 0, /* tp_str */
527 PyObject_GenericGetAttr, /* tp_getattro */
528 0, /* tp_setattro */
529 0, /* tp_as_buffer */
530 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
531 Py_TPFLAGS_BASETYPE, /* tp_flags */
532 filter_doc, /* tp_doc */
533 (traverseproc)filter_traverse, /* tp_traverse */
534 0, /* tp_clear */
535 0, /* tp_richcompare */
536 0, /* tp_weaklistoffset */
537 PyObject_SelfIter, /* tp_iter */
538 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000539 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 0, /* tp_members */
541 0, /* tp_getset */
542 0, /* tp_base */
543 0, /* tp_dict */
544 0, /* tp_descr_get */
545 0, /* tp_descr_set */
546 0, /* tp_dictoffset */
547 0, /* tp_init */
548 PyType_GenericAlloc, /* tp_alloc */
549 filter_new, /* tp_new */
550 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000551};
552
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000553
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000554/*[clinic input]
555format as builtin_format
556
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300557 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000558 format_spec: unicode(c_default="NULL") = ''
559 /
560
561Return value.__format__(format_spec)
562
563format_spec defaults to the empty string
564[clinic start generated code]*/
565
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000566static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300567builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
568/*[clinic end generated code: output=2f40bdfa4954b077 input=6325e751a1b29b86]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000569{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000570 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000571}
572
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000573/*[clinic input]
574chr as builtin_chr
575
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300576 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000577 /
578
579Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
580[clinic start generated code]*/
581
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000582static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300583builtin_chr_impl(PyObject *module, int i)
584/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000585{
586 return PyUnicode_FromOrdinal(i);
587}
Guido van Rossum09095f32000-03-10 23:00:52 +0000588
589
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200590static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000591source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000592{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200593 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000595 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000596
Martin Pantereeb896c2015-11-07 02:32:21 +0000597 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (PyUnicode_Check(cmd)) {
599 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200600 str = PyUnicode_AsUTF8AndSize(cmd, &size);
601 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 return NULL;
603 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000604 else if (PyBytes_Check(cmd)) {
605 str = PyBytes_AS_STRING(cmd);
606 size = PyBytes_GET_SIZE(cmd);
607 }
608 else if (PyByteArray_Check(cmd)) {
609 str = PyByteArray_AS_STRING(cmd);
610 size = PyByteArray_GET_SIZE(cmd);
611 }
612 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
613 /* Copy to NUL-terminated buffer. */
614 *cmd_copy = PyBytes_FromStringAndSize(
615 (const char *)view.buf, view.len);
616 PyBuffer_Release(&view);
617 if (*cmd_copy == NULL) {
618 return NULL;
619 }
620 str = PyBytes_AS_STRING(*cmd_copy);
621 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200622 }
623 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyErr_Format(PyExc_TypeError,
625 "%s() arg 1 must be a %s object",
626 funcname, what);
627 return NULL;
628 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200629
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200630 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300631 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000633 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return NULL;
635 }
636 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000637}
638
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000639/*[clinic input]
640compile as builtin_compile
641
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300642 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000643 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300644 mode: str
645 flags: int = 0
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300646 dont_inherit: int(c_default="0") = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300647 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000648
649Compile source into a code object that can be executed by exec() or eval().
650
651The source code may represent a Python module, statement or expression.
652The filename will be used for run-time error messages.
653The mode must be 'exec' to compile a module, 'single' to compile a
654single (interactive) statement, or 'eval' to compile an expression.
655The flags argument, if present, controls which future statements influence
656the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300657The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000658the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300659compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000660in addition to any features explicitly specified.
661[clinic start generated code]*/
662
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000663static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300664builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
665 const char *mode, int flags, int dont_inherit,
666 int optimize)
667/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000668{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000669 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200670 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000671 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 int is_ast;
673 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000675 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000676
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000677 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000678
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000679 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
681 {
682 PyErr_SetString(PyExc_ValueError,
683 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000684 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 }
686 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000687
Georg Brandl8334fd92010-12-04 10:26:46 +0000688 if (optimize < -1 || optimize > 2) {
689 PyErr_SetString(PyExc_ValueError,
690 "compile(): invalid optimize value");
691 goto error;
692 }
693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (!dont_inherit) {
695 PyEval_MergeCompilerFlags(&cf);
696 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000697
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000698 if (strcmp(mode, "exec") == 0)
699 compile_mode = 0;
700 else if (strcmp(mode, "eval") == 0)
701 compile_mode = 1;
702 else if (strcmp(mode, "single") == 0)
703 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 else {
705 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000706 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000707 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000709
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000710 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000712 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000714 if (flags & PyCF_ONLY_AST) {
715 Py_INCREF(source);
716 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 }
718 else {
719 PyArena *arena;
720 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200723 if (arena == NULL)
724 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000725 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (mod == NULL) {
727 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000728 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500730 if (!PyAST_Validate(mod)) {
731 PyArena_Free(arena);
732 goto error;
733 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200734 result = (PyObject*)PyAST_CompileObject(mod, filename,
735 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyArena_Free(arena);
737 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000738 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000740
Martin Panter61d6e4a2015-11-07 02:56:11 +0000741 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000743 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000744
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000745 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000746 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000747 goto finally;
748
749error:
750 result = NULL;
751finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200752 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000753 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000754}
755
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000756/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000757static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000758builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
763 return NULL;
764 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000765}
766
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000767PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000768"dir([object]) -> list of strings\n"
769"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000770"If called without an argument, return the names in the current scope.\n"
771"Else, return an alphabetized list of names comprising (some of) the attributes\n"
772"of the given object, and of attributes reachable from it.\n"
773"If the object supplies a method named __dir__, it will be used; otherwise\n"
774"the default dir() logic is used and returns:\n"
775" for a module object: the module's attributes.\n"
776" for a class object: its attributes, and recursively the attributes\n"
777" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000778" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000779" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000780
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000781/*[clinic input]
782divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000783
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300784 x: object
785 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000786 /
787
Zachary Ware7f227d92016-04-28 14:39:50 -0500788Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000789[clinic start generated code]*/
790
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000791static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300792builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
793/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000794{
795 return PyNumber_Divmod(x, y);
796}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000797
798
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000799/*[clinic input]
800eval as builtin_eval
801
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300802 source: object
803 globals: object = None
804 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000805 /
806
807Evaluate the given source in the context of globals and locals.
808
809The source may be a string representing a Python expression
810or a code object as returned by compile().
811The globals must be a dictionary and locals can be any mapping,
812defaulting to the current globals and locals.
813If only globals is given, locals defaults to it.
814[clinic start generated code]*/
815
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000816static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300817builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400818 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300819/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000820{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000821 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200822 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 if (locals != Py_None && !PyMapping_Check(locals)) {
826 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
827 return NULL;
828 }
829 if (globals != Py_None && !PyDict_Check(globals)) {
830 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
831 "globals must be a real dict; try eval(expr, {}, mapping)"
832 : "globals must be a dict");
833 return NULL;
834 }
835 if (globals == Py_None) {
836 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100837 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100839 if (locals == NULL)
840 return NULL;
841 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
843 else if (locals == Py_None)
844 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 if (globals == NULL || locals == NULL) {
847 PyErr_SetString(PyExc_TypeError,
848 "eval must be given globals and locals "
849 "when called without a frame");
850 return NULL;
851 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000852
Victor Stinnerb44562b2013-11-06 19:03:11 +0100853 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
854 if (_PyDict_SetItemId(globals, &PyId___builtins__,
855 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 return NULL;
857 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000858
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000859 if (PyCode_Check(source)) {
860 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 PyErr_SetString(PyExc_TypeError,
862 "code object passed to eval() may not contain free variables");
863 return NULL;
864 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000865 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000869 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (str == NULL)
871 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 while (*str == ' ' || *str == '\t')
874 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 (void)PyEval_MergeCompilerFlags(&cf);
877 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000878 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000880}
881
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000882/*[clinic input]
883exec as builtin_exec
884
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300885 source: object
886 globals: object = None
887 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000888 /
889
890Execute the given source in the context of globals and locals.
891
892The source may be a string representing one or more Python statements
893or a code object as returned by compile().
894The globals must be a dictionary and locals can be any mapping,
895defaulting to the current globals and locals.
896If only globals is given, locals defaults to it.
897[clinic start generated code]*/
898
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000899static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300900builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400901 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300902/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (globals == Py_None) {
907 globals = PyEval_GetGlobals();
908 if (locals == Py_None) {
909 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100910 if (locals == NULL)
911 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 }
913 if (!globals || !locals) {
914 PyErr_SetString(PyExc_SystemError,
915 "globals and locals cannot be NULL");
916 return NULL;
917 }
918 }
919 else if (locals == Py_None)
920 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000923 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 globals->ob_type->tp_name);
925 return NULL;
926 }
927 if (!PyMapping_Check(locals)) {
928 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000929 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 locals->ob_type->tp_name);
931 return NULL;
932 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100933 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
934 if (_PyDict_SetItemId(globals, &PyId___builtins__,
935 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 return NULL;
937 }
938
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000939 if (PyCode_Check(source)) {
940 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 PyErr_SetString(PyExc_TypeError,
942 "code object passed to exec() may not "
943 "contain free variables");
944 return NULL;
945 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000946 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
948 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000949 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200950 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyCompilerFlags cf;
952 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000953 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000954 "string, bytes or code", &cf,
955 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (str == NULL)
957 return NULL;
958 if (PyEval_MergeCompilerFlags(&cf))
959 v = PyRun_StringFlags(str, Py_file_input, globals,
960 locals, &cf);
961 else
962 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000963 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
965 if (v == NULL)
966 return NULL;
967 Py_DECREF(v);
968 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000969}
970
Georg Brandl7cae87c2006-09-06 06:51:57 +0000971
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000972/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000973static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000974builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 PyObject *v, *result, *dflt = NULL;
977 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
980 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (!PyUnicode_Check(name)) {
983 PyErr_SetString(PyExc_TypeError,
984 "getattr(): attribute name must be string");
985 return NULL;
986 }
987 result = PyObject_GetAttr(v, name);
988 if (result == NULL && dflt != NULL &&
989 PyErr_ExceptionMatches(PyExc_AttributeError))
990 {
991 PyErr_Clear();
992 Py_INCREF(dflt);
993 result = dflt;
994 }
995 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000996}
997
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000998PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000999"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001000\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001001Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1002When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001003exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001004
1005
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001006/*[clinic input]
1007globals as builtin_globals
1008
1009Return the dictionary containing the current scope's global variables.
1010
1011NOTE: Updates to this dictionary *will* affect name lookups in the current
1012global scope and vice-versa.
1013[clinic start generated code]*/
1014
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001015static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001016builtin_globals_impl(PyObject *module)
1017/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 d = PyEval_GetGlobals();
1022 Py_XINCREF(d);
1023 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001024}
1025
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001026
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001027/*[clinic input]
1028hasattr as builtin_hasattr
1029
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001030 obj: object
1031 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001032 /
1033
1034Return whether the object has an attribute with the given name.
1035
1036This is done by calling getattr(obj, name) and catching AttributeError.
1037[clinic start generated code]*/
1038
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001039static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001040builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1041/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001042{
1043 PyObject *v;
1044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 if (!PyUnicode_Check(name)) {
1046 PyErr_SetString(PyExc_TypeError,
1047 "hasattr(): attribute name must be string");
1048 return NULL;
1049 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001050 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001052 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001054 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001056 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 }
1058 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001059 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001060}
1061
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001062
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001063/* AC: gdb's integration with CPython relies on builtin_id having
1064 * the *exact* parameter names of "self" and "v", so we ensure we
1065 * preserve those name rather than using the AC defaults.
1066 */
1067/*[clinic input]
1068id as builtin_id
1069
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001070 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001071 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001072 /
1073
1074Return the identity of an object.
1075
1076This is guaranteed to be unique among simultaneously existing objects.
1077(CPython uses the object's memory address.)
1078[clinic start generated code]*/
1079
Guido van Rossum79f25d91997-04-29 20:08:16 +00001080static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001081builtin_id(PyModuleDef *self, PyObject *v)
1082/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001085}
1086
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001087
Raymond Hettingera6c60372008-03-13 01:26:19 +00001088/* map object ************************************************************/
1089
1090typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyObject_HEAD
1092 PyObject *iters;
1093 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001094} mapobject;
1095
Guido van Rossum79f25d91997-04-29 20:08:16 +00001096static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001097map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyObject *it, *iters, *func;
1100 mapobject *lz;
1101 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1104 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 numargs = PyTuple_Size(args);
1107 if (numargs < 2) {
1108 PyErr_SetString(PyExc_TypeError,
1109 "map() must have at least two arguments.");
1110 return NULL;
1111 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 iters = PyTuple_New(numargs-1);
1114 if (iters == NULL)
1115 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 for (i=1 ; i<numargs ; i++) {
1118 /* Get iterator. */
1119 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1120 if (it == NULL) {
1121 Py_DECREF(iters);
1122 return NULL;
1123 }
1124 PyTuple_SET_ITEM(iters, i-1, it);
1125 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* create mapobject structure */
1128 lz = (mapobject *)type->tp_alloc(type, 0);
1129 if (lz == NULL) {
1130 Py_DECREF(iters);
1131 return NULL;
1132 }
1133 lz->iters = iters;
1134 func = PyTuple_GET_ITEM(args, 0);
1135 Py_INCREF(func);
1136 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001139}
1140
1141static void
1142map_dealloc(mapobject *lz)
1143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 PyObject_GC_UnTrack(lz);
1145 Py_XDECREF(lz->iters);
1146 Py_XDECREF(lz->func);
1147 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001148}
1149
1150static int
1151map_traverse(mapobject *lz, visitproc visit, void *arg)
1152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 Py_VISIT(lz->iters);
1154 Py_VISIT(lz->func);
1155 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001156}
1157
1158static PyObject *
1159map_next(mapobject *lz)
1160{
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001161 PyObject *small_stack[5];
1162 PyObject **stack;
1163 Py_ssize_t niters, nargs, i;
1164 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001165
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001166 niters = PyTuple_GET_SIZE(lz->iters);
1167 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1168 stack = small_stack;
1169 }
1170 else {
1171 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1172 if (stack == NULL) {
1173 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 return NULL;
1175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001177
1178 nargs = 0;
1179 for (i=0; i < niters; i++) {
1180 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1181 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1182 if (val == NULL) {
1183 goto exit;
1184 }
1185 stack[i] = val;
1186 nargs++;
1187 }
1188
1189 result = _PyObject_FastCall(lz->func, stack, nargs);
1190
1191exit:
1192 for (i=0; i < nargs; i++) {
1193 Py_DECREF(stack[i]);
1194 }
1195 if (stack != small_stack) {
1196 PyMem_Free(stack);
1197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001199}
1200
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001201static PyObject *
1202map_reduce(mapobject *lz)
1203{
1204 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1205 PyObject *args = PyTuple_New(numargs+1);
1206 Py_ssize_t i;
1207 if (args == NULL)
1208 return NULL;
1209 Py_INCREF(lz->func);
1210 PyTuple_SET_ITEM(args, 0, lz->func);
1211 for (i = 0; i<numargs; i++){
1212 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1213 Py_INCREF(it);
1214 PyTuple_SET_ITEM(args, i+1, it);
1215 }
1216
1217 return Py_BuildValue("ON", Py_TYPE(lz), args);
1218}
1219
1220static PyMethodDef map_methods[] = {
1221 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1222 {NULL, NULL} /* sentinel */
1223};
1224
1225
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001226PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001227"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001228\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001229Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001231
Raymond Hettingera6c60372008-03-13 01:26:19 +00001232PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1234 "map", /* tp_name */
1235 sizeof(mapobject), /* tp_basicsize */
1236 0, /* tp_itemsize */
1237 /* methods */
1238 (destructor)map_dealloc, /* tp_dealloc */
1239 0, /* tp_print */
1240 0, /* tp_getattr */
1241 0, /* tp_setattr */
1242 0, /* tp_reserved */
1243 0, /* tp_repr */
1244 0, /* tp_as_number */
1245 0, /* tp_as_sequence */
1246 0, /* tp_as_mapping */
1247 0, /* tp_hash */
1248 0, /* tp_call */
1249 0, /* tp_str */
1250 PyObject_GenericGetAttr, /* tp_getattro */
1251 0, /* tp_setattro */
1252 0, /* tp_as_buffer */
1253 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1254 Py_TPFLAGS_BASETYPE, /* tp_flags */
1255 map_doc, /* tp_doc */
1256 (traverseproc)map_traverse, /* tp_traverse */
1257 0, /* tp_clear */
1258 0, /* tp_richcompare */
1259 0, /* tp_weaklistoffset */
1260 PyObject_SelfIter, /* tp_iter */
1261 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001262 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 0, /* tp_members */
1264 0, /* tp_getset */
1265 0, /* tp_base */
1266 0, /* tp_dict */
1267 0, /* tp_descr_get */
1268 0, /* tp_descr_set */
1269 0, /* tp_dictoffset */
1270 0, /* tp_init */
1271 PyType_GenericAlloc, /* tp_alloc */
1272 map_new, /* tp_new */
1273 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001274};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001275
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001276
1277/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001278static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001279builtin_next(PyObject *self, PyObject *args)
1280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 PyObject *it, *res;
1282 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1285 return NULL;
1286 if (!PyIter_Check(it)) {
1287 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001288 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 it->ob_type->tp_name);
1290 return NULL;
1291 }
1292
1293 res = (*it->ob_type->tp_iternext)(it);
1294 if (res != NULL) {
1295 return res;
1296 } else if (def != NULL) {
1297 if (PyErr_Occurred()) {
1298 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1299 return NULL;
1300 PyErr_Clear();
1301 }
1302 Py_INCREF(def);
1303 return def;
1304 } else if (PyErr_Occurred()) {
1305 return NULL;
1306 } else {
1307 PyErr_SetNone(PyExc_StopIteration);
1308 return NULL;
1309 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001310}
1311
1312PyDoc_STRVAR(next_doc,
1313"next(iterator[, default])\n\
1314\n\
1315Return the next item from the iterator. If default is given and the iterator\n\
1316is exhausted, it is returned instead of raising StopIteration.");
1317
1318
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001319/*[clinic input]
1320setattr as builtin_setattr
1321
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001322 obj: object
1323 name: object
1324 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001325 /
1326
1327Sets the named attribute on the given object to the specified value.
1328
1329setattr(x, 'y', v) is equivalent to ``x.y = v''
1330[clinic start generated code]*/
1331
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001332static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001333builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001334 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001335/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001336{
1337 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 return NULL;
1339 Py_INCREF(Py_None);
1340 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001341}
1342
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001343
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001344/*[clinic input]
1345delattr as builtin_delattr
1346
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001347 obj: object
1348 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001349 /
1350
1351Deletes the named attribute from the given object.
1352
1353delattr(x, 'y') is equivalent to ``del x.y''
1354[clinic start generated code]*/
1355
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001356static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001357builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1358/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001359{
1360 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 return NULL;
1362 Py_INCREF(Py_None);
1363 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001364}
1365
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001366
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001367/*[clinic input]
1368hash as builtin_hash
1369
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001370 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001371 /
1372
1373Return the hash value for the given object.
1374
1375Two objects that compare equal must also have the same hash value, but the
1376reverse is not necessarily true.
1377[clinic start generated code]*/
1378
Guido van Rossum79f25d91997-04-29 20:08:16 +00001379static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001380builtin_hash(PyObject *module, PyObject *obj)
1381/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001382{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001383 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001384
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001385 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 if (x == -1)
1387 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001388 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001389}
1390
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001391
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001392/*[clinic input]
1393hex as builtin_hex
1394
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001395 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001396 /
1397
1398Return the hexadecimal representation of an integer.
1399
1400 >>> hex(12648430)
1401 '0xc0ffee'
1402[clinic start generated code]*/
1403
Guido van Rossum79f25d91997-04-29 20:08:16 +00001404static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001405builtin_hex(PyObject *module, PyObject *number)
1406/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001407{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001408 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001409}
1410
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001411
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001412/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001413static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001414builtin_iter(PyObject *self, PyObject *args)
1415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1419 return NULL;
1420 if (w == NULL)
1421 return PyObject_GetIter(v);
1422 if (!PyCallable_Check(v)) {
1423 PyErr_SetString(PyExc_TypeError,
1424 "iter(v, w): v must be callable");
1425 return NULL;
1426 }
1427 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001428}
1429
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001430PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001431"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001432iter(callable, sentinel) -> iterator\n\
1433\n\
1434Get an iterator from an object. In the first form, the argument must\n\
1435supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001436In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001437
1438
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001439/*[clinic input]
1440len as builtin_len
1441
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001442 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001443 /
1444
1445Return the number of items in a container.
1446[clinic start generated code]*/
1447
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001448static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001449builtin_len(PyObject *module, PyObject *obj)
1450/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001453
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001454 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (res < 0 && PyErr_Occurred())
1456 return NULL;
1457 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001458}
1459
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001460
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001461/*[clinic input]
1462locals as builtin_locals
1463
1464Return a dictionary containing the current scope's local variables.
1465
1466NOTE: Whether or not updates to this dictionary will affect name lookups in
1467the local scope and vice-versa is *implementation dependent* and not
1468covered by any backwards compatibility guarantees.
1469[clinic start generated code]*/
1470
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001471static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001472builtin_locals_impl(PyObject *module)
1473/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 d = PyEval_GetLocals();
1478 Py_XINCREF(d);
1479 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001480}
1481
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001482
Guido van Rossum79f25d91997-04-29 20:08:16 +00001483static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001484min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001487 PyObject *emptytuple, *defaultval = NULL;
1488 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001490 const int positional = PyTuple_Size(args) > 1;
1491 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001492
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001493 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001495 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001497
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001498 emptytuple = PyTuple_New(0);
1499 if (emptytuple == NULL)
1500 return NULL;
1501 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1502 &keyfunc, &defaultval);
1503 Py_DECREF(emptytuple);
1504 if (!ret)
1505 return NULL;
1506
1507 if (positional && defaultval != NULL) {
1508 PyErr_Format(PyExc_TypeError,
1509 "Cannot specify a default for %s() with multiple "
1510 "positional arguments", name);
1511 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 it = PyObject_GetIter(v);
1515 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 return NULL;
1517 }
Tim Petersc3074532001-05-03 07:00:32 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 maxitem = NULL; /* the result */
1520 maxval = NULL; /* the value associated with the result */
1521 while (( item = PyIter_Next(it) )) {
1522 /* get the value from the key function */
1523 if (keyfunc != NULL) {
1524 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1525 if (val == NULL)
1526 goto Fail_it_item;
1527 }
1528 /* no key function; the value is the item */
1529 else {
1530 val = item;
1531 Py_INCREF(val);
1532 }
Tim Petersc3074532001-05-03 07:00:32 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 /* maximum value and item are unset; set them */
1535 if (maxval == NULL) {
1536 maxitem = item;
1537 maxval = val;
1538 }
1539 /* maximum value and item are set; update them as necessary */
1540 else {
1541 int cmp = PyObject_RichCompareBool(val, maxval, op);
1542 if (cmp < 0)
1543 goto Fail_it_item_and_val;
1544 else if (cmp > 0) {
1545 Py_DECREF(maxval);
1546 Py_DECREF(maxitem);
1547 maxval = val;
1548 maxitem = item;
1549 }
1550 else {
1551 Py_DECREF(item);
1552 Py_DECREF(val);
1553 }
1554 }
1555 }
1556 if (PyErr_Occurred())
1557 goto Fail_it;
1558 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001560 if (defaultval != NULL) {
1561 Py_INCREF(defaultval);
1562 maxitem = defaultval;
1563 } else {
1564 PyErr_Format(PyExc_ValueError,
1565 "%s() arg is an empty sequence", name);
1566 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 }
1568 else
1569 Py_DECREF(maxval);
1570 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001572
1573Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001575Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001577Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 Py_XDECREF(maxval);
1579 Py_XDECREF(maxitem);
1580 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001582}
1583
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001584/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001585static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001586builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001589}
1590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001591PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001592"min(iterable, *[, default=obj, key=func]) -> value\n\
1593min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001594\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001595With a single iterable argument, return its smallest item. The\n\
1596default keyword-only argument specifies an object to return if\n\
1597the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001598With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001599
1600
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001601/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001602static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001603builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001606}
1607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001608PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001609"max(iterable, *[, default=obj, key=func]) -> value\n\
1610max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001611\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001612With a single iterable argument, return its biggest item. The\n\
1613default keyword-only argument specifies an object to return if\n\
1614the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001615With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001616
1617
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001618/*[clinic input]
1619oct as builtin_oct
1620
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001621 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001622 /
1623
1624Return the octal representation of an integer.
1625
1626 >>> oct(342391)
1627 '0o1234567'
1628[clinic start generated code]*/
1629
Guido van Rossum79f25d91997-04-29 20:08:16 +00001630static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001631builtin_oct(PyObject *module, PyObject *number)
1632/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001633{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001634 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001635}
1636
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001637
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001638/*[clinic input]
1639ord as builtin_ord
1640
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001641 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001642 /
1643
1644Return the Unicode code point for a one-character string.
1645[clinic start generated code]*/
1646
Guido van Rossum79f25d91997-04-29 20:08:16 +00001647static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001648builtin_ord(PyObject *module, PyObject *c)
1649/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 long ord;
1652 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001653
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001654 if (PyBytes_Check(c)) {
1655 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001657 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 return PyLong_FromLong(ord);
1659 }
1660 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001661 else if (PyUnicode_Check(c)) {
1662 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001663 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001664 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001666 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 return PyLong_FromLong(ord);
1668 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001670 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001672 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001674 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 return PyLong_FromLong(ord);
1676 }
1677 }
1678 else {
1679 PyErr_Format(PyExc_TypeError,
1680 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001681 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 return NULL;
1683 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyErr_Format(PyExc_TypeError,
1686 "ord() expected a character, "
1687 "but string of length %zd found",
1688 size);
1689 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001690}
1691
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001692
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001693/*[clinic input]
1694pow as builtin_pow
1695
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001696 x: object
1697 y: object
1698 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001699 /
1700
1701Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1702
1703Some types, such as ints, are able to use a more efficient algorithm when
1704invoked using the three argument form.
1705[clinic start generated code]*/
1706
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001707static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001708builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1709/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001710{
1711 return PyNumber_Power(x, y, z);
1712}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001713
1714
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001715/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001716static PyObject *
1717builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1718{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001719 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001721 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001723
Benjamin Peterson00102562012-01-11 21:00:16 -05001724 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001725 return NULL;
1726 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1727 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 return NULL;
1729 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001730 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001731 if (file == NULL) {
1732 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1733 return NULL;
1734 }
1735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 /* sys.stdout may be None when FILE* stdout isn't connected */
1737 if (file == Py_None)
1738 Py_RETURN_NONE;
1739 }
Guido van Rossum34343512006-11-30 22:13:52 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (sep == Py_None) {
1742 sep = NULL;
1743 }
1744 else if (sep && !PyUnicode_Check(sep)) {
1745 PyErr_Format(PyExc_TypeError,
1746 "sep must be None or a string, not %.200s",
1747 sep->ob_type->tp_name);
1748 return NULL;
1749 }
1750 if (end == Py_None) {
1751 end = NULL;
1752 }
1753 else if (end && !PyUnicode_Check(end)) {
1754 PyErr_Format(PyExc_TypeError,
1755 "end must be None or a string, not %.200s",
1756 end->ob_type->tp_name);
1757 return NULL;
1758 }
Guido van Rossum34343512006-11-30 22:13:52 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 for (i = 0; i < PyTuple_Size(args); i++) {
1761 if (i > 0) {
1762 if (sep == NULL)
1763 err = PyFile_WriteString(" ", file);
1764 else
1765 err = PyFile_WriteObject(sep, file,
1766 Py_PRINT_RAW);
1767 if (err)
1768 return NULL;
1769 }
1770 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1771 Py_PRINT_RAW);
1772 if (err)
1773 return NULL;
1774 }
Guido van Rossum34343512006-11-30 22:13:52 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (end == NULL)
1777 err = PyFile_WriteString("\n", file);
1778 else
1779 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1780 if (err)
1781 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001782
Georg Brandlbc3b6822012-01-13 19:41:25 +01001783 if (flush != NULL) {
1784 PyObject *tmp;
1785 int do_flush = PyObject_IsTrue(flush);
1786 if (do_flush == -1)
1787 return NULL;
1788 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001789 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001790 if (tmp == NULL)
1791 return NULL;
1792 else
1793 Py_DECREF(tmp);
1794 }
1795 }
1796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001798}
1799
1800PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001801"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001802\n\
1803Prints the values to a stream, or to sys.stdout by default.\n\
1804Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001805file: a file-like object (stream); defaults to the current sys.stdout.\n\
1806sep: string inserted between values, default a space.\n\
1807end: string appended after the last value, default a newline.\n\
1808flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001809
1810
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001811/*[clinic input]
1812input as builtin_input
1813
1814 prompt: object(c_default="NULL") = None
1815 /
1816
1817Read a string from standard input. The trailing newline is stripped.
1818
1819The prompt string, if given, is printed to standard output without a
1820trailing newline before reading input.
1821
1822If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1823On *nix systems, readline is used if available.
1824[clinic start generated code]*/
1825
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001826static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001827builtin_input_impl(PyObject *module, PyObject *prompt)
1828/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001829{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001830 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1831 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1832 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyObject *tmp;
1834 long fd;
1835 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 /* Check that stdin/out/err are intact */
1838 if (fin == NULL || fin == Py_None) {
1839 PyErr_SetString(PyExc_RuntimeError,
1840 "input(): lost sys.stdin");
1841 return NULL;
1842 }
1843 if (fout == NULL || fout == Py_None) {
1844 PyErr_SetString(PyExc_RuntimeError,
1845 "input(): lost sys.stdout");
1846 return NULL;
1847 }
1848 if (ferr == NULL || ferr == Py_None) {
1849 PyErr_SetString(PyExc_RuntimeError,
1850 "input(): lost sys.stderr");
1851 return NULL;
1852 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001855 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 if (tmp == NULL)
1857 PyErr_Clear();
1858 else
1859 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 /* We should only use (GNU) readline if Python's sys.stdin and
1862 sys.stdout are the same as C's stdin and stdout, because we
1863 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001864 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if (tmp == NULL) {
1866 PyErr_Clear();
1867 tty = 0;
1868 }
1869 else {
1870 fd = PyLong_AsLong(tmp);
1871 Py_DECREF(tmp);
1872 if (fd < 0 && PyErr_Occurred())
1873 return NULL;
1874 tty = fd == fileno(stdin) && isatty(fd);
1875 }
1876 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001877 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001878 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001880 tty = 0;
1881 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 else {
1883 fd = PyLong_AsLong(tmp);
1884 Py_DECREF(tmp);
1885 if (fd < 0 && PyErr_Occurred())
1886 return NULL;
1887 tty = fd == fileno(stdout) && isatty(fd);
1888 }
1889 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* If we're interactive, use (GNU) readline */
1892 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001893 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001894 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001895 char *s = NULL;
1896 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1897 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1898 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001900 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001901
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001902 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001903 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001904 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* stdin is a text stream, so it must have an
1906 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001907 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001908 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001909 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1910 if (!stdin_encoding_str || !stdin_errors_str)
1911 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07001912 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (tmp == NULL)
1914 PyErr_Clear();
1915 else
1916 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001917 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001918 /* We have a prompt, encode it as stdout would */
1919 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001921 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001922 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001923 if (!stdout_encoding || !stdout_errors)
1924 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001925 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001926 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1927 if (!stdout_encoding_str || !stdout_errors_str)
1928 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001929 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001930 if (stringpo == NULL)
1931 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001933 stdout_encoding_str, stdout_errors_str);
1934 Py_CLEAR(stdout_encoding);
1935 Py_CLEAR(stdout_errors);
1936 Py_CLEAR(stringpo);
1937 if (po == NULL)
1938 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001939 assert(PyBytes_Check(po));
1940 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 }
1942 else {
1943 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001944 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001946 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001948 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 if (!PyErr_Occurred())
1950 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001951 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001953
1954 len = strlen(s);
1955 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 PyErr_SetNone(PyExc_EOFError);
1957 result = NULL;
1958 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001959 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (len > PY_SSIZE_T_MAX) {
1961 PyErr_SetString(PyExc_OverflowError,
1962 "input: input too long");
1963 result = NULL;
1964 }
1965 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001966 len--; /* strip trailing '\n' */
1967 if (len != 0 && s[len-1] == '\r')
1968 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001969 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1970 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 }
1972 }
1973 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001974 Py_DECREF(stdin_errors);
1975 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 PyMem_FREE(s);
1977 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001978 _readline_errors:
1979 Py_XDECREF(stdin_encoding);
1980 Py_XDECREF(stdout_encoding);
1981 Py_XDECREF(stdin_errors);
1982 Py_XDECREF(stdout_errors);
1983 Py_XDECREF(po);
1984 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001988 if (prompt != NULL) {
1989 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 return NULL;
1991 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001992 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 if (tmp == NULL)
1994 PyErr_Clear();
1995 else
1996 Py_DECREF(tmp);
1997 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001998}
1999
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002000
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002001/*[clinic input]
2002repr as builtin_repr
2003
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002004 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002005 /
2006
2007Return the canonical string representation of the object.
2008
2009For many object types, including most builtins, eval(repr(obj)) == obj.
2010[clinic start generated code]*/
2011
Guido van Rossum79f25d91997-04-29 20:08:16 +00002012static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002013builtin_repr(PyObject *module, PyObject *obj)
2014/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002015{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002016 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002017}
2018
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002019
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002020/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2021 * or a semantic change to accept None for "ndigits"
2022 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002023static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002024builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyObject *ndigits = NULL;
2027 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002028 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2031 kwlist, &number, &ndigits))
2032 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if (Py_TYPE(number)->tp_dict == NULL) {
2035 if (PyType_Ready(Py_TYPE(number)) < 0)
2036 return NULL;
2037 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002038
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002039 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002041 if (!PyErr_Occurred())
2042 PyErr_Format(PyExc_TypeError,
2043 "type %.100s doesn't define __round__ method",
2044 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 return NULL;
2046 }
Alex Martelliae211f92007-08-22 23:21:33 +00002047
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002048 if (ndigits == NULL || ndigits == Py_None)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002049 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002051 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2052 Py_DECREF(round);
2053 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002054}
2055
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002056PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002057"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002058\n\
2059Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002060This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002061same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002062
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002063
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002064/*AC: we need to keep the kwds dict intact to easily call into the
2065 * list.sort method, which isn't currently supported in AC. So we just use
2066 * the initially generated signature with a custom implementation.
2067 */
2068/* [disabled clinic input]
2069sorted as builtin_sorted
2070
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002071 iterable as seq: object
2072 key as keyfunc: object = None
2073 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002074
2075Return a new list containing all items from the iterable in ascending order.
2076
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002077A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002078reverse flag can be set to request the result in descending order.
2079[end disabled clinic input]*/
2080
2081PyDoc_STRVAR(builtin_sorted__doc__,
2082"sorted($module, iterable, key=None, reverse=False)\n"
2083"--\n"
2084"\n"
2085"Return a new list containing all items from the iterable in ascending order.\n"
2086"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002087"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002088"reverse flag can be set to request the result in descending order.");
2089
2090#define BUILTIN_SORTED_METHODDEF \
2091 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
2092
Raymond Hettinger64958a12003-12-17 20:43:33 +00002093static PyObject *
2094builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2095{
Victor Stinner2990fa12016-08-22 23:21:55 +02002096 PyObject *newlist, *v, *seq, *keyfunc=NULL, **newargs;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 PyObject *callable;
2098 static char *kwlist[] = {"iterable", "key", "reverse", 0};
2099 int reverse;
Victor Stinner74319ae2016-08-25 00:04:09 +02002100 Py_ssize_t nargs;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* args 1-3 should match listsort in Objects/listobject.c */
2103 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
2104 kwlist, &seq, &keyfunc, &reverse))
2105 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 newlist = PySequence_List(seq);
2108 if (newlist == NULL)
2109 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002110
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002111 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (callable == NULL) {
2113 Py_DECREF(newlist);
2114 return NULL;
2115 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002116
Victor Stinner2990fa12016-08-22 23:21:55 +02002117 newargs = &PyTuple_GET_ITEM(args, 1);
2118 nargs = PyTuple_GET_SIZE(args) - 1;
2119 v = _PyObject_FastCallDict(callable, newargs, nargs, kwds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 Py_DECREF(callable);
2121 if (v == NULL) {
2122 Py_DECREF(newlist);
2123 return NULL;
2124 }
2125 Py_DECREF(v);
2126 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002127}
2128
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002129
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002130/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002131static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002132builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 PyObject *v = NULL;
2135 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2138 return NULL;
2139 if (v == NULL) {
2140 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002141 if (d == NULL)
2142 return NULL;
2143 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 }
2145 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002146 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 if (d == NULL) {
2148 PyErr_SetString(PyExc_TypeError,
2149 "vars() argument must have __dict__ attribute");
2150 return NULL;
2151 }
2152 }
2153 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002154}
2155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002156PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002157"vars([object]) -> dictionary\n\
2158\n\
2159Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002160With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002161
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002162
2163/*[clinic input]
2164sum as builtin_sum
2165
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002166 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002167 start: object(c_default="NULL") = 0
2168 /
2169
2170Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2171
2172When the iterable is empty, return the start value.
2173This function is intended specifically for use with numeric values and may
2174reject non-numeric types.
2175[clinic start generated code]*/
2176
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002177static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002178builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2179/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002180{
2181 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002183
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002184 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (iter == NULL)
2186 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 if (result == NULL) {
2189 result = PyLong_FromLong(0);
2190 if (result == NULL) {
2191 Py_DECREF(iter);
2192 return NULL;
2193 }
2194 } else {
2195 /* reject string values for 'start' parameter */
2196 if (PyUnicode_Check(result)) {
2197 PyErr_SetString(PyExc_TypeError,
2198 "sum() can't sum strings [use ''.join(seq) instead]");
2199 Py_DECREF(iter);
2200 return NULL;
2201 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002202 if (PyBytes_Check(result)) {
2203 PyErr_SetString(PyExc_TypeError,
2204 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002205 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002206 return NULL;
2207 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 if (PyByteArray_Check(result)) {
2209 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002210 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 Py_DECREF(iter);
2212 return NULL;
2213 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 Py_INCREF(result);
2215 }
Alex Martellia70b1912003-04-22 08:12:33 +00002216
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002217#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2219 Assumes all inputs are the same type. If the assumption fails, default
2220 to the more general routine.
2221 */
2222 if (PyLong_CheckExact(result)) {
2223 int overflow;
2224 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2225 /* If this already overflowed, don't even enter the loop. */
2226 if (overflow == 0) {
2227 Py_DECREF(result);
2228 result = NULL;
2229 }
2230 while(result == NULL) {
2231 item = PyIter_Next(iter);
2232 if (item == NULL) {
2233 Py_DECREF(iter);
2234 if (PyErr_Occurred())
2235 return NULL;
2236 return PyLong_FromLong(i_result);
2237 }
2238 if (PyLong_CheckExact(item)) {
2239 long b = PyLong_AsLongAndOverflow(item, &overflow);
2240 long x = i_result + b;
2241 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2242 i_result = x;
2243 Py_DECREF(item);
2244 continue;
2245 }
2246 }
2247 /* Either overflowed or is not an int. Restore real objects and process normally */
2248 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002249 if (result == NULL) {
2250 Py_DECREF(item);
2251 Py_DECREF(iter);
2252 return NULL;
2253 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 temp = PyNumber_Add(result, item);
2255 Py_DECREF(result);
2256 Py_DECREF(item);
2257 result = temp;
2258 if (result == NULL) {
2259 Py_DECREF(iter);
2260 return NULL;
2261 }
2262 }
2263 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (PyFloat_CheckExact(result)) {
2266 double f_result = PyFloat_AS_DOUBLE(result);
2267 Py_DECREF(result);
2268 result = NULL;
2269 while(result == NULL) {
2270 item = PyIter_Next(iter);
2271 if (item == NULL) {
2272 Py_DECREF(iter);
2273 if (PyErr_Occurred())
2274 return NULL;
2275 return PyFloat_FromDouble(f_result);
2276 }
2277 if (PyFloat_CheckExact(item)) {
2278 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2279 f_result += PyFloat_AS_DOUBLE(item);
2280 PyFPE_END_PROTECT(f_result)
2281 Py_DECREF(item);
2282 continue;
2283 }
2284 if (PyLong_CheckExact(item)) {
2285 long value;
2286 int overflow;
2287 value = PyLong_AsLongAndOverflow(item, &overflow);
2288 if (!overflow) {
2289 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2290 f_result += (double)value;
2291 PyFPE_END_PROTECT(f_result)
2292 Py_DECREF(item);
2293 continue;
2294 }
2295 }
2296 result = PyFloat_FromDouble(f_result);
2297 temp = PyNumber_Add(result, item);
2298 Py_DECREF(result);
2299 Py_DECREF(item);
2300 result = temp;
2301 if (result == NULL) {
2302 Py_DECREF(iter);
2303 return NULL;
2304 }
2305 }
2306 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002307#endif
2308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 for(;;) {
2310 item = PyIter_Next(iter);
2311 if (item == NULL) {
2312 /* error, or end-of-sequence */
2313 if (PyErr_Occurred()) {
2314 Py_DECREF(result);
2315 result = NULL;
2316 }
2317 break;
2318 }
2319 /* It's tempting to use PyNumber_InPlaceAdd instead of
2320 PyNumber_Add here, to avoid quadratic running time
2321 when doing 'sum(list_of_lists, [])'. However, this
2322 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 empty = []
2325 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 would change the value of empty. */
2328 temp = PyNumber_Add(result, item);
2329 Py_DECREF(result);
2330 Py_DECREF(item);
2331 result = temp;
2332 if (result == NULL)
2333 break;
2334 }
2335 Py_DECREF(iter);
2336 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002337}
2338
Alex Martellia70b1912003-04-22 08:12:33 +00002339
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002340/*[clinic input]
2341isinstance as builtin_isinstance
2342
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002343 obj: object
2344 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002345 /
2346
2347Return whether an object is an instance of a class or of a subclass thereof.
2348
2349A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2350check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2351or ...`` etc.
2352[clinic start generated code]*/
2353
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002354static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002355builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002356 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002357/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002360
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002361 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 if (retval < 0)
2363 return NULL;
2364 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002365}
2366
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002367
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002368/*[clinic input]
2369issubclass as builtin_issubclass
2370
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002371 cls: object
2372 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002373 /
2374
2375Return whether 'cls' is a derived from another class or is the same class.
2376
2377A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2378check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2379or ...`` etc.
2380[clinic start generated code]*/
2381
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002382static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002383builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002384 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002385/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002388
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002389 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 if (retval < 0)
2391 return NULL;
2392 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002393}
2394
2395
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002396typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 PyObject_HEAD
2398 Py_ssize_t tuplesize;
2399 PyObject *ittuple; /* tuple of iterators */
2400 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002401} zipobject;
2402
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002403static PyObject *
2404zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 zipobject *lz;
2407 Py_ssize_t i;
2408 PyObject *ittuple; /* tuple of iterators */
2409 PyObject *result;
2410 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2413 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 /* args must be a tuple */
2416 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 /* obtain iterators */
2419 ittuple = PyTuple_New(tuplesize);
2420 if (ittuple == NULL)
2421 return NULL;
2422 for (i=0; i < tuplesize; ++i) {
2423 PyObject *item = PyTuple_GET_ITEM(args, i);
2424 PyObject *it = PyObject_GetIter(item);
2425 if (it == NULL) {
2426 if (PyErr_ExceptionMatches(PyExc_TypeError))
2427 PyErr_Format(PyExc_TypeError,
2428 "zip argument #%zd must support iteration",
2429 i+1);
2430 Py_DECREF(ittuple);
2431 return NULL;
2432 }
2433 PyTuple_SET_ITEM(ittuple, i, it);
2434 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 /* create a result holder */
2437 result = PyTuple_New(tuplesize);
2438 if (result == NULL) {
2439 Py_DECREF(ittuple);
2440 return NULL;
2441 }
2442 for (i=0 ; i < tuplesize ; i++) {
2443 Py_INCREF(Py_None);
2444 PyTuple_SET_ITEM(result, i, Py_None);
2445 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* create zipobject structure */
2448 lz = (zipobject *)type->tp_alloc(type, 0);
2449 if (lz == NULL) {
2450 Py_DECREF(ittuple);
2451 Py_DECREF(result);
2452 return NULL;
2453 }
2454 lz->ittuple = ittuple;
2455 lz->tuplesize = tuplesize;
2456 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002459}
2460
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002461static void
2462zip_dealloc(zipobject *lz)
2463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 PyObject_GC_UnTrack(lz);
2465 Py_XDECREF(lz->ittuple);
2466 Py_XDECREF(lz->result);
2467 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002468}
2469
2470static int
2471zip_traverse(zipobject *lz, visitproc visit, void *arg)
2472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 Py_VISIT(lz->ittuple);
2474 Py_VISIT(lz->result);
2475 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002476}
2477
2478static PyObject *
2479zip_next(zipobject *lz)
2480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 Py_ssize_t i;
2482 Py_ssize_t tuplesize = lz->tuplesize;
2483 PyObject *result = lz->result;
2484 PyObject *it;
2485 PyObject *item;
2486 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (tuplesize == 0)
2489 return NULL;
2490 if (Py_REFCNT(result) == 1) {
2491 Py_INCREF(result);
2492 for (i=0 ; i < tuplesize ; i++) {
2493 it = PyTuple_GET_ITEM(lz->ittuple, i);
2494 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002495 if (item == NULL) {
2496 Py_DECREF(result);
2497 return NULL;
2498 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 olditem = PyTuple_GET_ITEM(result, i);
2500 PyTuple_SET_ITEM(result, i, item);
2501 Py_DECREF(olditem);
2502 }
2503 } else {
2504 result = PyTuple_New(tuplesize);
2505 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002506 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 for (i=0 ; i < tuplesize ; i++) {
2508 it = PyTuple_GET_ITEM(lz->ittuple, i);
2509 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002510 if (item == NULL) {
2511 Py_DECREF(result);
2512 return NULL;
2513 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 PyTuple_SET_ITEM(result, i, item);
2515 }
2516 }
2517 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002518}
Barry Warsawbd599b52000-08-03 15:45:29 +00002519
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002520static PyObject *
2521zip_reduce(zipobject *lz)
2522{
2523 /* Just recreate the zip with the internal iterator tuple */
2524 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2525}
2526
2527static PyMethodDef zip_methods[] = {
2528 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2529 {NULL, NULL} /* sentinel */
2530};
2531
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002532PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002533"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002534\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002535Return a zip object whose .__next__() method returns a tuple where\n\
2536the i-th element comes from the i-th iterable argument. The .__next__()\n\
2537method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002538is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002539
2540PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2542 "zip", /* tp_name */
2543 sizeof(zipobject), /* tp_basicsize */
2544 0, /* tp_itemsize */
2545 /* methods */
2546 (destructor)zip_dealloc, /* tp_dealloc */
2547 0, /* tp_print */
2548 0, /* tp_getattr */
2549 0, /* tp_setattr */
2550 0, /* tp_reserved */
2551 0, /* tp_repr */
2552 0, /* tp_as_number */
2553 0, /* tp_as_sequence */
2554 0, /* tp_as_mapping */
2555 0, /* tp_hash */
2556 0, /* tp_call */
2557 0, /* tp_str */
2558 PyObject_GenericGetAttr, /* tp_getattro */
2559 0, /* tp_setattro */
2560 0, /* tp_as_buffer */
2561 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2562 Py_TPFLAGS_BASETYPE, /* tp_flags */
2563 zip_doc, /* tp_doc */
2564 (traverseproc)zip_traverse, /* tp_traverse */
2565 0, /* tp_clear */
2566 0, /* tp_richcompare */
2567 0, /* tp_weaklistoffset */
2568 PyObject_SelfIter, /* tp_iter */
2569 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002570 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 0, /* tp_members */
2572 0, /* tp_getset */
2573 0, /* tp_base */
2574 0, /* tp_dict */
2575 0, /* tp_descr_get */
2576 0, /* tp_descr_set */
2577 0, /* tp_dictoffset */
2578 0, /* tp_init */
2579 PyType_GenericAlloc, /* tp_alloc */
2580 zip_new, /* tp_new */
2581 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002582};
Barry Warsawbd599b52000-08-03 15:45:29 +00002583
2584
Guido van Rossum79f25d91997-04-29 20:08:16 +00002585static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 {"__build_class__", (PyCFunction)builtin___build_class__,
2587 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2588 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002589 BUILTIN_ABS_METHODDEF
2590 BUILTIN_ALL_METHODDEF
2591 BUILTIN_ANY_METHODDEF
2592 BUILTIN_ASCII_METHODDEF
2593 BUILTIN_BIN_METHODDEF
2594 BUILTIN_CALLABLE_METHODDEF
2595 BUILTIN_CHR_METHODDEF
2596 BUILTIN_COMPILE_METHODDEF
2597 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002599 BUILTIN_DIVMOD_METHODDEF
2600 BUILTIN_EVAL_METHODDEF
2601 BUILTIN_EXEC_METHODDEF
2602 BUILTIN_FORMAT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002604 BUILTIN_GLOBALS_METHODDEF
2605 BUILTIN_HASATTR_METHODDEF
2606 BUILTIN_HASH_METHODDEF
2607 BUILTIN_HEX_METHODDEF
2608 BUILTIN_ID_METHODDEF
2609 BUILTIN_INPUT_METHODDEF
2610 BUILTIN_ISINSTANCE_METHODDEF
2611 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002613 BUILTIN_LEN_METHODDEF
2614 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2616 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2617 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002618 BUILTIN_OCT_METHODDEF
2619 BUILTIN_ORD_METHODDEF
2620 BUILTIN_POW_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002622 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002624 BUILTIN_SETATTR_METHODDEF
2625 BUILTIN_SORTED_METHODDEF
2626 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2628 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002629};
2630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002631PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002632"Built-in functions, exceptions, and other objects.\n\
2633\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002634Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002635
Martin v. Löwis1a214512008-06-11 05:26:20 +00002636static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 PyModuleDef_HEAD_INIT,
2638 "builtins",
2639 builtin_doc,
2640 -1, /* multiple "initialization" just copies the module dict. */
2641 builtin_methods,
2642 NULL,
2643 NULL,
2644 NULL,
2645 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002646};
2647
2648
Guido van Rossum25ce5661997-08-02 03:10:38 +00002649PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002650_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002653
2654 if (PyType_Ready(&PyFilter_Type) < 0 ||
2655 PyType_Ready(&PyMap_Type) < 0 ||
2656 PyType_Ready(&PyZip_Type) < 0)
2657 return NULL;
2658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 mod = PyModule_Create(&builtinsmodule);
2660 if (mod == NULL)
2661 return NULL;
2662 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002663
Tim Peters7571a0f2003-03-23 17:52:28 +00002664#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 /* "builtins" exposes a number of statically allocated objects
2666 * that, before this code was added in 2.3, never showed up in
2667 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2668 * result, programs leaking references to None and False (etc)
2669 * couldn't be diagnosed by examining sys.getobjects(0).
2670 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002671#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2672#else
2673#define ADD_TO_ALL(OBJECT) (void)0
2674#endif
2675
Tim Peters4b7625e2001-09-13 21:37:17 +00002676#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2678 return NULL; \
2679 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 SETBUILTIN("None", Py_None);
2682 SETBUILTIN("Ellipsis", Py_Ellipsis);
2683 SETBUILTIN("NotImplemented", Py_NotImplemented);
2684 SETBUILTIN("False", Py_False);
2685 SETBUILTIN("True", Py_True);
2686 SETBUILTIN("bool", &PyBool_Type);
2687 SETBUILTIN("memoryview", &PyMemoryView_Type);
2688 SETBUILTIN("bytearray", &PyByteArray_Type);
2689 SETBUILTIN("bytes", &PyBytes_Type);
2690 SETBUILTIN("classmethod", &PyClassMethod_Type);
2691 SETBUILTIN("complex", &PyComplex_Type);
2692 SETBUILTIN("dict", &PyDict_Type);
2693 SETBUILTIN("enumerate", &PyEnum_Type);
2694 SETBUILTIN("filter", &PyFilter_Type);
2695 SETBUILTIN("float", &PyFloat_Type);
2696 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2697 SETBUILTIN("property", &PyProperty_Type);
2698 SETBUILTIN("int", &PyLong_Type);
2699 SETBUILTIN("list", &PyList_Type);
2700 SETBUILTIN("map", &PyMap_Type);
2701 SETBUILTIN("object", &PyBaseObject_Type);
2702 SETBUILTIN("range", &PyRange_Type);
2703 SETBUILTIN("reversed", &PyReversed_Type);
2704 SETBUILTIN("set", &PySet_Type);
2705 SETBUILTIN("slice", &PySlice_Type);
2706 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2707 SETBUILTIN("str", &PyUnicode_Type);
2708 SETBUILTIN("super", &PySuper_Type);
2709 SETBUILTIN("tuple", &PyTuple_Type);
2710 SETBUILTIN("type", &PyType_Type);
2711 SETBUILTIN("zip", &PyZip_Type);
2712 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2713 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002714 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 return NULL;
2716 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002717 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002720#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002721#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002722}