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