source: python/trunk/Python/bltinmodule.c@ 383

Last change on this file since 383 was 2, checked in by Yuri Dario, 15 years ago

Initial import for vendor code.

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