1 /* Built-in functions */
2
3 #include "Python.h"
4 #include "Python-ast.h"
5
6 #include "node.h"
7 #include "code.h"
8 #include "eval.h"
9
10 #include <ctype.h>
11 #include <float.h> /* for DBL_MANT_DIG and friends */
12
13 #ifdef RISCOS
14 #include "unixstuff.h"
15 #endif
16
17 /* The default encoding used by the platform file system APIs
18 Can remain NULL for all platforms that don't have such a concept
19 */
20 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
21 const char *Py_FileSystemDefaultEncoding = "mbcs";
22 #elif defined(__APPLE__)
23 const char *Py_FileSystemDefaultEncoding = "utf-8";
24 #else
25 const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
26 #endif
27
28 /* Forward */
29 static PyObject *filterstring(PyObject *, PyObject *);
30 #ifdef Py_USING_UNICODE
31 static PyObject *filterunicode(PyObject *, PyObject *);
32 #endif
33 static PyObject *filtertuple (PyObject *, PyObject *);
34
35 static PyObject *
builtin___import__(PyObject * self,PyObject * args,PyObject * kwds)36 builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
37 {
38 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
39 "level", 0};
40 char *name;
41 PyObject *globals = NULL;
42 PyObject *locals = NULL;
43 PyObject *fromlist = NULL;
44 int level = -1;
45
46 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
47 kwlist, &name, &globals, &locals, &fromlist, &level))
48 return NULL;
49 return PyImport_ImportModuleLevel(name, globals, locals,
50 fromlist, level);
51 }
52
53 PyDoc_STRVAR(import_doc,
54 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
55 \n\
56 Import a module. Because this function is meant for use by the Python\n\
57 interpreter and not for general use, it is better to use\n\
58 importlib.import_module() to programmatically import a module.\n\
59 \n\
60 The globals argument is only used to determine the context;\n\
61 they are not modified. The locals argument is unused. The fromlist\n\
62 should be a list of names to emulate ``from name import ...'', or an\n\
63 empty list to emulate ``import name''.\n\
64 When importing a module from a package, note that __import__('A.B', ...)\n\
65 returns package A when fromlist is empty, but its submodule B when\n\
66 fromlist is not empty. The level argument is used to determine whether to\n\
67 perform absolute or relative imports: 0 is absolute, while a positive number\n\
68 is the number of parent directories to search relative to the current module.");
69
70
71 static PyObject *
builtin_abs(PyObject * self,PyObject * v)72 builtin_abs(PyObject *self, PyObject *v)
73 {
74 return PyNumber_Absolute(v);
75 }
76
77 PyDoc_STRVAR(abs_doc,
78 "abs(number) -> number\n\
79 \n\
80 Return the absolute value of the argument.");
81
82 static PyObject *
builtin_all(PyObject * self,PyObject * v)83 builtin_all(PyObject *self, PyObject *v)
84 {
85 PyObject *it, *item;
86 PyObject *(*iternext)(PyObject *);
87 int cmp;
88
89 it = PyObject_GetIter(v);
90 if (it == NULL)
91 return NULL;
92 iternext = *Py_TYPE(it)->tp_iternext;
93
94 for (;;) {
95 item = iternext(it);
96 if (item == NULL)
97 break;
98 cmp = PyObject_IsTrue(item);
99 Py_DECREF(item);
100 if (cmp < 0) {
101 Py_DECREF(it);
102 return NULL;
103 }
104 if (cmp == 0) {
105 Py_DECREF(it);
106 Py_RETURN_FALSE;
107 }
108 }
109 Py_DECREF(it);
110 if (PyErr_Occurred()) {
111 if (PyErr_ExceptionMatches(PyExc_StopIteration))
112 PyErr_Clear();
113 else
114 return NULL;
115 }
116 Py_RETURN_TRUE;
117 }
118
119 PyDoc_STRVAR(all_doc,
120 "all(iterable) -> bool\n\
121 \n\
122 Return True if bool(x) is True for all values x in the iterable.\n\
123 If the iterable is empty, return True.");
124
125 static PyObject *
builtin_any(PyObject * self,PyObject * v)126 builtin_any(PyObject *self, PyObject *v)
127 {
128 PyObject *it, *item;
129 PyObject *(*iternext)(PyObject *);
130 int cmp;
131
132 it = PyObject_GetIter(v);
133 if (it == NULL)
134 return NULL;
135 iternext = *Py_TYPE(it)->tp_iternext;
136
137 for (;;) {
138 item = iternext(it);
139 if (item == NULL)
140 break;
141 cmp = PyObject_IsTrue(item);
142 Py_DECREF(item);
143 if (cmp < 0) {
144 Py_DECREF(it);
145 return NULL;
146 }
147 if (cmp == 1) {
148 Py_DECREF(it);
149 Py_RETURN_TRUE;
150 }
151 }
152 Py_DECREF(it);
153 if (PyErr_Occurred()) {
154 if (PyErr_ExceptionMatches(PyExc_StopIteration))
155 PyErr_Clear();
156 else
157 return NULL;
158 }
159 Py_RETURN_FALSE;
160 }
161
162 PyDoc_STRVAR(any_doc,
163 "any(iterable) -> bool\n\
164 \n\
165 Return True if bool(x) is True for any x in the iterable.\n\
166 If the iterable is empty, return False.");
167
168 static PyObject *
builtin_apply(PyObject * self,PyObject * args)169 builtin_apply(PyObject *self, PyObject *args)
170 {
171 PyObject *func, *alist = NULL, *kwdict = NULL;
172 PyObject *t = NULL, *retval = NULL;
173
174 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
175 "use func(*args, **kwargs)", 1) < 0)
176 return NULL;
177
178 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
179 return NULL;
180 if (alist != NULL) {
181 if (!PyTuple_Check(alist)) {
182 if (!PySequence_Check(alist)) {
183 PyErr_Format(PyExc_TypeError,
184 "apply() arg 2 expected sequence, found %s",
185 alist->ob_type->tp_name);
186 return NULL;
187 }
188 t = PySequence_Tuple(alist);
189 if (t == NULL)
190 return NULL;
191 alist = t;
192 }
193 }
194 if (kwdict != NULL && !PyDict_Check(kwdict)) {
195 PyErr_Format(PyExc_TypeError,
196 "apply() arg 3 expected dictionary, found %s",
197 kwdict->ob_type->tp_name);
198 goto finally;
199 }
200 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
201 finally:
202 Py_XDECREF(t);
203 return retval;
204 }
205
206 PyDoc_STRVAR(apply_doc,
207 "apply(object[, args[, kwargs]]) -> value\n\
208 \n\
209 Call a callable object with positional arguments taken from the tuple args,\n\
210 and keyword arguments taken from the optional dictionary kwargs.\n\
211 Note that classes are callable, as are instances with a __call__() method.\n\
212 \n\
213 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
214 function(*args, **keywords).");
215
216
217 static PyObject *
builtin_bin(PyObject * self,PyObject * v)218 builtin_bin(PyObject *self, PyObject *v)
219 {
220 return PyNumber_ToBase(v, 2);
221 }
222
223 PyDoc_STRVAR(bin_doc,
224 "bin(number) -> string\n\
225 \n\
226 Return the binary representation of an integer or long integer.");
227
228
229 static PyObject *
builtin_callable(PyObject * self,PyObject * v)230 builtin_callable(PyObject *self, PyObject *v)
231 {
232 return PyBool_FromLong((long)PyCallable_Check(v));
233 }
234
235 PyDoc_STRVAR(callable_doc,
236 "callable(object) -> bool\n\
237 \n\
238 Return whether the object is callable (i.e., some kind of function).\n\
239 Note that classes are callable, as are instances with a __call__() method.");
240
241
242 static PyObject *
builtin_filter(PyObject * self,PyObject * args)243 builtin_filter(PyObject *self, PyObject *args)
244 {
245 PyObject *func, *seq, *result, *it, *arg;
246 Py_ssize_t len; /* guess for result list size */
247 register Py_ssize_t j;
248
249 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
250 return NULL;
251
252 /* Strings and tuples return a result of the same type. */
253 if (PyString_Check(seq))
254 return filterstring(func, seq);
255 #ifdef Py_USING_UNICODE
256 if (PyUnicode_Check(seq))
257 return filterunicode(func, seq);
258 #endif
259 if (PyTuple_Check(seq))
260 return filtertuple(func, seq);
261
262 /* Pre-allocate argument list tuple. */
263 arg = PyTuple_New(1);
264 if (arg == NULL)
265 return NULL;
266
267 /* Get iterator. */
268 it = PyObject_GetIter(seq);
269 if (it == NULL)
270 goto Fail_arg;
271
272 /* Guess a result list size. */
273 len = _PyObject_LengthHint(seq, 8);
274 if (len == -1)
275 goto Fail_it;
276
277 /* Get a result list. */
278 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
279 /* Eww - can modify the list in-place. */
280 Py_INCREF(seq);
281 result = seq;
282 }
283 else {
284 result = PyList_New(len);
285 if (result == NULL)
286 goto Fail_it;
287 }
288
289 /* Build the result list. */
290 j = 0;
291 for (;;) {
292 PyObject *item;
293 int ok;
294
295 item = PyIter_Next(it);
296 if (item == NULL) {
297 if (PyErr_Occurred())
298 goto Fail_result_it;
299 break;
300 }
301
302 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
303 ok = PyObject_IsTrue(item);
304 }
305 else {
306 PyObject *good;
307 PyTuple_SET_ITEM(arg, 0, item);
308 good = PyObject_Call(func, arg, NULL);
309 PyTuple_SET_ITEM(arg, 0, NULL);
310 if (good == NULL) {
311 Py_DECREF(item);
312 goto Fail_result_it;
313 }
314 ok = PyObject_IsTrue(good);
315 Py_DECREF(good);
316 }
317 if (ok > 0) {
318 if (j < len)
319 PyList_SET_ITEM(result, j, item);
320 else {
321 int status = PyList_Append(result, item);
322 Py_DECREF(item);
323 if (status < 0)
324 goto Fail_result_it;
325 }
326 ++j;
327 }
328 else {
329 Py_DECREF(item);
330 if (ok < 0)
331 goto Fail_result_it;
332 }
333 }
334
335
336 /* Cut back result list if len is too big. */
337 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
338 goto Fail_result_it;
339
340 Py_DECREF(it);
341 Py_DECREF(arg);
342 return result;
343
344 Fail_result_it:
345 Py_DECREF(result);
346 Fail_it:
347 Py_DECREF(it);
348 Fail_arg:
349 Py_DECREF(arg);
350 return NULL;
351 }
352
353 PyDoc_STRVAR(filter_doc,
354 "filter(function or None, iterable) -> list, string or tuple\n\
355 \n\
356 Return a sequence yielding those items of iterable for which function(item)\n\
357 is true. If function is None, return the items that are true.\n\
358 If iterable is a string or a tuple, the result also has that type; otherwise\n\
359 it is always a list.");
360
361 static PyObject *
builtin_format(PyObject * self,PyObject * args)362 builtin_format(PyObject *self, PyObject *args)
363 {
364 PyObject *value;
365 PyObject *format_spec = NULL;
366
367 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
368 return NULL;
369
370 return PyObject_Format(value, format_spec);
371 }
372
373 PyDoc_STRVAR(format_doc,
374 "format(value[, format_spec]) -> string\n\
375 \n\
376 Returns value.__format__(format_spec)\n\
377 format_spec defaults to the empty string.\n\
378 See the Format Specification Mini-Language section of help('FORMATTING') for\n\
379 details.");
380
381 static PyObject *
builtin_chr(PyObject * self,PyObject * args)382 builtin_chr(PyObject *self, PyObject *args)
383 {
384 long x;
385 char s[1];
386
387 if (!PyArg_ParseTuple(args, "l:chr", &x))
388 return NULL;
389 if (x < 0 || x >= 256) {
390 PyErr_SetString(PyExc_ValueError,
391 "chr() arg not in range(256)");
392 return NULL;
393 }
394 s[0] = (char)x;
395 return PyString_FromStringAndSize(s, 1);
396 }
397
398 PyDoc_STRVAR(chr_doc,
399 "chr(i) -> character\n\
400 \n\
401 Return a string of one character with ordinal i; 0 <= i < 256.");
402
403
404 #ifdef Py_USING_UNICODE
405 static PyObject *
builtin_unichr(PyObject * self,PyObject * args)406 builtin_unichr(PyObject *self, PyObject *args)
407 {
408 int x;
409
410 if (!PyArg_ParseTuple(args, "i:unichr", &x))
411 return NULL;
412
413 return PyUnicode_FromOrdinal(x);
414 }
415
416 PyDoc_STRVAR(unichr_doc,
417 "unichr(i) -> Unicode character\n\
418 \n\
419 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
420 #endif
421
422
423 static PyObject *
builtin_cmp(PyObject * self,PyObject * args)424 builtin_cmp(PyObject *self, PyObject *args)
425 {
426 PyObject *a, *b;
427 int c;
428
429 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
430 return NULL;
431 if (PyObject_Cmp(a, b, &c) < 0)
432 return NULL;
433 return PyInt_FromLong((long)c);
434 }
435
436 PyDoc_STRVAR(cmp_doc,
437 "cmp(x, y) -> integer\n\
438 \n\
439 Return negative if x<y, zero if x==y, positive if x>y.");
440
441
442 static PyObject *
builtin_coerce(PyObject * self,PyObject * args)443 builtin_coerce(PyObject *self, PyObject *args)
444 {
445 PyObject *v, *w;
446 PyObject *res;
447
448 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
449 return NULL;
450
451 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
452 return NULL;
453 if (PyNumber_Coerce(&v, &w) < 0)
454 return NULL;
455 res = PyTuple_Pack(2, v, w);
456 Py_DECREF(v);
457 Py_DECREF(w);
458 return res;
459 }
460
461 PyDoc_STRVAR(coerce_doc,
462 "coerce(x, y) -> (x1, y1)\n\
463 \n\
464 Return a tuple consisting of the two numeric arguments converted to\n\
465 a common type, using the same rules as used by arithmetic operations.\n\
466 If coercion is not possible, raise TypeError.");
467
468 static PyObject *
builtin_compile(PyObject * self,PyObject * args,PyObject * kwds)469 builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
470 {
471 char *str;
472 char *filename;
473 char *startstr;
474 int mode = -1;
475 int dont_inherit = 0;
476 int supplied_flags = 0;
477 int is_ast;
478 PyCompilerFlags cf;
479 PyObject *result = NULL, *cmd, *tmp = NULL;
480 Py_ssize_t length;
481 static char *kwlist[] = {"source", "filename", "mode", "flags",
482 "dont_inherit", NULL};
483 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
484
485 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
486 kwlist, &cmd, &filename, &startstr,
487 &supplied_flags, &dont_inherit))
488 return NULL;
489
490 cf.cf_flags = supplied_flags;
491
492 if (supplied_flags &
493 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
494 {
495 PyErr_SetString(PyExc_ValueError,
496 "compile(): unrecognised flags");
497 return NULL;
498 }
499 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
500
501 if (!dont_inherit) {
502 PyEval_MergeCompilerFlags(&cf);
503 }
504
505 if (strcmp(startstr, "exec") == 0)
506 mode = 0;
507 else if (strcmp(startstr, "eval") == 0)
508 mode = 1;
509 else if (strcmp(startstr, "single") == 0)
510 mode = 2;
511 else {
512 PyErr_SetString(PyExc_ValueError,
513 "compile() arg 3 must be 'exec', 'eval' or 'single'");
514 return NULL;
515 }
516
517 is_ast = PyAST_Check(cmd);
518 if (is_ast == -1)
519 return NULL;
520 if (is_ast) {
521 if (supplied_flags & PyCF_ONLY_AST) {
522 Py_INCREF(cmd);
523 result = cmd;
524 }
525 else {
526 PyArena *arena;
527 mod_ty mod;
528
529 arena = PyArena_New();
530 if (arena == NULL)
531 return NULL;
532 mod = PyAST_obj2mod(cmd, arena, mode);
533 if (mod == NULL) {
534 PyArena_Free(arena);
535 return NULL;
536 }
537 result = (PyObject*)PyAST_Compile(mod, filename,
538 &cf, arena);
539 PyArena_Free(arena);
540 }
541 return result;
542 }
543 if (PyString_Check(cmd)) {
544 str = PyString_AS_STRING(cmd);
545 length = PyString_GET_SIZE(cmd);
546 }
547 #ifdef Py_USING_UNICODE
548 else if (PyUnicode_Check(cmd)) {
549 tmp = PyUnicode_AsUTF8String(cmd);
550 if (tmp == NULL)
551 return NULL;
552 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
553 str = PyString_AS_STRING(tmp);
554 length = PyString_GET_SIZE(tmp);
555 }
556 #endif
557 else if (!PyObject_AsReadBuffer(cmd, (const void **)&str, &length)) {
558 /* Copy to NUL-terminated buffer. */
559 tmp = PyString_FromStringAndSize(str, length);
560 if (tmp == NULL)
561 return NULL;
562 str = PyString_AS_STRING(tmp);
563 length = PyString_GET_SIZE(tmp);
564 }
565 else
566 goto cleanup;
567 if ((size_t)length != strlen(str)) {
568 PyErr_SetString(PyExc_TypeError,
569 "compile() expected string without null bytes");
570 goto cleanup;
571 }
572 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
573 cleanup:
574 Py_XDECREF(tmp);
575 return result;
576 }
577
578 PyDoc_STRVAR(compile_doc,
579 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
580 \n\
581 Compile the source string (a Python module, statement or expression)\n\
582 into a code object that can be executed by the exec statement or eval().\n\
583 The filename will be used for run-time error messages.\n\
584 The mode must be 'exec' to compile a module, 'single' to compile a\n\
585 single (interactive) statement, or 'eval' to compile an expression.\n\
586 The flags argument, if present, controls which future statements influence\n\
587 the compilation of the code.\n\
588 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
589 the effects of any future statements in effect in the code calling\n\
590 compile; if absent or zero these statements do influence the compilation,\n\
591 in addition to any features explicitly specified.");
592
593 static PyObject *
builtin_dir(PyObject * self,PyObject * args)594 builtin_dir(PyObject *self, PyObject *args)
595 {
596 PyObject *arg = NULL;
597
598 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
599 return NULL;
600 return PyObject_Dir(arg);
601 }
602
603 PyDoc_STRVAR(dir_doc,
604 "dir([object]) -> list of strings\n"
605 "\n"
606 "If called without an argument, return the names in the current scope.\n"
607 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
608 "of the given object, and of attributes reachable from it.\n"
609 "If the object supplies a method named __dir__, it will be used; otherwise\n"
610 "the default dir() logic is used and returns:\n"
611 " for a module object: the module's attributes.\n"
612 " for a class object: its attributes, and recursively the attributes\n"
613 " of its bases.\n"
614 " for any other object: its attributes, its class's attributes, and\n"
615 " recursively the attributes of its class's base classes.");
616
617 static PyObject *
builtin_divmod(PyObject * self,PyObject * args)618 builtin_divmod(PyObject *self, PyObject *args)
619 {
620 PyObject *v, *w;
621
622 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
623 return NULL;
624 return PyNumber_Divmod(v, w);
625 }
626
627 PyDoc_STRVAR(divmod_doc,
628 "divmod(x, y) -> (quotient, remainder)\n\
629 \n\
630 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.");
631
632
633 static PyObject *
builtin_eval(PyObject * self,PyObject * args)634 builtin_eval(PyObject *self, PyObject *args)
635 {
636 PyObject *cmd, *result, *tmp = NULL;
637 PyObject *globals = Py_None, *locals = Py_None;
638 char *str;
639 PyCompilerFlags cf;
640
641 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
642 return NULL;
643 if (locals != Py_None && !PyMapping_Check(locals)) {
644 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
645 return NULL;
646 }
647 if (globals != Py_None && !PyDict_Check(globals)) {
648 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
649 "globals must be a real dict; try eval(expr, {}, mapping)"
650 : "globals must be a dict");
651 return NULL;
652 }
653 if (globals == Py_None) {
654 globals = PyEval_GetGlobals();
655 if (locals == Py_None)
656 locals = PyEval_GetLocals();
657 }
658 else if (locals == Py_None)
659 locals = globals;
660
661 if (globals == NULL || locals == NULL) {
662 PyErr_SetString(PyExc_TypeError,
663 "eval must be given globals and locals "
664 "when called without a frame");
665 return NULL;
666 }
667
668 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
669 if (PyDict_SetItemString(globals, "__builtins__",
670 PyEval_GetBuiltins()) != 0)
671 return NULL;
672 }
673
674 if (PyCode_Check(cmd)) {
675 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
676 PyErr_SetString(PyExc_TypeError,
677 "code object passed to eval() may not contain free variables");
678 return NULL;
679 }
680 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
681 }
682
683 if (!PyString_Check(cmd) &&
684 !PyUnicode_Check(cmd)) {
685 PyErr_SetString(PyExc_TypeError,
686 "eval() arg 1 must be a string or code object");
687 return NULL;
688 }
689 cf.cf_flags = 0;
690
691 #ifdef Py_USING_UNICODE
692 if (PyUnicode_Check(cmd)) {
693 tmp = PyUnicode_AsUTF8String(cmd);
694 if (tmp == NULL)
695 return NULL;
696 cmd = tmp;
697 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
698 }
699 #endif
700 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
701 Py_XDECREF(tmp);
702 return NULL;
703 }
704 while (*str == ' ' || *str == '\t')
705 str++;
706
707 (void)PyEval_MergeCompilerFlags(&cf);
708 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
709 Py_XDECREF(tmp);
710 return result;
711 }
712
713 PyDoc_STRVAR(eval_doc,
714 "eval(source[, globals[, locals]]) -> value\n\
715 \n\
716 Evaluate the source in the context of globals and locals.\n\
717 The source may be a string representing a Python expression\n\
718 or a code object as returned by compile().\n\
719 The globals must be a dictionary and locals can be any mapping,\n\
720 defaulting to the current globals and locals.\n\
721 If only globals is given, locals defaults to it.\n");
722
723
724 static PyObject *
builtin_execfile(PyObject * self,PyObject * args)725 builtin_execfile(PyObject *self, PyObject *args)
726 {
727 char *filename;
728 PyObject *globals = Py_None, *locals = Py_None;
729 PyObject *res;
730 FILE* fp = NULL;
731 PyCompilerFlags cf;
732 int exists;
733
734 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
735 1) < 0)
736 return NULL;
737
738 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
739 &filename,
740 &PyDict_Type, &globals,
741 &locals))
742 return NULL;
743 if (locals != Py_None && !PyMapping_Check(locals)) {
744 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
745 return NULL;
746 }
747 if (globals == Py_None) {
748 globals = PyEval_GetGlobals();
749 if (locals == Py_None)
750 locals = PyEval_GetLocals();
751 }
752 else if (locals == Py_None)
753 locals = globals;
754 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
755 if (PyDict_SetItemString(globals, "__builtins__",
756 PyEval_GetBuiltins()) != 0)
757 return NULL;
758 }
759
760 exists = 0;
761 /* Test for existence or directory. */
762 #if defined(PLAN9)
763 {
764 Dir *d;
765
766 if ((d = dirstat(filename))!=nil) {
767 if(d->mode & DMDIR)
768 werrstr("is a directory");
769 else
770 exists = 1;
771 free(d);
772 }
773 }
774 #elif defined(RISCOS)
775 if (object_exists(filename)) {
776 if (isdir(filename))
777 errno = EISDIR;
778 else
779 exists = 1;
780 }
781 #else /* standard Posix */
782 {
783 struct stat s;
784 if (stat(filename, &s) == 0) {
785 if (S_ISDIR(s.st_mode))
786 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
787 errno = EOS2ERR;
788 # else
789 errno = EISDIR;
790 # endif
791 else
792 exists = 1;
793 }
794 }
795 #endif
796
797 if (exists) {
798 Py_BEGIN_ALLOW_THREADS
799 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
800 Py_END_ALLOW_THREADS
801
802 if (fp == NULL) {
803 exists = 0;
804 }
805 }
806
807 if (!exists) {
808 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
809 return NULL;
810 }
811 cf.cf_flags = 0;
812 if (PyEval_MergeCompilerFlags(&cf))
813 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
814 locals, 1, &cf);
815 else
816 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
817 locals, 1);
818 return res;
819 }
820
821 PyDoc_STRVAR(execfile_doc,
822 "execfile(filename[, globals[, locals]])\n\
823 \n\
824 Read and execute a Python script from a file.\n\
825 The globals and locals are dictionaries, defaulting to the current\n\
826 globals and locals. If only globals is given, locals defaults to it.");
827
828
829 static PyObject *
builtin_getattr(PyObject * self,PyObject * args)830 builtin_getattr(PyObject *self, PyObject *args)
831 {
832 PyObject *v, *result, *dflt = NULL;
833 PyObject *name;
834
835 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
836 return NULL;
837 #ifdef Py_USING_UNICODE
838 if (PyUnicode_Check(name)) {
839 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
840 if (name == NULL)
841 return NULL;
842 }
843 #endif
844
845 if (!PyString_Check(name)) {
846 PyErr_SetString(PyExc_TypeError,
847 "getattr(): attribute name must be string");
848 return NULL;
849 }
850 result = PyObject_GetAttr(v, name);
851 if (result == NULL && dflt != NULL &&
852 PyErr_ExceptionMatches(PyExc_AttributeError))
853 {
854 PyErr_Clear();
855 Py_INCREF(dflt);
856 result = dflt;
857 }
858 return result;
859 }
860
861 PyDoc_STRVAR(getattr_doc,
862 "getattr(object, name[, default]) -> value\n\
863 \n\
864 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
865 When a default argument is given, it is returned when the attribute doesn't\n\
866 exist; without it, an exception is raised in that case.");
867
868
869 static PyObject *
builtin_globals(PyObject * self)870 builtin_globals(PyObject *self)
871 {
872 PyObject *d;
873
874 d = PyEval_GetGlobals();
875 Py_XINCREF(d);
876 return d;
877 }
878
879 PyDoc_STRVAR(globals_doc,
880 "globals() -> dictionary\n\
881 \n\
882 Return the dictionary containing the current scope's global variables.");
883
884
885 static PyObject *
builtin_hasattr(PyObject * self,PyObject * args)886 builtin_hasattr(PyObject *self, PyObject *args)
887 {
888 PyObject *v;
889 PyObject *name;
890
891 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
892 return NULL;
893 #ifdef Py_USING_UNICODE
894 if (PyUnicode_Check(name)) {
895 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
896 if (name == NULL)
897 return NULL;
898 }
899 #endif
900
901 if (!PyString_Check(name)) {
902 PyErr_SetString(PyExc_TypeError,
903 "hasattr(): attribute name must be string");
904 return NULL;
905 }
906 v = PyObject_GetAttr(v, name);
907 if (v == NULL) {
908 if (!PyErr_ExceptionMatches(PyExc_Exception))
909 return NULL;
910 else {
911 PyErr_Clear();
912 Py_INCREF(Py_False);
913 return Py_False;
914 }
915 }
916 Py_DECREF(v);
917 Py_INCREF(Py_True);
918 return Py_True;
919 }
920
921 PyDoc_STRVAR(hasattr_doc,
922 "hasattr(object, name) -> bool\n\
923 \n\
924 Return whether the object has an attribute with the given name.\n\
925 (This is done by calling getattr(object, name) and catching exceptions.)");
926
927
928 static PyObject *
builtin_id(PyObject * self,PyObject * v)929 builtin_id(PyObject *self, PyObject *v)
930 {
931 return PyLong_FromVoidPtr(v);
932 }
933
934 PyDoc_STRVAR(id_doc,
935 "id(object) -> integer\n\
936 \n\
937 Return the identity of an object. This is guaranteed to be unique among\n\
938 simultaneously existing objects. (Hint: it's the object's memory address.)");
939
940
941 static PyObject *
builtin_map(PyObject * self,PyObject * args)942 builtin_map(PyObject *self, PyObject *args)
943 {
944 typedef struct {
945 PyObject *it; /* the iterator object */
946 int saw_StopIteration; /* bool: did the iterator end? */
947 } sequence;
948
949 PyObject *func, *result;
950 sequence *seqs = NULL, *sqp;
951 Py_ssize_t n, len;
952 register int i, j;
953
954 n = PyTuple_Size(args);
955 if (n < 2) {
956 PyErr_SetString(PyExc_TypeError,
957 "map() requires at least two args");
958 return NULL;
959 }
960
961 func = PyTuple_GetItem(args, 0);
962 n--;
963
964 if (func == Py_None) {
965 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
966 "use list(...)", 1) < 0)
967 return NULL;
968 if (n == 1) {
969 /* map(None, S) is the same as list(S). */
970 return PySequence_List(PyTuple_GetItem(args, 1));
971 }
972 }
973
974 /* Get space for sequence descriptors. Must NULL out the iterator
975 * pointers so that jumping to Fail_2 later doesn't see trash.
976 */
977 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
978 PyErr_NoMemory();
979 return NULL;
980 }
981 for (i = 0; i < n; ++i) {
982 seqs[i].it = (PyObject*)NULL;
983 seqs[i].saw_StopIteration = 0;
984 }
985
986 /* Do a first pass to obtain iterators for the arguments, and set len
987 * to the largest of their lengths.
988 */
989 len = 0;
990 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
991 PyObject *curseq;
992 Py_ssize_t curlen;
993
994 /* Get iterator. */
995 curseq = PyTuple_GetItem(args, i+1);
996 sqp->it = PyObject_GetIter(curseq);
997 if (sqp->it == NULL) {
998 static char errmsg[] =
999 "argument %d to map() must support iteration";
1000 char errbuf[sizeof(errmsg) + 25];
1001 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
1002 PyErr_SetString(PyExc_TypeError, errbuf);
1003 goto Fail_2;
1004 }
1005
1006 /* Update len. */
1007 curlen = _PyObject_LengthHint(curseq, 8);
1008 if (curlen > len)
1009 len = curlen;
1010 }
1011
1012 /* Get space for the result list. */
1013 if ((result = (PyObject *) PyList_New(len)) == NULL)
1014 goto Fail_2;
1015
1016 /* Iterate over the sequences until all have stopped. */
1017 for (i = 0; ; ++i) {
1018 PyObject *alist, *item=NULL, *value;
1019 int numactive = 0;
1020
1021 if (func == Py_None && n == 1)
1022 alist = NULL;
1023 else if ((alist = PyTuple_New(n)) == NULL)
1024 goto Fail_1;
1025
1026 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1027 if (sqp->saw_StopIteration) {
1028 Py_INCREF(Py_None);
1029 item = Py_None;
1030 }
1031 else {
1032 item = PyIter_Next(sqp->it);
1033 if (item)
1034 ++numactive;
1035 else {
1036 if (PyErr_Occurred()) {
1037 Py_XDECREF(alist);
1038 goto Fail_1;
1039 }
1040 Py_INCREF(Py_None);
1041 item = Py_None;
1042 sqp->saw_StopIteration = 1;
1043 }
1044 }
1045 if (alist)
1046 PyTuple_SET_ITEM(alist, j, item);
1047 else
1048 break;
1049 }
1050
1051 if (!alist)
1052 alist = item;
1053
1054 if (numactive == 0) {
1055 Py_DECREF(alist);
1056 break;
1057 }
1058
1059 if (func == Py_None)
1060 value = alist;
1061 else {
1062 value = PyEval_CallObject(func, alist);
1063 Py_DECREF(alist);
1064 if (value == NULL)
1065 goto Fail_1;
1066 }
1067 if (i >= len) {
1068 int status = PyList_Append(result, value);
1069 Py_DECREF(value);
1070 if (status < 0)
1071 goto Fail_1;
1072 }
1073 else if (PyList_SetItem(result, i, value) < 0)
1074 goto Fail_1;
1075 }
1076
1077 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1078 goto Fail_1;
1079
1080 goto Succeed;
1081
1082 Fail_1:
1083 Py_DECREF(result);
1084 Fail_2:
1085 result = NULL;
1086 Succeed:
1087 assert(seqs);
1088 for (i = 0; i < n; ++i)
1089 Py_XDECREF(seqs[i].it);
1090 PyMem_DEL(seqs);
1091 return result;
1092 }
1093
1094 PyDoc_STRVAR(map_doc,
1095 "map(function, sequence[, sequence, ...]) -> list\n\
1096 \n\
1097 Return a list of the results of applying the function to the items of\n\
1098 the argument sequence(s). If more than one sequence is given, the\n\
1099 function is called with an argument list consisting of the corresponding\n\
1100 item of each sequence, substituting None for missing values when not all\n\
1101 sequences have the same length. If the function is None, return a list of\n\
1102 the items of the sequence (or a list of tuples if more than one sequence).");
1103
1104
1105 static PyObject *
builtin_next(PyObject * self,PyObject * args)1106 builtin_next(PyObject *self, PyObject *args)
1107 {
1108 PyObject *it, *res;
1109 PyObject *def = NULL;
1110
1111 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1112 return NULL;
1113 if (!PyIter_Check(it)) {
1114 PyErr_Format(PyExc_TypeError,
1115 "%.200s object is not an iterator",
1116 it->ob_type->tp_name);
1117 return NULL;
1118 }
1119
1120 res = (*it->ob_type->tp_iternext)(it);
1121 if (res != NULL) {
1122 return res;
1123 } else if (def != NULL) {
1124 if (PyErr_Occurred()) {
1125 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1126 return NULL;
1127 PyErr_Clear();
1128 }
1129 Py_INCREF(def);
1130 return def;
1131 } else if (PyErr_Occurred()) {
1132 return NULL;
1133 } else {
1134 PyErr_SetNone(PyExc_StopIteration);
1135 return NULL;
1136 }
1137 }
1138
1139 PyDoc_STRVAR(next_doc,
1140 "next(iterator[, default])\n\
1141 \n\
1142 Return the next item from the iterator. If default is given and the iterator\n\
1143 is exhausted, it is returned instead of raising StopIteration.");
1144
1145
1146 static PyObject *
builtin_setattr(PyObject * self,PyObject * args)1147 builtin_setattr(PyObject *self, PyObject *args)
1148 {
1149 PyObject *v;
1150 PyObject *name;
1151 PyObject *value;
1152
1153 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1154 return NULL;
1155 if (PyObject_SetAttr(v, name, value) != 0)
1156 return NULL;
1157 Py_INCREF(Py_None);
1158 return Py_None;
1159 }
1160
1161 PyDoc_STRVAR(setattr_doc,
1162 "setattr(object, name, value)\n\
1163 \n\
1164 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1165 ``x.y = v''.");
1166
1167
1168 static PyObject *
builtin_delattr(PyObject * self,PyObject * args)1169 builtin_delattr(PyObject *self, PyObject *args)
1170 {
1171 PyObject *v;
1172 PyObject *name;
1173
1174 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1175 return NULL;
1176 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1177 return NULL;
1178 Py_INCREF(Py_None);
1179 return Py_None;
1180 }
1181
1182 PyDoc_STRVAR(delattr_doc,
1183 "delattr(object, name)\n\
1184 \n\
1185 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1186 ``del x.y''.");
1187
1188
1189 static PyObject *
builtin_hash(PyObject * self,PyObject * v)1190 builtin_hash(PyObject *self, PyObject *v)
1191 {
1192 long x;
1193
1194 x = PyObject_Hash(v);
1195 if (x == -1)
1196 return NULL;
1197 return PyInt_FromLong(x);
1198 }
1199
1200 PyDoc_STRVAR(hash_doc,
1201 "hash(object) -> integer\n\
1202 \n\
1203 Return a hash value for the object. Two objects with the same value have\n\
1204 the same hash value. The reverse is not necessarily true, but likely.");
1205
1206
1207 static PyObject *
builtin_hex(PyObject * self,PyObject * v)1208 builtin_hex(PyObject *self, PyObject *v)
1209 {
1210 PyNumberMethods *nb;
1211 PyObject *res;
1212
1213 if ((nb = v->ob_type->tp_as_number) == NULL ||
1214 nb->nb_hex == NULL) {
1215 PyErr_SetString(PyExc_TypeError,
1216 "hex() argument can't be converted to hex");
1217 return NULL;
1218 }
1219 res = (*nb->nb_hex)(v);
1220 if (res && !PyString_Check(res)) {
1221 PyErr_Format(PyExc_TypeError,
1222 "__hex__ returned non-string (type %.200s)",
1223 res->ob_type->tp_name);
1224 Py_DECREF(res);
1225 return NULL;
1226 }
1227 return res;
1228 }
1229
1230 PyDoc_STRVAR(hex_doc,
1231 "hex(number) -> string\n\
1232 \n\
1233 Return the hexadecimal representation of an integer or long integer.");
1234
1235
1236 static PyObject *builtin_raw_input(PyObject *, PyObject *);
1237
1238 static PyObject *
builtin_input(PyObject * self,PyObject * args)1239 builtin_input(PyObject *self, PyObject *args)
1240 {
1241 PyObject *line;
1242 char *str;
1243 PyObject *res;
1244 PyObject *globals, *locals;
1245 PyCompilerFlags cf;
1246
1247 line = builtin_raw_input(self, args);
1248 if (line == NULL)
1249 return line;
1250 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1251 return NULL;
1252 while (*str == ' ' || *str == '\t')
1253 str++;
1254 globals = PyEval_GetGlobals();
1255 locals = PyEval_GetLocals();
1256 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1257 if (PyDict_SetItemString(globals, "__builtins__",
1258 PyEval_GetBuiltins()) != 0)
1259 return NULL;
1260 }
1261 cf.cf_flags = 0;
1262 PyEval_MergeCompilerFlags(&cf);
1263 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1264 Py_DECREF(line);
1265 return res;
1266 }
1267
1268 PyDoc_STRVAR(input_doc,
1269 "input([prompt]) -> value\n\
1270 \n\
1271 Equivalent to eval(raw_input(prompt)).");
1272
1273
1274 static PyObject *
builtin_intern(PyObject * self,PyObject * args)1275 builtin_intern(PyObject *self, PyObject *args)
1276 {
1277 PyObject *s;
1278 if (!PyArg_ParseTuple(args, "S:intern", &s))
1279 return NULL;
1280 if (!PyString_CheckExact(s)) {
1281 PyErr_SetString(PyExc_TypeError,
1282 "can't intern subclass of string");
1283 return NULL;
1284 }
1285 Py_INCREF(s);
1286 PyString_InternInPlace(&s);
1287 return s;
1288 }
1289
1290 PyDoc_STRVAR(intern_doc,
1291 "intern(string) -> string\n\
1292 \n\
1293 ``Intern'' the given string. This enters the string in the (global)\n\
1294 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1295 Return the string itself or the previously interned string object with the\n\
1296 same value.");
1297
1298
1299 static PyObject *
builtin_iter(PyObject * self,PyObject * args)1300 builtin_iter(PyObject *self, PyObject *args)
1301 {
1302 PyObject *v, *w = NULL;
1303
1304 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1305 return NULL;
1306 if (w == NULL)
1307 return PyObject_GetIter(v);
1308 if (!PyCallable_Check(v)) {
1309 PyErr_SetString(PyExc_TypeError,
1310 "iter(v, w): v must be callable");
1311 return NULL;
1312 }
1313 return PyCallIter_New(v, w);
1314 }
1315
1316 PyDoc_STRVAR(iter_doc,
1317 "iter(collection) -> iterator\n\
1318 iter(callable, sentinel) -> iterator\n\
1319 \n\
1320 Get an iterator from an object. In the first form, the argument must\n\
1321 supply its own iterator, or be a sequence.\n\
1322 In the second form, the callable is called until it returns the sentinel.");
1323
1324
1325 static PyObject *
builtin_len(PyObject * self,PyObject * v)1326 builtin_len(PyObject *self, PyObject *v)
1327 {
1328 Py_ssize_t res;
1329
1330 res = PyObject_Size(v);
1331 if (res < 0 && PyErr_Occurred())
1332 return NULL;
1333 return PyInt_FromSsize_t(res);
1334 }
1335
1336 PyDoc_STRVAR(len_doc,
1337 "len(object) -> integer\n\
1338 \n\
1339 Return the number of items of a sequence or collection.");
1340
1341
1342 static PyObject *
builtin_locals(PyObject * self)1343 builtin_locals(PyObject *self)
1344 {
1345 PyObject *d;
1346
1347 d = PyEval_GetLocals();
1348 Py_XINCREF(d);
1349 return d;
1350 }
1351
1352 PyDoc_STRVAR(locals_doc,
1353 "locals() -> dictionary\n\
1354 \n\
1355 Update and return a dictionary containing the current scope's local variables.");
1356
1357
1358 static PyObject *
min_max(PyObject * args,PyObject * kwds,int op)1359 min_max(PyObject *args, PyObject *kwds, int op)
1360 {
1361 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1362 const char *name = op == Py_LT ? "min" : "max";
1363
1364 if (PyTuple_Size(args) > 1)
1365 v = args;
1366 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1367 return NULL;
1368
1369 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1370 keyfunc = PyDict_GetItemString(kwds, "key");
1371 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1372 PyErr_Format(PyExc_TypeError,
1373 "%s() got an unexpected keyword argument", name);
1374 return NULL;
1375 }
1376 Py_INCREF(keyfunc);
1377 }
1378
1379 it = PyObject_GetIter(v);
1380 if (it == NULL) {
1381 Py_XDECREF(keyfunc);
1382 return NULL;
1383 }
1384
1385 maxitem = NULL; /* the result */
1386 maxval = NULL; /* the value associated with the result */
1387 while (( item = PyIter_Next(it) )) {
1388 /* get the value from the key function */
1389 if (keyfunc != NULL) {
1390 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1391 if (val == NULL)
1392 goto Fail_it_item;
1393 }
1394 /* no key function; the value is the item */
1395 else {
1396 val = item;
1397 Py_INCREF(val);
1398 }
1399
1400 /* maximum value and item are unset; set them */
1401 if (maxval == NULL) {
1402 maxitem = item;
1403 maxval = val;
1404 }
1405 /* maximum value and item are set; update them as necessary */
1406 else {
1407 int cmp = PyObject_RichCompareBool(val, maxval, op);
1408 if (cmp < 0)
1409 goto Fail_it_item_and_val;
1410 else if (cmp > 0) {
1411 Py_DECREF(maxval);
1412 Py_DECREF(maxitem);
1413 maxval = val;
1414 maxitem = item;
1415 }
1416 else {
1417 Py_DECREF(item);
1418 Py_DECREF(val);
1419 }
1420 }
1421 }
1422 if (PyErr_Occurred())
1423 goto Fail_it;
1424 if (maxval == NULL) {
1425 PyErr_Format(PyExc_ValueError,
1426 "%s() arg is an empty sequence", name);
1427 assert(maxitem == NULL);
1428 }
1429 else
1430 Py_DECREF(maxval);
1431 Py_DECREF(it);
1432 Py_XDECREF(keyfunc);
1433 return maxitem;
1434
1435 Fail_it_item_and_val:
1436 Py_DECREF(val);
1437 Fail_it_item:
1438 Py_DECREF(item);
1439 Fail_it:
1440 Py_XDECREF(maxval);
1441 Py_XDECREF(maxitem);
1442 Py_DECREF(it);
1443 Py_XDECREF(keyfunc);
1444 return NULL;
1445 }
1446
1447 static PyObject *
builtin_min(PyObject * self,PyObject * args,PyObject * kwds)1448 builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1449 {
1450 return min_max(args, kwds, Py_LT);
1451 }
1452
1453 PyDoc_STRVAR(min_doc,
1454 "min(iterable[, key=func]) -> value\n\
1455 min(a, b, c, ...[, key=func]) -> value\n\
1456 \n\
1457 With a single iterable argument, return its smallest item.\n\
1458 With two or more arguments, return the smallest argument.");
1459
1460
1461 static PyObject *
builtin_max(PyObject * self,PyObject * args,PyObject * kwds)1462 builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1463 {
1464 return min_max(args, kwds, Py_GT);
1465 }
1466
1467 PyDoc_STRVAR(max_doc,
1468 "max(iterable[, key=func]) -> value\n\
1469 max(a, b, c, ...[, key=func]) -> value\n\
1470 \n\
1471 With a single iterable argument, return its largest item.\n\
1472 With two or more arguments, return the largest argument.");
1473
1474
1475 static PyObject *
builtin_oct(PyObject * self,PyObject * v)1476 builtin_oct(PyObject *self, PyObject *v)
1477 {
1478 PyNumberMethods *nb;
1479 PyObject *res;
1480
1481 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1482 nb->nb_oct == NULL) {
1483 PyErr_SetString(PyExc_TypeError,
1484 "oct() argument can't be converted to oct");
1485 return NULL;
1486 }
1487 res = (*nb->nb_oct)(v);
1488 if (res && !PyString_Check(res)) {
1489 PyErr_Format(PyExc_TypeError,
1490 "__oct__ returned non-string (type %.200s)",
1491 res->ob_type->tp_name);
1492 Py_DECREF(res);
1493 return NULL;
1494 }
1495 return res;
1496 }
1497
1498 PyDoc_STRVAR(oct_doc,
1499 "oct(number) -> string\n\
1500 \n\
1501 Return the octal representation of an integer or long integer.");
1502
1503
1504 static PyObject *
builtin_open(PyObject * self,PyObject * args,PyObject * kwds)1505 builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1506 {
1507 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
1508 }
1509
1510 PyDoc_STRVAR(open_doc,
1511 "open(name[, mode[, buffering]]) -> file object\n\
1512 \n\
1513 Open a file using the file() type, returns a file object. This is the\n\
1514 preferred way to open a file. See file.__doc__ for further information.");
1515
1516
1517 static PyObject *
builtin_ord(PyObject * self,PyObject * obj)1518 builtin_ord(PyObject *self, PyObject* obj)
1519 {
1520 long ord;
1521 Py_ssize_t size;
1522
1523 if (PyString_Check(obj)) {
1524 size = PyString_GET_SIZE(obj);
1525 if (size == 1) {
1526 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1527 return PyInt_FromLong(ord);
1528 }
1529 } else if (PyByteArray_Check(obj)) {
1530 size = PyByteArray_GET_SIZE(obj);
1531 if (size == 1) {
1532 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1533 return PyInt_FromLong(ord);
1534 }
1535
1536 #ifdef Py_USING_UNICODE
1537 } else if (PyUnicode_Check(obj)) {
1538 size = PyUnicode_GET_SIZE(obj);
1539 if (size == 1) {
1540 ord = (long)*PyUnicode_AS_UNICODE(obj);
1541 return PyInt_FromLong(ord);
1542 }
1543 #endif
1544 } else {
1545 PyErr_Format(PyExc_TypeError,
1546 "ord() expected string of length 1, but " \
1547 "%.200s found", obj->ob_type->tp_name);
1548 return NULL;
1549 }
1550
1551 PyErr_Format(PyExc_TypeError,
1552 "ord() expected a character, "
1553 "but string of length %zd found",
1554 size);
1555 return NULL;
1556 }
1557
1558 PyDoc_STRVAR(ord_doc,
1559 "ord(c) -> integer\n\
1560 \n\
1561 Return the integer ordinal of a one-character string.");
1562
1563
1564 static PyObject *
builtin_pow(PyObject * self,PyObject * args)1565 builtin_pow(PyObject *self, PyObject *args)
1566 {
1567 PyObject *v, *w, *z = Py_None;
1568
1569 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1570 return NULL;
1571 return PyNumber_Power(v, w, z);
1572 }
1573
1574 PyDoc_STRVAR(pow_doc,
1575 "pow(x, y[, z]) -> number\n\
1576 \n\
1577 With two arguments, equivalent to x**y. With three arguments,\n\
1578 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1579
1580
1581 static PyObject *
builtin_print(PyObject * self,PyObject * args,PyObject * kwds)1582 builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1583 {
1584 static char *kwlist[] = {"sep", "end", "file", 0};
1585 static PyObject *dummy_args = NULL;
1586 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1587 static PyObject *str_newline = NULL, *str_space = NULL;
1588 PyObject *newline, *space;
1589 PyObject *sep = NULL, *end = NULL, *file = NULL;
1590 int i, err, use_unicode = 0;
1591
1592 if (dummy_args == NULL) {
1593 if (!(dummy_args = PyTuple_New(0)))
1594 return NULL;
1595 }
1596 if (str_newline == NULL) {
1597 str_newline = PyString_FromString("\n");
1598 if (str_newline == NULL)
1599 return NULL;
1600 str_space = PyString_FromString(" ");
1601 if (str_space == NULL) {
1602 Py_CLEAR(str_newline);
1603 return NULL;
1604 }
1605 #ifdef Py_USING_UNICODE
1606 unicode_newline = PyUnicode_FromString("\n");
1607 if (unicode_newline == NULL) {
1608 Py_CLEAR(str_newline);
1609 Py_CLEAR(str_space);
1610 return NULL;
1611 }
1612 unicode_space = PyUnicode_FromString(" ");
1613 if (unicode_space == NULL) {
1614 Py_CLEAR(str_newline);
1615 Py_CLEAR(str_space);
1616 Py_CLEAR(unicode_space);
1617 return NULL;
1618 }
1619 #endif
1620 }
1621 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1622 kwlist, &sep, &end, &file))
1623 return NULL;
1624 if (file == NULL || file == Py_None) {
1625 file = PySys_GetObject("stdout");
1626 /* sys.stdout may be None when FILE* stdout isn't connected */
1627 if (file == Py_None)
1628 Py_RETURN_NONE;
1629 }
1630 if (sep == Py_None) {
1631 sep = NULL;
1632 }
1633 else if (sep) {
1634 if (PyUnicode_Check(sep)) {
1635 use_unicode = 1;
1636 }
1637 else if (!PyString_Check(sep)) {
1638 PyErr_Format(PyExc_TypeError,
1639 "sep must be None, str or unicode, not %.200s",
1640 sep->ob_type->tp_name);
1641 return NULL;
1642 }
1643 }
1644 if (end == Py_None)
1645 end = NULL;
1646 else if (end) {
1647 if (PyUnicode_Check(end)) {
1648 use_unicode = 1;
1649 }
1650 else if (!PyString_Check(end)) {
1651 PyErr_Format(PyExc_TypeError,
1652 "end must be None, str or unicode, not %.200s",
1653 end->ob_type->tp_name);
1654 return NULL;
1655 }
1656 }
1657
1658 if (!use_unicode) {
1659 for (i = 0; i < PyTuple_Size(args); i++) {
1660 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1661 use_unicode = 1;
1662 break;
1663 }
1664 }
1665 }
1666 if (use_unicode) {
1667 newline = unicode_newline;
1668 space = unicode_space;
1669 }
1670 else {
1671 newline = str_newline;
1672 space = str_space;
1673 }
1674
1675 for (i = 0; i < PyTuple_Size(args); i++) {
1676 if (i > 0) {
1677 if (sep == NULL)
1678 err = PyFile_WriteObject(space, file,
1679 Py_PRINT_RAW);
1680 else
1681 err = PyFile_WriteObject(sep, file,
1682 Py_PRINT_RAW);
1683 if (err)
1684 return NULL;
1685 }
1686 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1687 Py_PRINT_RAW);
1688 if (err)
1689 return NULL;
1690 }
1691
1692 if (end == NULL)
1693 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1694 else
1695 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1696 if (err)
1697 return NULL;
1698
1699 Py_RETURN_NONE;
1700 }
1701
1702 PyDoc_STRVAR(print_doc,
1703 "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1704 \n\
1705 Prints the values to a stream, or to sys.stdout by default.\n\
1706 Optional keyword arguments:\n\
1707 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1708 sep: string inserted between values, default a space.\n\
1709 end: string appended after the last value, default a newline.");
1710
1711
1712 /* Return number of items in range (lo, hi, step), when arguments are
1713 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1714 * & only if the true value is too large to fit in a signed long.
1715 * Arguments MUST return 1 with either PyInt_Check() or
1716 * PyLong_Check(). Return -1 when there is an error.
1717 */
1718 static long
get_len_of_range_longs(PyObject * lo,PyObject * hi,PyObject * step)1719 get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1720 {
1721 /* -------------------------------------------------------------
1722 Algorithm is equal to that of get_len_of_range(), but it operates
1723 on PyObjects (which are assumed to be PyLong or PyInt objects).
1724 ---------------------------------------------------------------*/
1725 long n;
1726 PyObject *diff = NULL;
1727 PyObject *one = NULL;
1728 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1729 /* holds sub-expression evaluations */
1730
1731 /* if (lo >= hi), return length of 0. */
1732 if (PyObject_Compare(lo, hi) >= 0)
1733 return 0;
1734
1735 if ((one = PyLong_FromLong(1L)) == NULL)
1736 goto Fail;
1737
1738 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1739 goto Fail;
1740
1741 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1742 goto Fail;
1743
1744 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1745 goto Fail;
1746
1747 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1748 goto Fail;
1749
1750 n = PyLong_AsLong(tmp3);
1751 if (PyErr_Occurred()) { /* Check for Overflow */
1752 PyErr_Clear();
1753 goto Fail;
1754 }
1755
1756 Py_DECREF(tmp3);
1757 Py_DECREF(tmp2);
1758 Py_DECREF(diff);
1759 Py_DECREF(tmp1);
1760 Py_DECREF(one);
1761 return n;
1762
1763 Fail:
1764 Py_XDECREF(tmp3);
1765 Py_XDECREF(tmp2);
1766 Py_XDECREF(diff);
1767 Py_XDECREF(tmp1);
1768 Py_XDECREF(one);
1769 return -1;
1770 }
1771
1772 /* Helper function for handle_range_longs. If arg is int or long
1773 object, returns it with incremented reference count. If arg is
1774 float, raises type error. As a last resort, creates a new int by
1775 calling arg type's nb_int method if it is defined. Returns NULL
1776 and sets exception on error.
1777
1778 Returns a new reference to an int object. */
1779 static PyObject *
get_range_long_argument(PyObject * arg,const char * name)1780 get_range_long_argument(PyObject *arg, const char *name)
1781 {
1782 PyObject *v;
1783 PyNumberMethods *nb;
1784 if (_PyAnyInt_Check(arg)) {
1785 Py_INCREF(arg);
1786 return arg;
1787 }
1788 if (PyFloat_Check(arg) ||
1789 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1790 nb->nb_int == NULL) {
1791 PyErr_Format(PyExc_TypeError,
1792 "range() integer %s argument expected, got %s.",
1793 name, arg->ob_type->tp_name);
1794 return NULL;
1795 }
1796 v = nb->nb_int(arg);
1797 if (v == NULL)
1798 return NULL;
1799 if (_PyAnyInt_Check(v))
1800 return v;
1801 Py_DECREF(v);
1802 PyErr_SetString(PyExc_TypeError,
1803 "__int__ should return int object");
1804 return NULL;
1805 }
1806
1807 /* An extension of builtin_range() that handles the case when PyLong
1808 * arguments are given. */
1809 static PyObject *
handle_range_longs(PyObject * self,PyObject * args)1810 handle_range_longs(PyObject *self, PyObject *args)
1811 {
1812 PyObject *ilow = NULL;
1813 PyObject *ihigh = NULL;
1814 PyObject *istep = NULL;
1815
1816 PyObject *low = NULL;
1817 PyObject *high = NULL;
1818 PyObject *step = NULL;
1819
1820 PyObject *curnum = NULL;
1821 PyObject *v = NULL;
1822 long bign;
1823 Py_ssize_t i, n;
1824 int cmp_result;
1825
1826 PyObject *zero = PyLong_FromLong(0);
1827
1828 if (zero == NULL)
1829 return NULL;
1830
1831 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1832 Py_DECREF(zero);
1833 return NULL;
1834 }
1835
1836 /* Figure out which way we were called, supply defaults, and be
1837 * sure to incref everything so that the decrefs at the end
1838 * are correct. NB: ilow, ihigh and istep are borrowed references.
1839 */
1840 assert(ilow != NULL);
1841 if (ihigh == NULL) {
1842 /* only 1 arg -- it's the upper limit */
1843 ihigh = ilow;
1844 ilow = NULL;
1845 }
1846
1847 /* convert ihigh if necessary */
1848 assert(ihigh != NULL);
1849 high = get_range_long_argument(ihigh, "end");
1850 if (high == NULL)
1851 goto Fail;
1852
1853 /* ihigh correct now; do ilow */
1854 if (ilow == NULL) {
1855 Py_INCREF(zero);
1856 low = zero;
1857 }
1858 else {
1859 low = get_range_long_argument(ilow, "start");
1860 if (low == NULL)
1861 goto Fail;
1862 }
1863
1864 /* ilow and ihigh correct now; do istep */
1865 if (istep == NULL)
1866 step = PyLong_FromLong(1);
1867 else
1868 step = get_range_long_argument(istep, "step");
1869 if (step == NULL)
1870 goto Fail;
1871
1872 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1873 goto Fail;
1874
1875 if (cmp_result == 0) {
1876 PyErr_SetString(PyExc_ValueError,
1877 "range() step argument must not be zero");
1878 goto Fail;
1879 }
1880
1881 if (cmp_result > 0)
1882 bign = get_len_of_range_longs(low, high, step);
1883 else {
1884 PyObject *neg_step = PyNumber_Negative(step);
1885 if (neg_step == NULL)
1886 goto Fail;
1887 bign = get_len_of_range_longs(high, low, neg_step);
1888 Py_DECREF(neg_step);
1889 }
1890
1891 n = (Py_ssize_t)bign;
1892 if (bign < 0 || (long)n != bign) {
1893 PyErr_SetString(PyExc_OverflowError,
1894 "range() result has too many items");
1895 goto Fail;
1896 }
1897
1898 v = PyList_New(n);
1899 if (v == NULL)
1900 goto Fail;
1901
1902 curnum = low;
1903 Py_INCREF(curnum);
1904
1905 for (i = 0; i < n; i++) {
1906 PyObject *w = PyNumber_Long(curnum);
1907 PyObject *tmp_num;
1908 if (w == NULL)
1909 goto Fail;
1910
1911 PyList_SET_ITEM(v, i, w);
1912
1913 tmp_num = PyNumber_Add(curnum, step);
1914 if (tmp_num == NULL)
1915 goto Fail;
1916
1917 Py_DECREF(curnum);
1918 curnum = tmp_num;
1919 }
1920 Py_DECREF(low);
1921 Py_DECREF(high);
1922 Py_DECREF(step);
1923 Py_DECREF(zero);
1924 Py_DECREF(curnum);
1925 return v;
1926
1927 Fail:
1928 Py_XDECREF(low);
1929 Py_XDECREF(high);
1930 Py_XDECREF(step);
1931 Py_DECREF(zero);
1932 Py_XDECREF(curnum);
1933 Py_XDECREF(v);
1934 return NULL;
1935 }
1936
1937 /* Return number of items in range/xrange (lo, hi, step). step > 0
1938 * required. Return a value < 0 if & only if the true value is too
1939 * large to fit in a signed long.
1940 */
1941 static long
get_len_of_range(long lo,long hi,long step)1942 get_len_of_range(long lo, long hi, long step)
1943 {
1944 /* -------------------------------------------------------------
1945 If lo >= hi, the range is empty.
1946 Else if n values are in the range, the last one is
1947 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1948 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1949 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1950 the RHS is non-negative and so truncation is the same as the
1951 floor. Letting M be the largest positive long, the worst case
1952 for the RHS numerator is hi=M, lo=-M-1, and then
1953 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1954 precision to compute the RHS exactly.
1955 ---------------------------------------------------------------*/
1956 long n = 0;
1957 if (lo < hi) {
1958 unsigned long uhi = (unsigned long)hi;
1959 unsigned long ulo = (unsigned long)lo;
1960 unsigned long diff = uhi - ulo - 1;
1961 n = (long)(diff / (unsigned long)step + 1);
1962 }
1963 return n;
1964 }
1965
1966 static PyObject *
builtin_range(PyObject * self,PyObject * args)1967 builtin_range(PyObject *self, PyObject *args)
1968 {
1969 long ilow = 0, ihigh = 0, istep = 1;
1970 long bign;
1971 Py_ssize_t i, n;
1972
1973 PyObject *v;
1974
1975 if (PyTuple_Size(args) <= 1) {
1976 if (!PyArg_ParseTuple(args,
1977 "l;range() requires 1-3 int arguments",
1978 &ihigh)) {
1979 PyErr_Clear();
1980 return handle_range_longs(self, args);
1981 }
1982 }
1983 else {
1984 if (!PyArg_ParseTuple(args,
1985 "ll|l;range() requires 1-3 int arguments",
1986 &ilow, &ihigh, &istep)) {
1987 PyErr_Clear();
1988 return handle_range_longs(self, args);
1989 }
1990 }
1991 if (istep == 0) {
1992 PyErr_SetString(PyExc_ValueError,
1993 "range() step argument must not be zero");
1994 return NULL;
1995 }
1996 if (istep > 0)
1997 bign = get_len_of_range(ilow, ihigh, istep);
1998 else
1999 bign = get_len_of_range(ihigh, ilow, -istep);
2000 n = (Py_ssize_t)bign;
2001 if (bign < 0 || (long)n != bign) {
2002 PyErr_SetString(PyExc_OverflowError,
2003 "range() result has too many items");
2004 return NULL;
2005 }
2006 v = PyList_New(n);
2007 if (v == NULL)
2008 return NULL;
2009 for (i = 0; i < n; i++) {
2010 PyObject *w = PyInt_FromLong(ilow);
2011 if (w == NULL) {
2012 Py_DECREF(v);
2013 return NULL;
2014 }
2015 PyList_SET_ITEM(v, i, w);
2016 ilow += istep;
2017 }
2018 return v;
2019 }
2020
2021 PyDoc_STRVAR(range_doc,
2022 "range(stop) -> list of integers\n\
2023 range(start, stop[, step]) -> list of integers\n\
2024 \n\
2025 Return a list containing an arithmetic progression of integers.\n\
2026 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2027 When step is given, it specifies the increment (or decrement).\n\
2028 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
2029 These are exactly the valid indices for a list of 4 elements.");
2030
2031
2032 static PyObject *
builtin_raw_input(PyObject * self,PyObject * args)2033 builtin_raw_input(PyObject *self, PyObject *args)
2034 {
2035 PyObject *v = NULL;
2036 PyObject *fin = PySys_GetObject("stdin");
2037 PyObject *fout = PySys_GetObject("stdout");
2038
2039 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2040 return NULL;
2041
2042 if (fin == NULL) {
2043 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2044 return NULL;
2045 }
2046 if (fout == NULL) {
2047 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2048 return NULL;
2049 }
2050 if (PyFile_SoftSpace(fout, 0)) {
2051 if (PyFile_WriteString(" ", fout) != 0)
2052 return NULL;
2053 }
2054 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2055 && isatty(fileno(PyFile_AsFile(fin)))
2056 && isatty(fileno(PyFile_AsFile(fout)))) {
2057 PyObject *po;
2058 char *prompt;
2059 char *s;
2060 PyObject *result;
2061 if (v != NULL) {
2062 po = PyObject_Str(v);
2063 if (po == NULL)
2064 return NULL;
2065 prompt = PyString_AsString(po);
2066 if (prompt == NULL)
2067 return NULL;
2068 }
2069 else {
2070 po = NULL;
2071 prompt = "";
2072 }
2073 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2074 prompt);
2075 Py_XDECREF(po);
2076 if (s == NULL) {
2077 if (!PyErr_Occurred())
2078 PyErr_SetNone(PyExc_KeyboardInterrupt);
2079 return NULL;
2080 }
2081 if (*s == '\0') {
2082 PyErr_SetNone(PyExc_EOFError);
2083 result = NULL;
2084 }
2085 else { /* strip trailing '\n' */
2086 size_t len = strlen(s);
2087 if (len > PY_SSIZE_T_MAX) {
2088 PyErr_SetString(PyExc_OverflowError,
2089 "[raw_]input: input too long");
2090 result = NULL;
2091 }
2092 else {
2093 result = PyString_FromStringAndSize(s, len-1);
2094 }
2095 }
2096 PyMem_FREE(s);
2097 return result;
2098 }
2099 if (v != NULL) {
2100 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2101 return NULL;
2102 }
2103 return PyFile_GetLine(fin, -1);
2104 }
2105
2106 PyDoc_STRVAR(raw_input_doc,
2107 "raw_input([prompt]) -> string\n\
2108 \n\
2109 Read a string from standard input. The trailing newline is stripped.\n\
2110 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2111 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
2112 is printed without a trailing newline before reading.");
2113
2114
2115 static PyObject *
builtin_reduce(PyObject * self,PyObject * args)2116 builtin_reduce(PyObject *self, PyObject *args)
2117 {
2118 static PyObject *functools_reduce = NULL;
2119
2120 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2121 "use functools.reduce()", 1) < 0)
2122 return NULL;
2123
2124 if (functools_reduce == NULL) {
2125 PyObject *functools = PyImport_ImportModule("functools");
2126 if (functools == NULL)
2127 return NULL;
2128 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2129 Py_DECREF(functools);
2130 if (functools_reduce == NULL)
2131 return NULL;
2132 }
2133 return PyObject_Call(functools_reduce, args, NULL);
2134 }
2135
2136 PyDoc_STRVAR(reduce_doc,
2137 "reduce(function, sequence[, initial]) -> value\n\
2138 \n\
2139 Apply a function of two arguments cumulatively to the items of a sequence,\n\
2140 from left to right, so as to reduce the sequence to a single value.\n\
2141 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2142 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2143 of the sequence in the calculation, and serves as a default when the\n\
2144 sequence is empty.");
2145
2146
2147 static PyObject *
builtin_reload(PyObject * self,PyObject * v)2148 builtin_reload(PyObject *self, PyObject *v)
2149 {
2150 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2151 1) < 0)
2152 return NULL;
2153
2154 return PyImport_ReloadModule(v);
2155 }
2156
2157 PyDoc_STRVAR(reload_doc,
2158 "reload(module) -> module\n\
2159 \n\
2160 Reload the module. The module must have been successfully imported before.");
2161
2162
2163 static PyObject *
builtin_repr(PyObject * self,PyObject * v)2164 builtin_repr(PyObject *self, PyObject *v)
2165 {
2166 return PyObject_Repr(v);
2167 }
2168
2169 PyDoc_STRVAR(repr_doc,
2170 "repr(object) -> string\n\
2171 \n\
2172 Return the canonical string representation of the object.\n\
2173 For most object types, eval(repr(object)) == object.");
2174
2175
2176 static PyObject *
builtin_round(PyObject * self,PyObject * args,PyObject * kwds)2177 builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
2178 {
2179 double x;
2180 PyObject *o_ndigits = NULL;
2181 Py_ssize_t ndigits;
2182 static char *kwlist[] = {"number", "ndigits", 0};
2183
2184 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2185 kwlist, &x, &o_ndigits))
2186 return NULL;
2187
2188 if (o_ndigits == NULL) {
2189 /* second argument defaults to 0 */
2190 ndigits = 0;
2191 }
2192 else {
2193 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2194 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2195 if (ndigits == -1 && PyErr_Occurred())
2196 return NULL;
2197 }
2198
2199 /* nans, infinities and zeros round to themselves */
2200 if (!Py_IS_FINITE(x) || x == 0.0)
2201 return PyFloat_FromDouble(x);
2202
2203 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2204 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2205 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
2206 #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2207 #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
2208 if (ndigits > NDIGITS_MAX)
2209 /* return x */
2210 return PyFloat_FromDouble(x);
2211 else if (ndigits < NDIGITS_MIN)
2212 /* return 0.0, but with sign of x */
2213 return PyFloat_FromDouble(0.0*x);
2214 else
2215 /* finite x, and ndigits is not unreasonably large */
2216 /* _Py_double_round is defined in floatobject.c */
2217 return _Py_double_round(x, (int)ndigits);
2218 #undef NDIGITS_MAX
2219 #undef NDIGITS_MIN
2220 }
2221
2222 PyDoc_STRVAR(round_doc,
2223 "round(number[, ndigits]) -> floating point number\n\
2224 \n\
2225 Round a number to a given precision in decimal digits (default 0 digits).\n\
2226 This always returns a floating point number. Precision may be negative.");
2227
2228 static PyObject *
builtin_sorted(PyObject * self,PyObject * args,PyObject * kwds)2229 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2230 {
2231 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2232 PyObject *callable;
2233 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2234 int reverse;
2235
2236 /* args 1-4 should match listsort in Objects/listobject.c */
2237 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2238 kwlist, &seq, &compare, &keyfunc, &reverse))
2239 return NULL;
2240
2241 newlist = PySequence_List(seq);
2242 if (newlist == NULL)
2243 return NULL;
2244
2245 callable = PyObject_GetAttrString(newlist, "sort");
2246 if (callable == NULL) {
2247 Py_DECREF(newlist);
2248 return NULL;
2249 }
2250
2251 newargs = PyTuple_GetSlice(args, 1, 4);
2252 if (newargs == NULL) {
2253 Py_DECREF(newlist);
2254 Py_DECREF(callable);
2255 return NULL;
2256 }
2257
2258 v = PyObject_Call(callable, newargs, kwds);
2259 Py_DECREF(newargs);
2260 Py_DECREF(callable);
2261 if (v == NULL) {
2262 Py_DECREF(newlist);
2263 return NULL;
2264 }
2265 Py_DECREF(v);
2266 return newlist;
2267 }
2268
2269 PyDoc_STRVAR(sorted_doc,
2270 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2271
2272 static PyObject *
builtin_vars(PyObject * self,PyObject * args)2273 builtin_vars(PyObject *self, PyObject *args)
2274 {
2275 PyObject *v = NULL;
2276 PyObject *d;
2277
2278 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2279 return NULL;
2280 if (v == NULL) {
2281 d = PyEval_GetLocals();
2282 if (d == NULL) {
2283 if (!PyErr_Occurred())
2284 PyErr_SetString(PyExc_SystemError,
2285 "vars(): no locals!?");
2286 }
2287 else
2288 Py_INCREF(d);
2289 }
2290 else {
2291 d = PyObject_GetAttrString(v, "__dict__");
2292 if (d == NULL) {
2293 PyErr_SetString(PyExc_TypeError,
2294 "vars() argument must have __dict__ attribute");
2295 return NULL;
2296 }
2297 }
2298 return d;
2299 }
2300
2301 PyDoc_STRVAR(vars_doc,
2302 "vars([object]) -> dictionary\n\
2303 \n\
2304 Without arguments, equivalent to locals().\n\
2305 With an argument, equivalent to object.__dict__.");
2306
2307
2308 static PyObject*
builtin_sum(PyObject * self,PyObject * args)2309 builtin_sum(PyObject *self, PyObject *args)
2310 {
2311 PyObject *seq;
2312 PyObject *result = NULL;
2313 PyObject *temp, *item, *iter;
2314
2315 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2316 return NULL;
2317
2318 iter = PyObject_GetIter(seq);
2319 if (iter == NULL)
2320 return NULL;
2321
2322 if (result == NULL) {
2323 result = PyInt_FromLong(0);
2324 if (result == NULL) {
2325 Py_DECREF(iter);
2326 return NULL;
2327 }
2328 } else {
2329 /* reject string values for 'start' parameter */
2330 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2331 PyErr_SetString(PyExc_TypeError,
2332 "sum() can't sum strings [use ''.join(seq) instead]");
2333 Py_DECREF(iter);
2334 return NULL;
2335 }
2336 Py_INCREF(result);
2337 }
2338
2339 #ifndef SLOW_SUM
2340 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2341 Assumes all inputs are the same type. If the assumption fails, default
2342 to the more general routine.
2343 */
2344 if (PyInt_CheckExact(result)) {
2345 long i_result = PyInt_AS_LONG(result);
2346 Py_DECREF(result);
2347 result = NULL;
2348 while(result == NULL) {
2349 item = PyIter_Next(iter);
2350 if (item == NULL) {
2351 Py_DECREF(iter);
2352 if (PyErr_Occurred())
2353 return NULL;
2354 return PyInt_FromLong(i_result);
2355 }
2356 if (PyInt_CheckExact(item)) {
2357 long b = PyInt_AS_LONG(item);
2358 long x = i_result + b;
2359 if ((x^i_result) >= 0 || (x^b) >= 0) {
2360 i_result = x;
2361 Py_DECREF(item);
2362 continue;
2363 }
2364 }
2365 /* Either overflowed or is not an int. Restore real objects and process normally */
2366 result = PyInt_FromLong(i_result);
2367 if (result == NULL) {
2368 Py_DECREF(item);
2369 Py_DECREF(iter);
2370 return NULL;
2371 }
2372 temp = PyNumber_Add(result, item);
2373 Py_DECREF(result);
2374 Py_DECREF(item);
2375 result = temp;
2376 if (result == NULL) {
2377 Py_DECREF(iter);
2378 return NULL;
2379 }
2380 }
2381 }
2382
2383 if (PyFloat_CheckExact(result)) {
2384 double f_result = PyFloat_AS_DOUBLE(result);
2385 Py_DECREF(result);
2386 result = NULL;
2387 while(result == NULL) {
2388 item = PyIter_Next(iter);
2389 if (item == NULL) {
2390 Py_DECREF(iter);
2391 if (PyErr_Occurred())
2392 return NULL;
2393 return PyFloat_FromDouble(f_result);
2394 }
2395 if (PyFloat_CheckExact(item)) {
2396 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2397 f_result += PyFloat_AS_DOUBLE(item);
2398 PyFPE_END_PROTECT(f_result)
2399 Py_DECREF(item);
2400 continue;
2401 }
2402 if (PyInt_CheckExact(item)) {
2403 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2404 f_result += (double)PyInt_AS_LONG(item);
2405 PyFPE_END_PROTECT(f_result)
2406 Py_DECREF(item);
2407 continue;
2408 }
2409 result = PyFloat_FromDouble(f_result);
2410 if (result == NULL) {
2411 Py_DECREF(item);
2412 Py_DECREF(iter);
2413 return NULL;
2414 }
2415 temp = PyNumber_Add(result, item);
2416 Py_DECREF(result);
2417 Py_DECREF(item);
2418 result = temp;
2419 if (result == NULL) {
2420 Py_DECREF(iter);
2421 return NULL;
2422 }
2423 }
2424 }
2425 #endif
2426
2427 for(;;) {
2428 item = PyIter_Next(iter);
2429 if (item == NULL) {
2430 /* error, or end-of-sequence */
2431 if (PyErr_Occurred()) {
2432 Py_DECREF(result);
2433 result = NULL;
2434 }
2435 break;
2436 }
2437 /* It's tempting to use PyNumber_InPlaceAdd instead of
2438 PyNumber_Add here, to avoid quadratic running time
2439 when doing 'sum(list_of_lists, [])'. However, this
2440 would produce a change in behaviour: a snippet like
2441
2442 empty = []
2443 sum([[x] for x in range(10)], empty)
2444
2445 would change the value of empty. */
2446 temp = PyNumber_Add(result, item);
2447 Py_DECREF(result);
2448 Py_DECREF(item);
2449 result = temp;
2450 if (result == NULL)
2451 break;
2452 }
2453 Py_DECREF(iter);
2454 return result;
2455 }
2456
2457 PyDoc_STRVAR(sum_doc,
2458 "sum(iterable[, start]) -> value\n\
2459 \n\
2460 Return the sum of an iterable or sequence of numbers (NOT strings)\n\
2461 plus the value of 'start' (which defaults to 0). When the sequence is\n\
2462 empty, return start.");
2463
2464
2465 static PyObject *
builtin_isinstance(PyObject * self,PyObject * args)2466 builtin_isinstance(PyObject *self, PyObject *args)
2467 {
2468 PyObject *inst;
2469 PyObject *cls;
2470 int retval;
2471
2472 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2473 return NULL;
2474
2475 retval = PyObject_IsInstance(inst, cls);
2476 if (retval < 0)
2477 return NULL;
2478 return PyBool_FromLong(retval);
2479 }
2480
2481 PyDoc_STRVAR(isinstance_doc,
2482 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2483 \n\
2484 Return whether an object is an instance of a class or of a subclass thereof.\n\
2485 With a type as second argument, return whether that is the object's type.\n\
2486 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2487 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2488
2489
2490 static PyObject *
builtin_issubclass(PyObject * self,PyObject * args)2491 builtin_issubclass(PyObject *self, PyObject *args)
2492 {
2493 PyObject *derived;
2494 PyObject *cls;
2495 int retval;
2496
2497 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2498 return NULL;
2499
2500 retval = PyObject_IsSubclass(derived, cls);
2501 if (retval < 0)
2502 return NULL;
2503 return PyBool_FromLong(retval);
2504 }
2505
2506 PyDoc_STRVAR(issubclass_doc,
2507 "issubclass(C, B) -> bool\n\
2508 \n\
2509 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2510 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2511 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2512
2513
2514 static PyObject*
builtin_zip(PyObject * self,PyObject * args)2515 builtin_zip(PyObject *self, PyObject *args)
2516 {
2517 PyObject *ret;
2518 const Py_ssize_t itemsize = PySequence_Length(args);
2519 Py_ssize_t i;
2520 PyObject *itlist; /* tuple of iterators */
2521 Py_ssize_t len; /* guess at result length */
2522
2523 if (itemsize == 0)
2524 return PyList_New(0);
2525
2526 /* args must be a tuple */
2527 assert(PyTuple_Check(args));
2528
2529 /* Guess at result length: the shortest of the input lengths.
2530 If some argument refuses to say, we refuse to guess too, lest
2531 an argument like xrange(sys.maxint) lead us astray.*/
2532 len = -1; /* unknown */
2533 for (i = 0; i < itemsize; ++i) {
2534 PyObject *item = PyTuple_GET_ITEM(args, i);
2535 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2536 if (thislen < 0) {
2537 if (thislen == -1)
2538 return NULL;
2539 len = -1;
2540 break;
2541 }
2542 else if (len < 0 || thislen < len)
2543 len = thislen;
2544 }
2545
2546 /* allocate result list */
2547 if (len < 0)
2548 len = 10; /* arbitrary */
2549 if ((ret = PyList_New(len)) == NULL)
2550 return NULL;
2551
2552 /* obtain iterators */
2553 itlist = PyTuple_New(itemsize);
2554 if (itlist == NULL)
2555 goto Fail_ret;
2556 for (i = 0; i < itemsize; ++i) {
2557 PyObject *item = PyTuple_GET_ITEM(args, i);
2558 PyObject *it = PyObject_GetIter(item);
2559 if (it == NULL) {
2560 if (PyErr_ExceptionMatches(PyExc_TypeError))
2561 PyErr_Format(PyExc_TypeError,
2562 "zip argument #%zd must support iteration",
2563 i+1);
2564 goto Fail_ret_itlist;
2565 }
2566 PyTuple_SET_ITEM(itlist, i, it);
2567 }
2568
2569 /* build result into ret list */
2570 for (i = 0; ; ++i) {
2571 int j;
2572 PyObject *next = PyTuple_New(itemsize);
2573 if (!next)
2574 goto Fail_ret_itlist;
2575
2576 for (j = 0; j < itemsize; j++) {
2577 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2578 PyObject *item = PyIter_Next(it);
2579 if (!item) {
2580 if (PyErr_Occurred()) {
2581 Py_DECREF(ret);
2582 ret = NULL;
2583 }
2584 Py_DECREF(next);
2585 Py_DECREF(itlist);
2586 goto Done;
2587 }
2588 PyTuple_SET_ITEM(next, j, item);
2589 }
2590
2591 if (i < len)
2592 PyList_SET_ITEM(ret, i, next);
2593 else {
2594 int status = PyList_Append(ret, next);
2595 Py_DECREF(next);
2596 ++len;
2597 if (status < 0)
2598 goto Fail_ret_itlist;
2599 }
2600 }
2601
2602 Done:
2603 if (ret != NULL && i < len) {
2604 /* The list is too big. */
2605 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2606 return NULL;
2607 }
2608 return ret;
2609
2610 Fail_ret_itlist:
2611 Py_DECREF(itlist);
2612 Fail_ret:
2613 Py_DECREF(ret);
2614 return NULL;
2615 }
2616
2617
2618 PyDoc_STRVAR(zip_doc,
2619 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2620 \n\
2621 Return a list of tuples, where each tuple contains the i-th element\n\
2622 from each of the argument sequences. The returned list is truncated\n\
2623 in length to the length of the shortest argument sequence.");
2624
2625
2626 static PyMethodDef builtin_methods[] = {
2627 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2628 {"abs", builtin_abs, METH_O, abs_doc},
2629 {"all", builtin_all, METH_O, all_doc},
2630 {"any", builtin_any, METH_O, any_doc},
2631 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2632 {"bin", builtin_bin, METH_O, bin_doc},
2633 {"callable", builtin_callable, METH_O, callable_doc},
2634 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2635 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2636 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2637 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2638 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2639 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2640 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2641 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2642 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2643 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2644 {"format", builtin_format, METH_VARARGS, format_doc},
2645 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2646 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2647 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2648 {"hash", builtin_hash, METH_O, hash_doc},
2649 {"hex", builtin_hex, METH_O, hex_doc},
2650 {"id", builtin_id, METH_O, id_doc},
2651 {"input", builtin_input, METH_VARARGS, input_doc},
2652 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2653 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2654 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2655 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2656 {"len", builtin_len, METH_O, len_doc},
2657 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2658 {"map", builtin_map, METH_VARARGS, map_doc},
2659 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2660 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2661 {"next", builtin_next, METH_VARARGS, next_doc},
2662 {"oct", builtin_oct, METH_O, oct_doc},
2663 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2664 {"ord", builtin_ord, METH_O, ord_doc},
2665 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2666 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2667 {"range", builtin_range, METH_VARARGS, range_doc},
2668 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2669 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2670 {"reload", builtin_reload, METH_O, reload_doc},
2671 {"repr", builtin_repr, METH_O, repr_doc},
2672 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2673 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2674 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2675 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2676 #ifdef Py_USING_UNICODE
2677 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
2678 #endif
2679 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2680 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2681 {NULL, NULL},
2682 };
2683
2684 PyDoc_STRVAR(builtin_doc,
2685 "Built-in functions, exceptions, and other objects.\n\
2686 \n\
2687 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2688
2689 PyObject *
_PyBuiltin_Init(void)2690 _PyBuiltin_Init(void)
2691 {
2692 PyObject *mod, *dict, *debug;
2693 mod = Py_InitModule4("__builtin__", builtin_methods,
2694 builtin_doc, (PyObject *)NULL,
2695 PYTHON_API_VERSION);
2696 if (mod == NULL)
2697 return NULL;
2698 dict = PyModule_GetDict(mod);
2699
2700 #ifdef Py_TRACE_REFS
2701 /* __builtin__ exposes a number of statically allocated objects
2702 * that, before this code was added in 2.3, never showed up in
2703 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2704 * result, programs leaking references to None and False (etc)
2705 * couldn't be diagnosed by examining sys.getobjects(0).
2706 */
2707 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2708 #else
2709 #define ADD_TO_ALL(OBJECT) (void)0
2710 #endif
2711
2712 #define SETBUILTIN(NAME, OBJECT) \
2713 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2714 return NULL; \
2715 ADD_TO_ALL(OBJECT)
2716
2717 SETBUILTIN("None", Py_None);
2718 SETBUILTIN("Ellipsis", Py_Ellipsis);
2719 SETBUILTIN("NotImplemented", Py_NotImplemented);
2720 SETBUILTIN("False", Py_False);
2721 SETBUILTIN("True", Py_True);
2722 SETBUILTIN("basestring", &PyBaseString_Type);
2723 SETBUILTIN("bool", &PyBool_Type);
2724 SETBUILTIN("memoryview", &PyMemoryView_Type);
2725 SETBUILTIN("bytearray", &PyByteArray_Type);
2726 SETBUILTIN("bytes", &PyString_Type);
2727 SETBUILTIN("buffer", &PyBuffer_Type);
2728 SETBUILTIN("classmethod", &PyClassMethod_Type);
2729 #ifndef WITHOUT_COMPLEX
2730 SETBUILTIN("complex", &PyComplex_Type);
2731 #endif
2732 SETBUILTIN("dict", &PyDict_Type);
2733 SETBUILTIN("enumerate", &PyEnum_Type);
2734 SETBUILTIN("file", &PyFile_Type);
2735 SETBUILTIN("float", &PyFloat_Type);
2736 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2737 SETBUILTIN("property", &PyProperty_Type);
2738 SETBUILTIN("int", &PyInt_Type);
2739 SETBUILTIN("list", &PyList_Type);
2740 SETBUILTIN("long", &PyLong_Type);
2741 SETBUILTIN("object", &PyBaseObject_Type);
2742 SETBUILTIN("reversed", &PyReversed_Type);
2743 SETBUILTIN("set", &PySet_Type);
2744 SETBUILTIN("slice", &PySlice_Type);
2745 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2746 SETBUILTIN("str", &PyString_Type);
2747 SETBUILTIN("super", &PySuper_Type);
2748 SETBUILTIN("tuple", &PyTuple_Type);
2749 SETBUILTIN("type", &PyType_Type);
2750 SETBUILTIN("xrange", &PyRange_Type);
2751 #ifdef Py_USING_UNICODE
2752 SETBUILTIN("unicode", &PyUnicode_Type);
2753 #endif
2754 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2755 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2756 Py_XDECREF(debug);
2757 return NULL;
2758 }
2759 Py_XDECREF(debug);
2760
2761 return mod;
2762 #undef ADD_TO_ALL
2763 #undef SETBUILTIN
2764 }
2765
2766 /* Helper for filter(): filter a tuple through a function */
2767
2768 static PyObject *
filtertuple(PyObject * func,PyObject * tuple)2769 filtertuple(PyObject *func, PyObject *tuple)
2770 {
2771 PyObject *result;
2772 Py_ssize_t i, j;
2773 Py_ssize_t len = PyTuple_Size(tuple);
2774
2775 if (len == 0) {
2776 if (PyTuple_CheckExact(tuple))
2777 Py_INCREF(tuple);
2778 else
2779 tuple = PyTuple_New(0);
2780 return tuple;
2781 }
2782
2783 if ((result = PyTuple_New(len)) == NULL)
2784 return NULL;
2785
2786 for (i = j = 0; i < len; ++i) {
2787 PyObject *item, *good;
2788 int ok;
2789
2790 if (tuple->ob_type->tp_as_sequence &&
2791 tuple->ob_type->tp_as_sequence->sq_item) {
2792 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2793 if (item == NULL)
2794 goto Fail_1;
2795 } else {
2796 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2797 goto Fail_1;
2798 }
2799 if (func == Py_None) {
2800 Py_INCREF(item);
2801 good = item;
2802 }
2803 else {
2804 PyObject *arg = PyTuple_Pack(1, item);
2805 if (arg == NULL) {
2806 Py_DECREF(item);
2807 goto Fail_1;
2808 }
2809 good = PyEval_CallObject(func, arg);
2810 Py_DECREF(arg);
2811 if (good == NULL) {
2812 Py_DECREF(item);
2813 goto Fail_1;
2814 }
2815 }
2816 ok = PyObject_IsTrue(good);
2817 Py_DECREF(good);
2818 if (ok > 0) {
2819 if (PyTuple_SetItem(result, j++, item) < 0)
2820 goto Fail_1;
2821 }
2822 else {
2823 Py_DECREF(item);
2824 if (ok < 0)
2825 goto Fail_1;
2826 }
2827 }
2828
2829 if (_PyTuple_Resize(&result, j) < 0)
2830 return NULL;
2831
2832 return result;
2833
2834 Fail_1:
2835 Py_DECREF(result);
2836 return NULL;
2837 }
2838
2839
2840 /* Helper for filter(): filter a string through a function */
2841
2842 static PyObject *
filterstring(PyObject * func,PyObject * strobj)2843 filterstring(PyObject *func, PyObject *strobj)
2844 {
2845 PyObject *result;
2846 Py_ssize_t i, j;
2847 Py_ssize_t len = PyString_Size(strobj);
2848 Py_ssize_t outlen = len;
2849
2850 if (func == Py_None) {
2851 /* If it's a real string we can return the original,
2852 * as no character is ever false and __getitem__
2853 * does return this character. If it's a subclass
2854 * we must go through the __getitem__ loop */
2855 if (PyString_CheckExact(strobj)) {
2856 Py_INCREF(strobj);
2857 return strobj;
2858 }
2859 }
2860 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2861 return NULL;
2862
2863 for (i = j = 0; i < len; ++i) {
2864 PyObject *item;
2865 int ok;
2866
2867 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2868 if (item == NULL)
2869 goto Fail_1;
2870 if (func==Py_None) {
2871 ok = 1;
2872 } else {
2873 PyObject *arg, *good;
2874 arg = PyTuple_Pack(1, item);
2875 if (arg == NULL) {
2876 Py_DECREF(item);
2877 goto Fail_1;
2878 }
2879 good = PyEval_CallObject(func, arg);
2880 Py_DECREF(arg);
2881 if (good == NULL) {
2882 Py_DECREF(item);
2883 goto Fail_1;
2884 }
2885 ok = PyObject_IsTrue(good);
2886 Py_DECREF(good);
2887 }
2888 if (ok > 0) {
2889 Py_ssize_t reslen;
2890 if (!PyString_Check(item)) {
2891 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2892 " __getitem__ returned different type");
2893 Py_DECREF(item);
2894 goto Fail_1;
2895 }
2896 reslen = PyString_GET_SIZE(item);
2897 if (reslen == 1) {
2898 PyString_AS_STRING(result)[j++] =
2899 PyString_AS_STRING(item)[0];
2900 } else {
2901 /* do we need more space? */
2902 Py_ssize_t need = j;
2903
2904 /* calculate space requirements while checking for overflow */
2905 if (need > PY_SSIZE_T_MAX - reslen) {
2906 Py_DECREF(item);
2907 goto Fail_1;
2908 }
2909
2910 need += reslen;
2911
2912 if (need > PY_SSIZE_T_MAX - len) {
2913 Py_DECREF(item);
2914 goto Fail_1;
2915 }
2916
2917 need += len;
2918
2919 if (need <= i) {
2920 Py_DECREF(item);
2921 goto Fail_1;
2922 }
2923
2924 need = need - i - 1;
2925
2926 assert(need >= 0);
2927 assert(outlen >= 0);
2928
2929 if (need > outlen) {
2930 /* overallocate, to avoid reallocations */
2931 if (outlen > PY_SSIZE_T_MAX / 2) {
2932 Py_DECREF(item);
2933 return NULL;
2934 }
2935
2936 if (need<2*outlen) {
2937 need = 2*outlen;
2938 }
2939 if (_PyString_Resize(&result, need)) {
2940 Py_DECREF(item);
2941 return NULL;
2942 }
2943 outlen = need;
2944 }
2945 memcpy(
2946 PyString_AS_STRING(result) + j,
2947 PyString_AS_STRING(item),
2948 reslen
2949 );
2950 j += reslen;
2951 }
2952 }
2953 Py_DECREF(item);
2954 if (ok < 0)
2955 goto Fail_1;
2956 }
2957
2958 if (j < outlen)
2959 _PyString_Resize(&result, j);
2960
2961 return result;
2962
2963 Fail_1:
2964 Py_DECREF(result);
2965 return NULL;
2966 }
2967
2968 #ifdef Py_USING_UNICODE
2969 /* Helper for filter(): filter a Unicode object through a function */
2970
2971 static PyObject *
filterunicode(PyObject * func,PyObject * strobj)2972 filterunicode(PyObject *func, PyObject *strobj)
2973 {
2974 PyObject *result;
2975 register Py_ssize_t i, j;
2976 Py_ssize_t len = PyUnicode_GetSize(strobj);
2977 Py_ssize_t outlen = len;
2978
2979 if (func == Py_None) {
2980 /* If it's a real string we can return the original,
2981 * as no character is ever false and __getitem__
2982 * does return this character. If it's a subclass
2983 * we must go through the __getitem__ loop */
2984 if (PyUnicode_CheckExact(strobj)) {
2985 Py_INCREF(strobj);
2986 return strobj;
2987 }
2988 }
2989 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2990 return NULL;
2991
2992 for (i = j = 0; i < len; ++i) {
2993 PyObject *item, *arg, *good;
2994 int ok;
2995
2996 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2997 if (item == NULL)
2998 goto Fail_1;
2999 if (func == Py_None) {
3000 ok = 1;
3001 } else {
3002 arg = PyTuple_Pack(1, item);
3003 if (arg == NULL) {
3004 Py_DECREF(item);
3005 goto Fail_1;
3006 }
3007 good = PyEval_CallObject(func, arg);
3008 Py_DECREF(arg);
3009 if (good == NULL) {
3010 Py_DECREF(item);
3011 goto Fail_1;
3012 }
3013 ok = PyObject_IsTrue(good);
3014 Py_DECREF(good);
3015 }
3016 if (ok > 0) {
3017 Py_ssize_t reslen;
3018 if (!PyUnicode_Check(item)) {
3019 PyErr_SetString(PyExc_TypeError,
3020 "can't filter unicode to unicode:"
3021 " __getitem__ returned different type");
3022 Py_DECREF(item);
3023 goto Fail_1;
3024 }
3025 reslen = PyUnicode_GET_SIZE(item);
3026 if (reslen == 1)
3027 PyUnicode_AS_UNICODE(result)[j++] =
3028 PyUnicode_AS_UNICODE(item)[0];
3029 else {
3030 /* do we need more space? */
3031 Py_ssize_t need = j + reslen + len - i - 1;
3032
3033 /* check that didnt overflow */
3034 if ((j > PY_SSIZE_T_MAX - reslen) ||
3035 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
3036 ((j + reslen + len) < i) ||
3037 ((j + reslen + len - i) <= 0)) {
3038 Py_DECREF(item);
3039 return NULL;
3040 }
3041
3042 assert(need >= 0);
3043 assert(outlen >= 0);
3044
3045 if (need > outlen) {
3046 /* overallocate, to avoid reallocations */
3047 if (need < 2 * outlen) {
3048 if (outlen > PY_SSIZE_T_MAX / 2) {
3049 Py_DECREF(item);
3050 return NULL;
3051 } else {
3052 need = 2 * outlen;
3053 }
3054 }
3055
3056 if (PyUnicode_Resize(&result, need) < 0) {
3057 Py_DECREF(item);
3058 goto Fail_1;
3059 }
3060 outlen = need;
3061 }
3062 memcpy(PyUnicode_AS_UNICODE(result) + j,
3063 PyUnicode_AS_UNICODE(item),
3064 reslen*sizeof(Py_UNICODE));
3065 j += reslen;
3066 }
3067 }
3068 Py_DECREF(item);
3069 if (ok < 0)
3070 goto Fail_1;
3071 }
3072
3073 if (j < outlen)
3074 PyUnicode_Resize(&result, j);
3075
3076 return result;
3077
3078 Fail_1:
3079 Py_DECREF(result);
3080 return NULL;
3081 }
3082 #endif
3083