This commit was manufactured by cvs2svn to create tag 'r241c1'.
[python/dscho.git] / Python / bltinmodule.c
blob6fbe799f71139e9b4b27040e5488edec1f949ed0
2 /* Built-in functions */
4 #include "Python.h"
6 #include "node.h"
7 #include "compile.h"
8 #include "eval.h"
10 #include <ctype.h>
12 #ifdef RISCOS
13 #include "unixstuff.h"
14 #endif
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
19 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
20 const char *Py_FileSystemDefaultEncoding = "mbcs";
21 #elif defined(__APPLE__)
22 const char *Py_FileSystemDefaultEncoding = "utf-8";
23 #else
24 const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
25 #endif
27 /* Forward */
28 static PyObject *filterstring(PyObject *, PyObject *);
29 #ifdef Py_USING_UNICODE
30 static PyObject *filterunicode(PyObject *, PyObject *);
31 #endif
32 static PyObject *filtertuple (PyObject *, PyObject *);
34 static PyObject *
35 builtin___import__(PyObject *self, PyObject *args)
37 char *name;
38 PyObject *globals = NULL;
39 PyObject *locals = NULL;
40 PyObject *fromlist = NULL;
42 if (!PyArg_ParseTuple(args, "s|OOO:__import__",
43 &name, &globals, &locals, &fromlist))
44 return NULL;
45 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
48 PyDoc_STRVAR(import_doc,
49 "__import__(name, globals, locals, fromlist) -> module\n\
50 \n\
51 Import a module. The globals are only used to determine the context;\n\
52 they are not modified. The locals are currently unused. The fromlist\n\
53 should be a list of names to emulate ``from name import ...'', or an\n\
54 empty list to emulate ``import name''.\n\
55 When importing a module from a package, note that __import__('A.B', ...)\n\
56 returns package A when fromlist is empty, but its submodule B when\n\
57 fromlist is not empty.");
60 static PyObject *
61 builtin_abs(PyObject *self, PyObject *v)
63 return PyNumber_Absolute(v);
66 PyDoc_STRVAR(abs_doc,
67 "abs(number) -> number\n\
68 \n\
69 Return the absolute value of the argument.");
72 static PyObject *
73 builtin_apply(PyObject *self, PyObject *args)
75 PyObject *func, *alist = NULL, *kwdict = NULL;
76 PyObject *t = NULL, *retval = NULL;
78 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
79 return NULL;
80 if (alist != NULL) {
81 if (!PyTuple_Check(alist)) {
82 if (!PySequence_Check(alist)) {
83 PyErr_Format(PyExc_TypeError,
84 "apply() arg 2 expected sequence, found %s",
85 alist->ob_type->tp_name);
86 return NULL;
88 t = PySequence_Tuple(alist);
89 if (t == NULL)
90 return NULL;
91 alist = t;
94 if (kwdict != NULL && !PyDict_Check(kwdict)) {
95 PyErr_Format(PyExc_TypeError,
96 "apply() arg 3 expected dictionary, found %s",
97 kwdict->ob_type->tp_name);
98 goto finally;
100 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
101 finally:
102 Py_XDECREF(t);
103 return retval;
106 PyDoc_STRVAR(apply_doc,
107 "apply(object[, args[, kwargs]]) -> value\n\
109 Call a callable object with positional arguments taken from the tuple args,\n\
110 and keyword arguments taken from the optional dictionary kwargs.\n\
111 Note that classes are callable, as are instances with a __call__() method.\n\
113 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
114 function(*args, **keywords).");
117 static PyObject *
118 builtin_callable(PyObject *self, PyObject *v)
120 return PyBool_FromLong((long)PyCallable_Check(v));
123 PyDoc_STRVAR(callable_doc,
124 "callable(object) -> bool\n\
126 Return whether the object is callable (i.e., some kind of function).\n\
127 Note that classes are callable, as are instances with a __call__() method.");
130 static PyObject *
131 builtin_filter(PyObject *self, PyObject *args)
133 PyObject *func, *seq, *result, *it, *arg;
134 int len; /* guess for result list size */
135 register int j;
137 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
138 return NULL;
140 /* Strings and tuples return a result of the same type. */
141 if (PyString_Check(seq))
142 return filterstring(func, seq);
143 #ifdef Py_USING_UNICODE
144 if (PyUnicode_Check(seq))
145 return filterunicode(func, seq);
146 #endif
147 if (PyTuple_Check(seq))
148 return filtertuple(func, seq);
150 /* Get iterator. */
151 it = PyObject_GetIter(seq);
152 if (it == NULL)
153 return NULL;
155 /* Guess a result list size. */
156 len = PyObject_Size(seq);
157 if (len < 0) {
158 PyErr_Clear();
159 len = 8; /* arbitrary */
162 /* Pre-allocate argument list tuple. */
163 arg = PyTuple_New(1);
164 if (arg == NULL)
165 goto Fail_arg;
167 /* Get a result list. */
168 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
169 /* Eww - can modify the list in-place. */
170 Py_INCREF(seq);
171 result = seq;
173 else {
174 result = PyList_New(len);
175 if (result == NULL)
176 goto Fail_it;
179 /* Build the result list. */
180 j = 0;
181 for (;;) {
182 PyObject *item;
183 int ok;
185 item = PyIter_Next(it);
186 if (item == NULL) {
187 if (PyErr_Occurred())
188 goto Fail_result_it;
189 break;
192 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
193 ok = PyObject_IsTrue(item);
195 else {
196 PyObject *good;
197 PyTuple_SET_ITEM(arg, 0, item);
198 good = PyObject_Call(func, arg, NULL);
199 PyTuple_SET_ITEM(arg, 0, NULL);
200 if (good == NULL) {
201 Py_DECREF(item);
202 goto Fail_result_it;
204 ok = PyObject_IsTrue(good);
205 Py_DECREF(good);
207 if (ok) {
208 if (j < len)
209 PyList_SET_ITEM(result, j, item);
210 else {
211 int status = PyList_Append(result, item);
212 Py_DECREF(item);
213 if (status < 0)
214 goto Fail_result_it;
216 ++j;
218 else
219 Py_DECREF(item);
223 /* Cut back result list if len is too big. */
224 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
225 goto Fail_result_it;
227 Py_DECREF(it);
228 Py_DECREF(arg);
229 return result;
231 Fail_result_it:
232 Py_DECREF(result);
233 Fail_it:
234 Py_DECREF(it);
235 Fail_arg:
236 Py_DECREF(arg);
237 return NULL;
240 PyDoc_STRVAR(filter_doc,
241 "filter(function or None, sequence) -> list, tuple, or string\n"
242 "\n"
243 "Return those items of sequence for which function(item) is true. If\n"
244 "function is None, return the items that are true. If sequence is a tuple\n"
245 "or string, return the same type, else return a list.");
247 static PyObject *
248 builtin_chr(PyObject *self, PyObject *args)
250 long x;
251 char s[1];
253 if (!PyArg_ParseTuple(args, "l:chr", &x))
254 return NULL;
255 if (x < 0 || x >= 256) {
256 PyErr_SetString(PyExc_ValueError,
257 "chr() arg not in range(256)");
258 return NULL;
260 s[0] = (char)x;
261 return PyString_FromStringAndSize(s, 1);
264 PyDoc_STRVAR(chr_doc,
265 "chr(i) -> character\n\
267 Return a string of one character with ordinal i; 0 <= i < 256.");
270 #ifdef Py_USING_UNICODE
271 static PyObject *
272 builtin_unichr(PyObject *self, PyObject *args)
274 long x;
276 if (!PyArg_ParseTuple(args, "l:unichr", &x))
277 return NULL;
279 return PyUnicode_FromOrdinal(x);
282 PyDoc_STRVAR(unichr_doc,
283 "unichr(i) -> Unicode character\n\
285 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
286 #endif
289 static PyObject *
290 builtin_cmp(PyObject *self, PyObject *args)
292 PyObject *a, *b;
293 int c;
295 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
296 return NULL;
297 if (PyObject_Cmp(a, b, &c) < 0)
298 return NULL;
299 return PyInt_FromLong((long)c);
302 PyDoc_STRVAR(cmp_doc,
303 "cmp(x, y) -> integer\n\
305 Return negative if x<y, zero if x==y, positive if x>y.");
308 static PyObject *
309 builtin_coerce(PyObject *self, PyObject *args)
311 PyObject *v, *w;
312 PyObject *res;
314 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
315 return NULL;
316 if (PyNumber_Coerce(&v, &w) < 0)
317 return NULL;
318 res = PyTuple_Pack(2, v, w);
319 Py_DECREF(v);
320 Py_DECREF(w);
321 return res;
324 PyDoc_STRVAR(coerce_doc,
325 "coerce(x, y) -> (x1, y1)\n\
327 Return a tuple consisting of the two numeric arguments converted to\n\
328 a common type, using the same rules as used by arithmetic operations.\n\
329 If coercion is not possible, raise TypeError.");
331 static PyObject *
332 builtin_compile(PyObject *self, PyObject *args)
334 char *str;
335 char *filename;
336 char *startstr;
337 int start;
338 int dont_inherit = 0;
339 int supplied_flags = 0;
340 PyCompilerFlags cf;
341 PyObject *result, *cmd, *tmp = NULL;
342 int length;
344 if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename,
345 &startstr, &supplied_flags, &dont_inherit))
346 return NULL;
348 cf.cf_flags = supplied_flags;
350 #ifdef Py_USING_UNICODE
351 if (PyUnicode_Check(cmd)) {
352 tmp = PyUnicode_AsUTF8String(cmd);
353 if (tmp == NULL)
354 return NULL;
355 cmd = tmp;
356 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
358 #endif
359 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
360 return NULL;
361 if ((size_t)length != strlen(str)) {
362 PyErr_SetString(PyExc_TypeError,
363 "compile() expected string without null bytes");
364 return NULL;
367 if (strcmp(startstr, "exec") == 0)
368 start = Py_file_input;
369 else if (strcmp(startstr, "eval") == 0)
370 start = Py_eval_input;
371 else if (strcmp(startstr, "single") == 0)
372 start = Py_single_input;
373 else {
374 PyErr_SetString(PyExc_ValueError,
375 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
376 return NULL;
379 if (supplied_flags &
380 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT))
382 PyErr_SetString(PyExc_ValueError,
383 "compile(): unrecognised flags");
384 return NULL;
386 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
388 if (!dont_inherit) {
389 PyEval_MergeCompilerFlags(&cf);
391 result = Py_CompileStringFlags(str, filename, start, &cf);
392 Py_XDECREF(tmp);
393 return result;
396 PyDoc_STRVAR(compile_doc,
397 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
399 Compile the source string (a Python module, statement or expression)\n\
400 into a code object that can be executed by the exec statement or eval().\n\
401 The filename will be used for run-time error messages.\n\
402 The mode must be 'exec' to compile a module, 'single' to compile a\n\
403 single (interactive) statement, or 'eval' to compile an expression.\n\
404 The flags argument, if present, controls which future statements influence\n\
405 the compilation of the code.\n\
406 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
407 the effects of any future statements in effect in the code calling\n\
408 compile; if absent or zero these statements do influence the compilation,\n\
409 in addition to any features explicitly specified.");
411 static PyObject *
412 builtin_dir(PyObject *self, PyObject *args)
414 PyObject *arg = NULL;
416 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
417 return NULL;
418 return PyObject_Dir(arg);
421 PyDoc_STRVAR(dir_doc,
422 "dir([object]) -> list of strings\n"
423 "\n"
424 "Return an alphabetized list of names comprising (some of) the attributes\n"
425 "of the given object, and of attributes reachable from it:\n"
426 "\n"
427 "No argument: the names in the current scope.\n"
428 "Module object: the module attributes.\n"
429 "Type or class object: its attributes, and recursively the attributes of\n"
430 " its bases.\n"
431 "Otherwise: its attributes, its class's attributes, and recursively the\n"
432 " attributes of its class's base classes.");
434 static PyObject *
435 builtin_divmod(PyObject *self, PyObject *args)
437 PyObject *v, *w;
439 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
440 return NULL;
441 return PyNumber_Divmod(v, w);
444 PyDoc_STRVAR(divmod_doc,
445 "divmod(x, y) -> (div, mod)\n\
447 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
450 static PyObject *
451 builtin_eval(PyObject *self, PyObject *args)
453 PyObject *cmd, *result, *tmp = NULL;
454 PyObject *globals = Py_None, *locals = Py_None;
455 char *str;
456 PyCompilerFlags cf;
458 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
459 return NULL;
460 if (locals != Py_None && !PyMapping_Check(locals)) {
461 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
462 return NULL;
464 if (globals != Py_None && !PyDict_Check(globals)) {
465 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
466 "globals must be a real dict; try eval(expr, {}, mapping)"
467 : "globals must be a dict");
468 return NULL;
470 if (globals == Py_None) {
471 globals = PyEval_GetGlobals();
472 if (locals == Py_None)
473 locals = PyEval_GetLocals();
475 else if (locals == Py_None)
476 locals = globals;
478 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
479 if (PyDict_SetItemString(globals, "__builtins__",
480 PyEval_GetBuiltins()) != 0)
481 return NULL;
484 if (PyCode_Check(cmd)) {
485 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
486 PyErr_SetString(PyExc_TypeError,
487 "code object passed to eval() may not contain free variables");
488 return NULL;
490 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
493 if (!PyString_Check(cmd) &&
494 !PyUnicode_Check(cmd)) {
495 PyErr_SetString(PyExc_TypeError,
496 "eval() arg 1 must be a string or code object");
497 return NULL;
499 cf.cf_flags = 0;
501 #ifdef Py_USING_UNICODE
502 if (PyUnicode_Check(cmd)) {
503 tmp = PyUnicode_AsUTF8String(cmd);
504 if (tmp == NULL)
505 return NULL;
506 cmd = tmp;
507 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
509 #endif
510 if (PyString_AsStringAndSize(cmd, &str, NULL))
511 return NULL;
512 while (*str == ' ' || *str == '\t')
513 str++;
515 (void)PyEval_MergeCompilerFlags(&cf);
516 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
517 Py_XDECREF(tmp);
518 return result;
521 PyDoc_STRVAR(eval_doc,
522 "eval(source[, globals[, locals]]) -> value\n\
524 Evaluate the source in the context of globals and locals.\n\
525 The source may be a string representing a Python expression\n\
526 or a code object as returned by compile().\n\
527 The globals must be a dictionary and locals can be any mappping,\n\
528 defaulting to the current globals and locals.\n\
529 If only globals is given, locals defaults to it.\n");
532 static PyObject *
533 builtin_execfile(PyObject *self, PyObject *args)
535 char *filename;
536 PyObject *globals = Py_None, *locals = Py_None;
537 PyObject *res;
538 FILE* fp = NULL;
539 PyCompilerFlags cf;
540 int exists;
542 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
543 &filename,
544 &PyDict_Type, &globals,
545 &locals))
546 return NULL;
547 if (locals != Py_None && !PyMapping_Check(locals)) {
548 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
549 return NULL;
551 if (globals == Py_None) {
552 globals = PyEval_GetGlobals();
553 if (locals == Py_None)
554 locals = PyEval_GetLocals();
556 else if (locals == Py_None)
557 locals = globals;
558 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
559 if (PyDict_SetItemString(globals, "__builtins__",
560 PyEval_GetBuiltins()) != 0)
561 return NULL;
564 exists = 0;
565 /* Test for existence or directory. */
566 #if defined(PLAN9)
568 Dir *d;
570 if ((d = dirstat(filename))!=nil) {
571 if(d->mode & DMDIR)
572 werrstr("is a directory");
573 else
574 exists = 1;
575 free(d);
578 #elif defined(RISCOS)
579 if (object_exists(filename)) {
580 if (isdir(filename))
581 errno = EISDIR;
582 else
583 exists = 1;
585 #else /* standard Posix */
587 struct stat s;
588 if (stat(filename, &s) == 0) {
589 if (S_ISDIR(s.st_mode))
590 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
591 errno = EOS2ERR;
592 # else
593 errno = EISDIR;
594 # endif
595 else
596 exists = 1;
599 #endif
601 if (exists) {
602 Py_BEGIN_ALLOW_THREADS
603 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
604 Py_END_ALLOW_THREADS
606 if (fp == NULL) {
607 exists = 0;
611 if (!exists) {
612 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
613 return NULL;
615 cf.cf_flags = 0;
616 if (PyEval_MergeCompilerFlags(&cf))
617 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
618 locals, 1, &cf);
619 else
620 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
621 locals, 1);
622 return res;
625 PyDoc_STRVAR(execfile_doc,
626 "execfile(filename[, globals[, locals]])\n\
628 Read and execute a Python script from a file.\n\
629 The globals and locals are dictionaries, defaulting to the current\n\
630 globals and locals. If only globals is given, locals defaults to it.");
633 static PyObject *
634 builtin_getattr(PyObject *self, PyObject *args)
636 PyObject *v, *result, *dflt = NULL;
637 PyObject *name;
639 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
640 return NULL;
641 #ifdef Py_USING_UNICODE
642 if (PyUnicode_Check(name)) {
643 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
644 if (name == NULL)
645 return NULL;
647 #endif
649 if (!PyString_Check(name)) {
650 PyErr_SetString(PyExc_TypeError,
651 "getattr(): attribute name must be string");
652 return NULL;
654 result = PyObject_GetAttr(v, name);
655 if (result == NULL && dflt != NULL &&
656 PyErr_ExceptionMatches(PyExc_AttributeError))
658 PyErr_Clear();
659 Py_INCREF(dflt);
660 result = dflt;
662 return result;
665 PyDoc_STRVAR(getattr_doc,
666 "getattr(object, name[, default]) -> value\n\
668 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
669 When a default argument is given, it is returned when the attribute doesn't\n\
670 exist; without it, an exception is raised in that case.");
673 static PyObject *
674 builtin_globals(PyObject *self)
676 PyObject *d;
678 d = PyEval_GetGlobals();
679 Py_INCREF(d);
680 return d;
683 PyDoc_STRVAR(globals_doc,
684 "globals() -> dictionary\n\
686 Return the dictionary containing the current scope's global variables.");
689 static PyObject *
690 builtin_hasattr(PyObject *self, PyObject *args)
692 PyObject *v;
693 PyObject *name;
695 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
696 return NULL;
697 #ifdef Py_USING_UNICODE
698 if (PyUnicode_Check(name)) {
699 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
700 if (name == NULL)
701 return NULL;
703 #endif
705 if (!PyString_Check(name)) {
706 PyErr_SetString(PyExc_TypeError,
707 "hasattr(): attribute name must be string");
708 return NULL;
710 v = PyObject_GetAttr(v, name);
711 if (v == NULL) {
712 PyErr_Clear();
713 Py_INCREF(Py_False);
714 return Py_False;
716 Py_DECREF(v);
717 Py_INCREF(Py_True);
718 return Py_True;
721 PyDoc_STRVAR(hasattr_doc,
722 "hasattr(object, name) -> bool\n\
724 Return whether the object has an attribute with the given name.\n\
725 (This is done by calling getattr(object, name) and catching exceptions.)");
728 static PyObject *
729 builtin_id(PyObject *self, PyObject *v)
731 return PyLong_FromVoidPtr(v);
734 PyDoc_STRVAR(id_doc,
735 "id(object) -> integer\n\
737 Return the identity of an object. This is guaranteed to be unique among\n\
738 simultaneously existing objects. (Hint: it's the object's memory address.)");
741 static PyObject *
742 builtin_map(PyObject *self, PyObject *args)
744 typedef struct {
745 PyObject *it; /* the iterator object */
746 int saw_StopIteration; /* bool: did the iterator end? */
747 } sequence;
749 PyObject *func, *result;
750 sequence *seqs = NULL, *sqp;
751 int n, len;
752 register int i, j;
754 n = PyTuple_Size(args);
755 if (n < 2) {
756 PyErr_SetString(PyExc_TypeError,
757 "map() requires at least two args");
758 return NULL;
761 func = PyTuple_GetItem(args, 0);
762 n--;
764 if (func == Py_None && n == 1) {
765 /* map(None, S) is the same as list(S). */
766 return PySequence_List(PyTuple_GetItem(args, 1));
769 /* Get space for sequence descriptors. Must NULL out the iterator
770 * pointers so that jumping to Fail_2 later doesn't see trash.
772 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
773 PyErr_NoMemory();
774 return NULL;
776 for (i = 0; i < n; ++i) {
777 seqs[i].it = (PyObject*)NULL;
778 seqs[i].saw_StopIteration = 0;
781 /* Do a first pass to obtain iterators for the arguments, and set len
782 * to the largest of their lengths.
784 len = 0;
785 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
786 PyObject *curseq;
787 int curlen;
789 /* Get iterator. */
790 curseq = PyTuple_GetItem(args, i+1);
791 sqp->it = PyObject_GetIter(curseq);
792 if (sqp->it == NULL) {
793 static char errmsg[] =
794 "argument %d to map() must support iteration";
795 char errbuf[sizeof(errmsg) + 25];
796 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
797 PyErr_SetString(PyExc_TypeError, errbuf);
798 goto Fail_2;
801 /* Update len. */
802 curlen = PyObject_Size(curseq);
803 if (curlen < 0) {
804 PyErr_Clear();
805 curlen = 8; /* arbitrary */
807 if (curlen > len)
808 len = curlen;
811 /* Get space for the result list. */
812 if ((result = (PyObject *) PyList_New(len)) == NULL)
813 goto Fail_2;
815 /* Iterate over the sequences until all have stopped. */
816 for (i = 0; ; ++i) {
817 PyObject *alist, *item=NULL, *value;
818 int numactive = 0;
820 if (func == Py_None && n == 1)
821 alist = NULL;
822 else if ((alist = PyTuple_New(n)) == NULL)
823 goto Fail_1;
825 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
826 if (sqp->saw_StopIteration) {
827 Py_INCREF(Py_None);
828 item = Py_None;
830 else {
831 item = PyIter_Next(sqp->it);
832 if (item)
833 ++numactive;
834 else {
835 if (PyErr_Occurred()) {
836 Py_XDECREF(alist);
837 goto Fail_1;
839 Py_INCREF(Py_None);
840 item = Py_None;
841 sqp->saw_StopIteration = 1;
844 if (alist)
845 PyTuple_SET_ITEM(alist, j, item);
846 else
847 break;
850 if (!alist)
851 alist = item;
853 if (numactive == 0) {
854 Py_DECREF(alist);
855 break;
858 if (func == Py_None)
859 value = alist;
860 else {
861 value = PyEval_CallObject(func, alist);
862 Py_DECREF(alist);
863 if (value == NULL)
864 goto Fail_1;
866 if (i >= len) {
867 int status = PyList_Append(result, value);
868 Py_DECREF(value);
869 if (status < 0)
870 goto Fail_1;
872 else if (PyList_SetItem(result, i, value) < 0)
873 goto Fail_1;
876 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
877 goto Fail_1;
879 goto Succeed;
881 Fail_1:
882 Py_DECREF(result);
883 Fail_2:
884 result = NULL;
885 Succeed:
886 assert(seqs);
887 for (i = 0; i < n; ++i)
888 Py_XDECREF(seqs[i].it);
889 PyMem_DEL(seqs);
890 return result;
893 PyDoc_STRVAR(map_doc,
894 "map(function, sequence[, sequence, ...]) -> list\n\
896 Return a list of the results of applying the function to the items of\n\
897 the argument sequence(s). If more than one sequence is given, the\n\
898 function is called with an argument list consisting of the corresponding\n\
899 item of each sequence, substituting None for missing values when not all\n\
900 sequences have the same length. If the function is None, return a list of\n\
901 the items of the sequence (or a list of tuples if more than one sequence).");
904 static PyObject *
905 builtin_setattr(PyObject *self, PyObject *args)
907 PyObject *v;
908 PyObject *name;
909 PyObject *value;
911 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
912 return NULL;
913 if (PyObject_SetAttr(v, name, value) != 0)
914 return NULL;
915 Py_INCREF(Py_None);
916 return Py_None;
919 PyDoc_STRVAR(setattr_doc,
920 "setattr(object, name, value)\n\
922 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
923 ``x.y = v''.");
926 static PyObject *
927 builtin_delattr(PyObject *self, PyObject *args)
929 PyObject *v;
930 PyObject *name;
932 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
933 return NULL;
934 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
935 return NULL;
936 Py_INCREF(Py_None);
937 return Py_None;
940 PyDoc_STRVAR(delattr_doc,
941 "delattr(object, name)\n\
943 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
944 ``del x.y''.");
947 static PyObject *
948 builtin_hash(PyObject *self, PyObject *v)
950 long x;
952 x = PyObject_Hash(v);
953 if (x == -1)
954 return NULL;
955 return PyInt_FromLong(x);
958 PyDoc_STRVAR(hash_doc,
959 "hash(object) -> integer\n\
961 Return a hash value for the object. Two objects with the same value have\n\
962 the same hash value. The reverse is not necessarily true, but likely.");
965 static PyObject *
966 builtin_hex(PyObject *self, PyObject *v)
968 PyNumberMethods *nb;
969 PyObject *res;
971 if ((nb = v->ob_type->tp_as_number) == NULL ||
972 nb->nb_hex == NULL) {
973 PyErr_SetString(PyExc_TypeError,
974 "hex() argument can't be converted to hex");
975 return NULL;
977 res = (*nb->nb_hex)(v);
978 if (res && !PyString_Check(res)) {
979 PyErr_Format(PyExc_TypeError,
980 "__hex__ returned non-string (type %.200s)",
981 res->ob_type->tp_name);
982 Py_DECREF(res);
983 return NULL;
985 return res;
988 PyDoc_STRVAR(hex_doc,
989 "hex(number) -> string\n\
991 Return the hexadecimal representation of an integer or long integer.");
994 static PyObject *builtin_raw_input(PyObject *, PyObject *);
996 static PyObject *
997 builtin_input(PyObject *self, PyObject *args)
999 PyObject *line;
1000 char *str;
1001 PyObject *res;
1002 PyObject *globals, *locals;
1003 PyCompilerFlags cf;
1005 line = builtin_raw_input(self, args);
1006 if (line == NULL)
1007 return line;
1008 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1009 return NULL;
1010 while (*str == ' ' || *str == '\t')
1011 str++;
1012 globals = PyEval_GetGlobals();
1013 locals = PyEval_GetLocals();
1014 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1015 if (PyDict_SetItemString(globals, "__builtins__",
1016 PyEval_GetBuiltins()) != 0)
1017 return NULL;
1019 cf.cf_flags = 0;
1020 PyEval_MergeCompilerFlags(&cf);
1021 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1022 Py_DECREF(line);
1023 return res;
1026 PyDoc_STRVAR(input_doc,
1027 "input([prompt]) -> value\n\
1029 Equivalent to eval(raw_input(prompt)).");
1032 static PyObject *
1033 builtin_intern(PyObject *self, PyObject *args)
1035 PyObject *s;
1036 if (!PyArg_ParseTuple(args, "S:intern", &s))
1037 return NULL;
1038 if (!PyString_CheckExact(s)) {
1039 PyErr_SetString(PyExc_TypeError,
1040 "can't intern subclass of string");
1041 return NULL;
1043 Py_INCREF(s);
1044 PyString_InternInPlace(&s);
1045 return s;
1048 PyDoc_STRVAR(intern_doc,
1049 "intern(string) -> string\n\
1051 ``Intern'' the given string. This enters the string in the (global)\n\
1052 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1053 Return the string itself or the previously interned string object with the\n\
1054 same value.");
1057 static PyObject *
1058 builtin_iter(PyObject *self, PyObject *args)
1060 PyObject *v, *w = NULL;
1062 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1063 return NULL;
1064 if (w == NULL)
1065 return PyObject_GetIter(v);
1066 if (!PyCallable_Check(v)) {
1067 PyErr_SetString(PyExc_TypeError,
1068 "iter(v, w): v must be callable");
1069 return NULL;
1071 return PyCallIter_New(v, w);
1074 PyDoc_STRVAR(iter_doc,
1075 "iter(collection) -> iterator\n\
1076 iter(callable, sentinel) -> iterator\n\
1078 Get an iterator from an object. In the first form, the argument must\n\
1079 supply its own iterator, or be a sequence.\n\
1080 In the second form, the callable is called until it returns the sentinel.");
1083 static PyObject *
1084 builtin_len(PyObject *self, PyObject *v)
1086 long res;
1088 res = PyObject_Size(v);
1089 if (res < 0 && PyErr_Occurred())
1090 return NULL;
1091 return PyInt_FromLong(res);
1094 PyDoc_STRVAR(len_doc,
1095 "len(object) -> integer\n\
1097 Return the number of items of a sequence or mapping.");
1100 static PyObject *
1101 builtin_locals(PyObject *self)
1103 PyObject *d;
1105 d = PyEval_GetLocals();
1106 Py_INCREF(d);
1107 return d;
1110 PyDoc_STRVAR(locals_doc,
1111 "locals() -> dictionary\n\
1113 Update and return a dictionary containing the current scope's local variables.");
1116 static PyObject *
1117 min_max(PyObject *args, int op)
1119 const char *name = op == Py_LT ? "min" : "max";
1120 PyObject *v, *w, *x, *it;
1122 if (PyTuple_Size(args) > 1)
1123 v = args;
1124 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1125 return NULL;
1127 it = PyObject_GetIter(v);
1128 if (it == NULL)
1129 return NULL;
1131 w = NULL; /* the result */
1132 for (;;) {
1133 x = PyIter_Next(it);
1134 if (x == NULL) {
1135 if (PyErr_Occurred()) {
1136 Py_XDECREF(w);
1137 Py_DECREF(it);
1138 return NULL;
1140 break;
1143 if (w == NULL)
1144 w = x;
1145 else {
1146 int cmp = PyObject_RichCompareBool(x, w, op);
1147 if (cmp > 0) {
1148 Py_DECREF(w);
1149 w = x;
1151 else if (cmp < 0) {
1152 Py_DECREF(x);
1153 Py_DECREF(w);
1154 Py_DECREF(it);
1155 return NULL;
1157 else
1158 Py_DECREF(x);
1161 if (w == NULL)
1162 PyErr_Format(PyExc_ValueError,
1163 "%s() arg is an empty sequence", name);
1164 Py_DECREF(it);
1165 return w;
1168 static PyObject *
1169 builtin_min(PyObject *self, PyObject *v)
1171 return min_max(v, Py_LT);
1174 PyDoc_STRVAR(min_doc,
1175 "min(sequence) -> value\n\
1176 min(a, b, c, ...) -> value\n\
1178 With a single sequence argument, return its smallest item.\n\
1179 With two or more arguments, return the smallest argument.");
1182 static PyObject *
1183 builtin_max(PyObject *self, PyObject *v)
1185 return min_max(v, Py_GT);
1188 PyDoc_STRVAR(max_doc,
1189 "max(sequence) -> value\n\
1190 max(a, b, c, ...) -> value\n\
1192 With a single sequence argument, return its largest item.\n\
1193 With two or more arguments, return the largest argument.");
1196 static PyObject *
1197 builtin_oct(PyObject *self, PyObject *v)
1199 PyNumberMethods *nb;
1200 PyObject *res;
1202 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1203 nb->nb_oct == NULL) {
1204 PyErr_SetString(PyExc_TypeError,
1205 "oct() argument can't be converted to oct");
1206 return NULL;
1208 res = (*nb->nb_oct)(v);
1209 if (res && !PyString_Check(res)) {
1210 PyErr_Format(PyExc_TypeError,
1211 "__oct__ returned non-string (type %.200s)",
1212 res->ob_type->tp_name);
1213 Py_DECREF(res);
1214 return NULL;
1216 return res;
1219 PyDoc_STRVAR(oct_doc,
1220 "oct(number) -> string\n\
1222 Return the octal representation of an integer or long integer.");
1225 static PyObject *
1226 builtin_ord(PyObject *self, PyObject* obj)
1228 long ord;
1229 int size;
1231 if (PyString_Check(obj)) {
1232 size = PyString_GET_SIZE(obj);
1233 if (size == 1) {
1234 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1235 return PyInt_FromLong(ord);
1237 #ifdef Py_USING_UNICODE
1238 } else if (PyUnicode_Check(obj)) {
1239 size = PyUnicode_GET_SIZE(obj);
1240 if (size == 1) {
1241 ord = (long)*PyUnicode_AS_UNICODE(obj);
1242 return PyInt_FromLong(ord);
1244 #endif
1245 } else {
1246 PyErr_Format(PyExc_TypeError,
1247 "ord() expected string of length 1, but " \
1248 "%.200s found", obj->ob_type->tp_name);
1249 return NULL;
1252 PyErr_Format(PyExc_TypeError,
1253 "ord() expected a character, "
1254 "but string of length %d found",
1255 size);
1256 return NULL;
1259 PyDoc_STRVAR(ord_doc,
1260 "ord(c) -> integer\n\
1262 Return the integer ordinal of a one-character string.");
1265 static PyObject *
1266 builtin_pow(PyObject *self, PyObject *args)
1268 PyObject *v, *w, *z = Py_None;
1270 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1271 return NULL;
1272 return PyNumber_Power(v, w, z);
1275 PyDoc_STRVAR(pow_doc,
1276 "pow(x, y[, z]) -> number\n\
1278 With two arguments, equivalent to x**y. With three arguments,\n\
1279 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1283 /* Return number of items in range (lo, hi, step), when arguments are
1284 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1285 * & only if the true value is too large to fit in a signed long.
1286 * Arguments MUST return 1 with either PyInt_Check() or
1287 * PyLong_Check(). Return -1 when there is an error.
1289 static long
1290 get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1292 /* -------------------------------------------------------------
1293 Algorithm is equal to that of get_len_of_range(), but it operates
1294 on PyObjects (which are assumed to be PyLong or PyInt objects).
1295 ---------------------------------------------------------------*/
1296 long n;
1297 PyObject *diff = NULL;
1298 PyObject *one = NULL;
1299 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1300 /* holds sub-expression evaluations */
1302 /* if (lo >= hi), return length of 0. */
1303 if (PyObject_Compare(lo, hi) >= 0)
1304 return 0;
1306 if ((one = PyLong_FromLong(1L)) == NULL)
1307 goto Fail;
1309 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1310 goto Fail;
1312 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1313 goto Fail;
1315 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1316 goto Fail;
1318 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1319 goto Fail;
1321 n = PyLong_AsLong(tmp3);
1322 if (PyErr_Occurred()) { /* Check for Overflow */
1323 PyErr_Clear();
1324 goto Fail;
1327 Py_DECREF(tmp3);
1328 Py_DECREF(tmp2);
1329 Py_DECREF(diff);
1330 Py_DECREF(tmp1);
1331 Py_DECREF(one);
1332 return n;
1334 Fail:
1335 Py_XDECREF(tmp3);
1336 Py_XDECREF(tmp2);
1337 Py_XDECREF(diff);
1338 Py_XDECREF(tmp1);
1339 Py_XDECREF(one);
1340 return -1;
1343 /* An extension of builtin_range() that handles the case when PyLong
1344 * arguments are given. */
1345 static PyObject *
1346 handle_range_longs(PyObject *self, PyObject *args)
1348 PyObject *ilow;
1349 PyObject *ihigh = NULL;
1350 PyObject *istep = NULL;
1352 PyObject *curnum = NULL;
1353 PyObject *v = NULL;
1354 long bign;
1355 int i, n;
1356 int cmp_result;
1358 PyObject *zero = PyLong_FromLong(0);
1360 if (zero == NULL)
1361 return NULL;
1363 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1364 Py_DECREF(zero);
1365 return NULL;
1368 /* Figure out which way we were called, supply defaults, and be
1369 * sure to incref everything so that the decrefs at the end
1370 * are correct.
1372 assert(ilow != NULL);
1373 if (ihigh == NULL) {
1374 /* only 1 arg -- it's the upper limit */
1375 ihigh = ilow;
1376 ilow = NULL;
1378 assert(ihigh != NULL);
1379 Py_INCREF(ihigh);
1381 /* ihigh correct now; do ilow */
1382 if (ilow == NULL)
1383 ilow = zero;
1384 Py_INCREF(ilow);
1386 /* ilow and ihigh correct now; do istep */
1387 if (istep == NULL) {
1388 istep = PyLong_FromLong(1L);
1389 if (istep == NULL)
1390 goto Fail;
1392 else {
1393 Py_INCREF(istep);
1396 if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
1397 PyErr_Format(PyExc_TypeError,
1398 "range() integer start argument expected, got %s.",
1399 ilow->ob_type->tp_name);
1400 goto Fail;
1403 if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
1404 PyErr_Format(PyExc_TypeError,
1405 "range() integer end argument expected, got %s.",
1406 ihigh->ob_type->tp_name);
1407 goto Fail;
1410 if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
1411 PyErr_Format(PyExc_TypeError,
1412 "range() integer step argument expected, got %s.",
1413 istep->ob_type->tp_name);
1414 goto Fail;
1417 if (PyObject_Cmp(istep, zero, &cmp_result) == -1)
1418 goto Fail;
1419 if (cmp_result == 0) {
1420 PyErr_SetString(PyExc_ValueError,
1421 "range() step argument must not be zero");
1422 goto Fail;
1425 if (cmp_result > 0)
1426 bign = get_len_of_range_longs(ilow, ihigh, istep);
1427 else {
1428 PyObject *neg_istep = PyNumber_Negative(istep);
1429 if (neg_istep == NULL)
1430 goto Fail;
1431 bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
1432 Py_DECREF(neg_istep);
1435 n = (int)bign;
1436 if (bign < 0 || (long)n != bign) {
1437 PyErr_SetString(PyExc_OverflowError,
1438 "range() result has too many items");
1439 goto Fail;
1442 v = PyList_New(n);
1443 if (v == NULL)
1444 goto Fail;
1446 curnum = ilow;
1447 Py_INCREF(curnum);
1449 for (i = 0; i < n; i++) {
1450 PyObject *w = PyNumber_Long(curnum);
1451 PyObject *tmp_num;
1452 if (w == NULL)
1453 goto Fail;
1455 PyList_SET_ITEM(v, i, w);
1457 tmp_num = PyNumber_Add(curnum, istep);
1458 if (tmp_num == NULL)
1459 goto Fail;
1461 Py_DECREF(curnum);
1462 curnum = tmp_num;
1464 Py_DECREF(ilow);
1465 Py_DECREF(ihigh);
1466 Py_DECREF(istep);
1467 Py_DECREF(zero);
1468 Py_DECREF(curnum);
1469 return v;
1471 Fail:
1472 Py_DECREF(ilow);
1473 Py_DECREF(ihigh);
1474 Py_XDECREF(istep);
1475 Py_DECREF(zero);
1476 Py_XDECREF(curnum);
1477 Py_XDECREF(v);
1478 return NULL;
1481 /* Return number of items in range/xrange (lo, hi, step). step > 0
1482 * required. Return a value < 0 if & only if the true value is too
1483 * large to fit in a signed long.
1485 static long
1486 get_len_of_range(long lo, long hi, long step)
1488 /* -------------------------------------------------------------
1489 If lo >= hi, the range is empty.
1490 Else if n values are in the range, the last one is
1491 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1492 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1493 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1494 the RHS is non-negative and so truncation is the same as the
1495 floor. Letting M be the largest positive long, the worst case
1496 for the RHS numerator is hi=M, lo=-M-1, and then
1497 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1498 precision to compute the RHS exactly.
1499 ---------------------------------------------------------------*/
1500 long n = 0;
1501 if (lo < hi) {
1502 unsigned long uhi = (unsigned long)hi;
1503 unsigned long ulo = (unsigned long)lo;
1504 unsigned long diff = uhi - ulo - 1;
1505 n = (long)(diff / (unsigned long)step + 1);
1507 return n;
1510 static PyObject *
1511 builtin_range(PyObject *self, PyObject *args)
1513 long ilow = 0, ihigh = 0, istep = 1;
1514 long bign;
1515 int i, n;
1517 PyObject *v;
1519 if (PyTuple_Size(args) <= 1) {
1520 if (!PyArg_ParseTuple(args,
1521 "l;range() requires 1-3 int arguments",
1522 &ihigh)) {
1523 PyErr_Clear();
1524 return handle_range_longs(self, args);
1527 else {
1528 if (!PyArg_ParseTuple(args,
1529 "ll|l;range() requires 1-3 int arguments",
1530 &ilow, &ihigh, &istep)) {
1531 PyErr_Clear();
1532 return handle_range_longs(self, args);
1535 if (istep == 0) {
1536 PyErr_SetString(PyExc_ValueError,
1537 "range() step argument must not be zero");
1538 return NULL;
1540 if (istep > 0)
1541 bign = get_len_of_range(ilow, ihigh, istep);
1542 else
1543 bign = get_len_of_range(ihigh, ilow, -istep);
1544 n = (int)bign;
1545 if (bign < 0 || (long)n != bign) {
1546 PyErr_SetString(PyExc_OverflowError,
1547 "range() result has too many items");
1548 return NULL;
1550 v = PyList_New(n);
1551 if (v == NULL)
1552 return NULL;
1553 for (i = 0; i < n; i++) {
1554 PyObject *w = PyInt_FromLong(ilow);
1555 if (w == NULL) {
1556 Py_DECREF(v);
1557 return NULL;
1559 PyList_SET_ITEM(v, i, w);
1560 ilow += istep;
1562 return v;
1565 PyDoc_STRVAR(range_doc,
1566 "range([start,] stop[, step]) -> list of integers\n\
1568 Return a list containing an arithmetic progression of integers.\n\
1569 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1570 When step is given, it specifies the increment (or decrement).\n\
1571 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1572 These are exactly the valid indices for a list of 4 elements.");
1575 static PyObject *
1576 builtin_raw_input(PyObject *self, PyObject *args)
1578 PyObject *v = NULL;
1579 PyObject *fin = PySys_GetObject("stdin");
1580 PyObject *fout = PySys_GetObject("stdout");
1582 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
1583 return NULL;
1585 if (fin == NULL) {
1586 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
1587 return NULL;
1589 if (fout == NULL) {
1590 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
1591 return NULL;
1593 if (PyFile_SoftSpace(fout, 0)) {
1594 if (PyFile_WriteString(" ", fout) != 0)
1595 return NULL;
1597 if (PyFile_Check(fin) && PyFile_Check(fout)
1598 && isatty(fileno(PyFile_AsFile(fin)))
1599 && isatty(fileno(PyFile_AsFile(fout)))) {
1600 PyObject *po;
1601 char *prompt;
1602 char *s;
1603 PyObject *result;
1604 if (v != NULL) {
1605 po = PyObject_Str(v);
1606 if (po == NULL)
1607 return NULL;
1608 prompt = PyString_AsString(po);
1609 if (prompt == NULL)
1610 return NULL;
1612 else {
1613 po = NULL;
1614 prompt = "";
1616 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
1617 prompt);
1618 Py_XDECREF(po);
1619 if (s == NULL) {
1620 if (!PyErr_Occurred())
1621 PyErr_SetNone(PyExc_KeyboardInterrupt);
1622 return NULL;
1624 if (*s == '\0') {
1625 PyErr_SetNone(PyExc_EOFError);
1626 result = NULL;
1628 else { /* strip trailing '\n' */
1629 size_t len = strlen(s);
1630 if (len > INT_MAX) {
1631 PyErr_SetString(PyExc_OverflowError,
1632 "[raw_]input: input too long");
1633 result = NULL;
1635 else {
1636 result = PyString_FromStringAndSize(s,
1637 (int)(len-1));
1640 PyMem_FREE(s);
1641 return result;
1643 if (v != NULL) {
1644 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
1645 return NULL;
1647 return PyFile_GetLine(fin, -1);
1650 PyDoc_STRVAR(raw_input_doc,
1651 "raw_input([prompt]) -> string\n\
1653 Read a string from standard input. The trailing newline is stripped.\n\
1654 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1655 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1656 is printed without a trailing newline before reading.");
1659 static PyObject *
1660 builtin_reduce(PyObject *self, PyObject *args)
1662 PyObject *seq, *func, *result = NULL, *it;
1664 if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
1665 return NULL;
1666 if (result != NULL)
1667 Py_INCREF(result);
1669 it = PyObject_GetIter(seq);
1670 if (it == NULL) {
1671 PyErr_SetString(PyExc_TypeError,
1672 "reduce() arg 2 must support iteration");
1673 Py_XDECREF(result);
1674 return NULL;
1677 if ((args = PyTuple_New(2)) == NULL)
1678 goto Fail;
1680 for (;;) {
1681 PyObject *op2;
1683 if (args->ob_refcnt > 1) {
1684 Py_DECREF(args);
1685 if ((args = PyTuple_New(2)) == NULL)
1686 goto Fail;
1689 op2 = PyIter_Next(it);
1690 if (op2 == NULL) {
1691 if (PyErr_Occurred())
1692 goto Fail;
1693 break;
1696 if (result == NULL)
1697 result = op2;
1698 else {
1699 PyTuple_SetItem(args, 0, result);
1700 PyTuple_SetItem(args, 1, op2);
1701 if ((result = PyEval_CallObject(func, args)) == NULL)
1702 goto Fail;
1706 Py_DECREF(args);
1708 if (result == NULL)
1709 PyErr_SetString(PyExc_TypeError,
1710 "reduce() of empty sequence with no initial value");
1712 Py_DECREF(it);
1713 return result;
1715 Fail:
1716 Py_XDECREF(args);
1717 Py_XDECREF(result);
1718 Py_DECREF(it);
1719 return NULL;
1722 PyDoc_STRVAR(reduce_doc,
1723 "reduce(function, sequence[, initial]) -> value\n\
1725 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1726 from left to right, so as to reduce the sequence to a single value.\n\
1727 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1728 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1729 of the sequence in the calculation, and serves as a default when the\n\
1730 sequence is empty.");
1733 static PyObject *
1734 builtin_reload(PyObject *self, PyObject *v)
1736 return PyImport_ReloadModule(v);
1739 PyDoc_STRVAR(reload_doc,
1740 "reload(module) -> module\n\
1742 Reload the module. The module must have been successfully imported before.");
1745 static PyObject *
1746 builtin_repr(PyObject *self, PyObject *v)
1748 return PyObject_Repr(v);
1751 PyDoc_STRVAR(repr_doc,
1752 "repr(object) -> string\n\
1754 Return the canonical string representation of the object.\n\
1755 For most object types, eval(repr(object)) == object.");
1758 static PyObject *
1759 builtin_round(PyObject *self, PyObject *args)
1761 double x;
1762 double f;
1763 int ndigits = 0;
1764 int i;
1766 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1767 return NULL;
1768 f = 1.0;
1769 i = abs(ndigits);
1770 while (--i >= 0)
1771 f = f*10.0;
1772 if (ndigits < 0)
1773 x /= f;
1774 else
1775 x *= f;
1776 if (x >= 0.0)
1777 x = floor(x + 0.5);
1778 else
1779 x = ceil(x - 0.5);
1780 if (ndigits < 0)
1781 x *= f;
1782 else
1783 x /= f;
1784 return PyFloat_FromDouble(x);
1787 PyDoc_STRVAR(round_doc,
1788 "round(number[, ndigits]) -> floating point number\n\
1790 Round a number to a given precision in decimal digits (default 0 digits).\n\
1791 This always returns a floating point number. Precision may be negative.");
1793 static PyObject *
1794 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1796 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1797 PyObject *callable;
1798 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
1799 long reverse;
1801 if (args != NULL) {
1802 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1803 kwlist, &seq, &compare, &keyfunc, &reverse))
1804 return NULL;
1807 newlist = PySequence_List(seq);
1808 if (newlist == NULL)
1809 return NULL;
1811 callable = PyObject_GetAttrString(newlist, "sort");
1812 if (callable == NULL) {
1813 Py_DECREF(newlist);
1814 return NULL;
1817 newargs = PyTuple_GetSlice(args, 1, 4);
1818 if (newargs == NULL) {
1819 Py_DECREF(newlist);
1820 Py_DECREF(callable);
1821 return NULL;
1824 v = PyObject_Call(callable, newargs, kwds);
1825 Py_DECREF(newargs);
1826 Py_DECREF(callable);
1827 if (v == NULL) {
1828 Py_DECREF(newlist);
1829 return NULL;
1831 Py_DECREF(v);
1832 return newlist;
1835 PyDoc_STRVAR(sorted_doc,
1836 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
1838 static PyObject *
1839 builtin_vars(PyObject *self, PyObject *args)
1841 PyObject *v = NULL;
1842 PyObject *d;
1844 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1845 return NULL;
1846 if (v == NULL) {
1847 d = PyEval_GetLocals();
1848 if (d == NULL) {
1849 if (!PyErr_Occurred())
1850 PyErr_SetString(PyExc_SystemError,
1851 "vars(): no locals!?");
1853 else
1854 Py_INCREF(d);
1856 else {
1857 d = PyObject_GetAttrString(v, "__dict__");
1858 if (d == NULL) {
1859 PyErr_SetString(PyExc_TypeError,
1860 "vars() argument must have __dict__ attribute");
1861 return NULL;
1864 return d;
1867 PyDoc_STRVAR(vars_doc,
1868 "vars([object]) -> dictionary\n\
1870 Without arguments, equivalent to locals().\n\
1871 With an argument, equivalent to object.__dict__.");
1874 static PyObject*
1875 builtin_sum(PyObject *self, PyObject *args)
1877 PyObject *seq;
1878 PyObject *result = NULL;
1879 PyObject *temp, *item, *iter;
1881 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1882 return NULL;
1884 iter = PyObject_GetIter(seq);
1885 if (iter == NULL)
1886 return NULL;
1888 if (result == NULL) {
1889 result = PyInt_FromLong(0);
1890 if (result == NULL) {
1891 Py_DECREF(iter);
1892 return NULL;
1894 } else {
1895 /* reject string values for 'start' parameter */
1896 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
1897 PyErr_SetString(PyExc_TypeError,
1898 "sum() can't sum strings [use ''.join(seq) instead]");
1899 Py_DECREF(iter);
1900 return NULL;
1902 Py_INCREF(result);
1905 for(;;) {
1906 item = PyIter_Next(iter);
1907 if (item == NULL) {
1908 /* error, or end-of-sequence */
1909 if (PyErr_Occurred()) {
1910 Py_DECREF(result);
1911 result = NULL;
1913 break;
1915 temp = PyNumber_Add(result, item);
1916 Py_DECREF(result);
1917 Py_DECREF(item);
1918 result = temp;
1919 if (result == NULL)
1920 break;
1922 Py_DECREF(iter);
1923 return result;
1926 PyDoc_STRVAR(sum_doc,
1927 "sum(sequence, start=0) -> value\n\
1929 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
1930 of parameter 'start'. When the sequence is empty, returns start.");
1933 static PyObject *
1934 builtin_isinstance(PyObject *self, PyObject *args)
1936 PyObject *inst;
1937 PyObject *cls;
1938 int retval;
1940 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
1941 return NULL;
1943 retval = PyObject_IsInstance(inst, cls);
1944 if (retval < 0)
1945 return NULL;
1946 return PyBool_FromLong(retval);
1949 PyDoc_STRVAR(isinstance_doc,
1950 "isinstance(object, class-or-type-or-tuple) -> bool\n\
1952 Return whether an object is an instance of a class or of a subclass thereof.\n\
1953 With a type as second argument, return whether that is the object's type.\n\
1954 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
1955 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
1958 static PyObject *
1959 builtin_issubclass(PyObject *self, PyObject *args)
1961 PyObject *derived;
1962 PyObject *cls;
1963 int retval;
1965 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
1966 return NULL;
1968 retval = PyObject_IsSubclass(derived, cls);
1969 if (retval < 0)
1970 return NULL;
1971 return PyBool_FromLong(retval);
1974 PyDoc_STRVAR(issubclass_doc,
1975 "issubclass(C, B) -> bool\n\
1977 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1978 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1979 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
1982 static PyObject*
1983 builtin_zip(PyObject *self, PyObject *args)
1985 PyObject *ret;
1986 const int itemsize = PySequence_Length(args);
1987 int i;
1988 PyObject *itlist; /* tuple of iterators */
1989 int len; /* guess at result length */
1991 if (itemsize == 0)
1992 return PyList_New(0);
1994 /* args must be a tuple */
1995 assert(PyTuple_Check(args));
1997 /* Guess at result length: the shortest of the input lengths.
1998 If some argument refuses to say, we refuse to guess too, lest
1999 an argument like xrange(sys.maxint) lead us astray.*/
2000 len = -1; /* unknown */
2001 for (i = 0; i < itemsize; ++i) {
2002 PyObject *item = PyTuple_GET_ITEM(args, i);
2003 int thislen = PyObject_Size(item);
2004 if (thislen < 0) {
2005 PyErr_Clear();
2006 len = -1;
2007 break;
2009 else if (len < 0 || thislen < len)
2010 len = thislen;
2013 /* allocate result list */
2014 if (len < 0)
2015 len = 10; /* arbitrary */
2016 if ((ret = PyList_New(len)) == NULL)
2017 return NULL;
2019 /* obtain iterators */
2020 itlist = PyTuple_New(itemsize);
2021 if (itlist == NULL)
2022 goto Fail_ret;
2023 for (i = 0; i < itemsize; ++i) {
2024 PyObject *item = PyTuple_GET_ITEM(args, i);
2025 PyObject *it = PyObject_GetIter(item);
2026 if (it == NULL) {
2027 if (PyErr_ExceptionMatches(PyExc_TypeError))
2028 PyErr_Format(PyExc_TypeError,
2029 "zip argument #%d must support iteration",
2030 i+1);
2031 goto Fail_ret_itlist;
2033 PyTuple_SET_ITEM(itlist, i, it);
2036 /* build result into ret list */
2037 for (i = 0; ; ++i) {
2038 int j;
2039 PyObject *next = PyTuple_New(itemsize);
2040 if (!next)
2041 goto Fail_ret_itlist;
2043 for (j = 0; j < itemsize; j++) {
2044 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2045 PyObject *item = PyIter_Next(it);
2046 if (!item) {
2047 if (PyErr_Occurred()) {
2048 Py_DECREF(ret);
2049 ret = NULL;
2051 Py_DECREF(next);
2052 Py_DECREF(itlist);
2053 goto Done;
2055 PyTuple_SET_ITEM(next, j, item);
2058 if (i < len)
2059 PyList_SET_ITEM(ret, i, next);
2060 else {
2061 int status = PyList_Append(ret, next);
2062 Py_DECREF(next);
2063 ++len;
2064 if (status < 0)
2065 goto Fail_ret_itlist;
2069 Done:
2070 if (ret != NULL && i < len) {
2071 /* The list is too big. */
2072 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2073 return NULL;
2075 return ret;
2077 Fail_ret_itlist:
2078 Py_DECREF(itlist);
2079 Fail_ret:
2080 Py_DECREF(ret);
2081 return NULL;
2085 PyDoc_STRVAR(zip_doc,
2086 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2088 Return a list of tuples, where each tuple contains the i-th element\n\
2089 from each of the argument sequences. The returned list is truncated\n\
2090 in length to the length of the shortest argument sequence.");
2093 static PyMethodDef builtin_methods[] = {
2094 {"__import__", builtin___import__, METH_VARARGS, import_doc},
2095 {"abs", builtin_abs, METH_O, abs_doc},
2096 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2097 {"callable", builtin_callable, METH_O, callable_doc},
2098 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2099 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2100 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2101 {"compile", builtin_compile, METH_VARARGS, compile_doc},
2102 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2103 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2104 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2105 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2106 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2107 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2108 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2109 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2110 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2111 {"hash", builtin_hash, METH_O, hash_doc},
2112 {"hex", builtin_hex, METH_O, hex_doc},
2113 {"id", builtin_id, METH_O, id_doc},
2114 {"input", builtin_input, METH_VARARGS, input_doc},
2115 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2116 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2117 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2118 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2119 {"len", builtin_len, METH_O, len_doc},
2120 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2121 {"map", builtin_map, METH_VARARGS, map_doc},
2122 {"max", builtin_max, METH_VARARGS, max_doc},
2123 {"min", builtin_min, METH_VARARGS, min_doc},
2124 {"oct", builtin_oct, METH_O, oct_doc},
2125 {"ord", builtin_ord, METH_O, ord_doc},
2126 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2127 {"range", builtin_range, METH_VARARGS, range_doc},
2128 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2129 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2130 {"reload", builtin_reload, METH_O, reload_doc},
2131 {"repr", builtin_repr, METH_O, repr_doc},
2132 {"round", builtin_round, METH_VARARGS, round_doc},
2133 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2134 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2135 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2136 #ifdef Py_USING_UNICODE
2137 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
2138 #endif
2139 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2140 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2141 {NULL, NULL},
2144 PyDoc_STRVAR(builtin_doc,
2145 "Built-in functions, exceptions, and other objects.\n\
2147 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2149 PyObject *
2150 _PyBuiltin_Init(void)
2152 PyObject *mod, *dict, *debug;
2153 mod = Py_InitModule4("__builtin__", builtin_methods,
2154 builtin_doc, (PyObject *)NULL,
2155 PYTHON_API_VERSION);
2156 if (mod == NULL)
2157 return NULL;
2158 dict = PyModule_GetDict(mod);
2160 #ifdef Py_TRACE_REFS
2161 /* __builtin__ exposes a number of statically allocated objects
2162 * that, before this code was added in 2.3, never showed up in
2163 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2164 * result, programs leaking references to None and False (etc)
2165 * couldn't be diagnosed by examining sys.getobjects(0).
2167 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2168 #else
2169 #define ADD_TO_ALL(OBJECT) (void)0
2170 #endif
2172 #define SETBUILTIN(NAME, OBJECT) \
2173 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2174 return NULL; \
2175 ADD_TO_ALL(OBJECT)
2177 SETBUILTIN("None", Py_None);
2178 SETBUILTIN("Ellipsis", Py_Ellipsis);
2179 SETBUILTIN("NotImplemented", Py_NotImplemented);
2180 SETBUILTIN("False", Py_False);
2181 SETBUILTIN("True", Py_True);
2182 SETBUILTIN("basestring", &PyBaseString_Type);
2183 SETBUILTIN("bool", &PyBool_Type);
2184 SETBUILTIN("buffer", &PyBuffer_Type);
2185 SETBUILTIN("classmethod", &PyClassMethod_Type);
2186 #ifndef WITHOUT_COMPLEX
2187 SETBUILTIN("complex", &PyComplex_Type);
2188 #endif
2189 SETBUILTIN("dict", &PyDict_Type);
2190 SETBUILTIN("enumerate", &PyEnum_Type);
2191 SETBUILTIN("float", &PyFloat_Type);
2192 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2193 SETBUILTIN("property", &PyProperty_Type);
2194 SETBUILTIN("int", &PyInt_Type);
2195 SETBUILTIN("list", &PyList_Type);
2196 SETBUILTIN("long", &PyLong_Type);
2197 SETBUILTIN("object", &PyBaseObject_Type);
2198 SETBUILTIN("reversed", &PyReversed_Type);
2199 SETBUILTIN("set", &PySet_Type);
2200 SETBUILTIN("slice", &PySlice_Type);
2201 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2202 SETBUILTIN("str", &PyString_Type);
2203 SETBUILTIN("super", &PySuper_Type);
2204 SETBUILTIN("tuple", &PyTuple_Type);
2205 SETBUILTIN("type", &PyType_Type);
2206 SETBUILTIN("xrange", &PyRange_Type);
2208 /* Note that open() is just an alias of file(). */
2209 SETBUILTIN("open", &PyFile_Type);
2210 SETBUILTIN("file", &PyFile_Type);
2211 #ifdef Py_USING_UNICODE
2212 SETBUILTIN("unicode", &PyUnicode_Type);
2213 #endif
2214 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2215 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2216 Py_XDECREF(debug);
2217 return NULL;
2219 Py_XDECREF(debug);
2221 return mod;
2222 #undef ADD_TO_ALL
2223 #undef SETBUILTIN
2226 /* Helper for filter(): filter a tuple through a function */
2228 static PyObject *
2229 filtertuple(PyObject *func, PyObject *tuple)
2231 PyObject *result;
2232 register int i, j;
2233 int len = PyTuple_Size(tuple);
2235 if (len == 0) {
2236 if (PyTuple_CheckExact(tuple))
2237 Py_INCREF(tuple);
2238 else
2239 tuple = PyTuple_New(0);
2240 return tuple;
2243 if ((result = PyTuple_New(len)) == NULL)
2244 return NULL;
2246 for (i = j = 0; i < len; ++i) {
2247 PyObject *item, *good;
2248 int ok;
2250 if (tuple->ob_type->tp_as_sequence &&
2251 tuple->ob_type->tp_as_sequence->sq_item) {
2252 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2253 if (item == NULL)
2254 goto Fail_1;
2255 } else {
2256 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2257 goto Fail_1;
2259 if (func == Py_None) {
2260 Py_INCREF(item);
2261 good = item;
2263 else {
2264 PyObject *arg = PyTuple_Pack(1, item);
2265 if (arg == NULL) {
2266 Py_DECREF(item);
2267 goto Fail_1;
2269 good = PyEval_CallObject(func, arg);
2270 Py_DECREF(arg);
2271 if (good == NULL) {
2272 Py_DECREF(item);
2273 goto Fail_1;
2276 ok = PyObject_IsTrue(good);
2277 Py_DECREF(good);
2278 if (ok) {
2279 if (PyTuple_SetItem(result, j++, item) < 0)
2280 goto Fail_1;
2282 else
2283 Py_DECREF(item);
2286 if (_PyTuple_Resize(&result, j) < 0)
2287 return NULL;
2289 return result;
2291 Fail_1:
2292 Py_DECREF(result);
2293 return NULL;
2297 /* Helper for filter(): filter a string through a function */
2299 static PyObject *
2300 filterstring(PyObject *func, PyObject *strobj)
2302 PyObject *result;
2303 register int i, j;
2304 int len = PyString_Size(strobj);
2305 int outlen = len;
2307 if (func == Py_None) {
2308 /* If it's a real string we can return the original,
2309 * as no character is ever false and __getitem__
2310 * does return this character. If it's a subclass
2311 * we must go through the __getitem__ loop */
2312 if (PyString_CheckExact(strobj)) {
2313 Py_INCREF(strobj);
2314 return strobj;
2317 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2318 return NULL;
2320 for (i = j = 0; i < len; ++i) {
2321 PyObject *item;
2322 int ok;
2324 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2325 if (item == NULL)
2326 goto Fail_1;
2327 if (func==Py_None) {
2328 ok = 1;
2329 } else {
2330 PyObject *arg, *good;
2331 arg = PyTuple_Pack(1, item);
2332 if (arg == NULL) {
2333 Py_DECREF(item);
2334 goto Fail_1;
2336 good = PyEval_CallObject(func, arg);
2337 Py_DECREF(arg);
2338 if (good == NULL) {
2339 Py_DECREF(item);
2340 goto Fail_1;
2342 ok = PyObject_IsTrue(good);
2343 Py_DECREF(good);
2345 if (ok) {
2346 int reslen;
2347 if (!PyString_Check(item)) {
2348 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2349 " __getitem__ returned different type");
2350 Py_DECREF(item);
2351 goto Fail_1;
2353 reslen = PyString_GET_SIZE(item);
2354 if (reslen == 1) {
2355 PyString_AS_STRING(result)[j++] =
2356 PyString_AS_STRING(item)[0];
2357 } else {
2358 /* do we need more space? */
2359 int need = j + reslen + len-i-1;
2360 if (need > outlen) {
2361 /* overallocate, to avoid reallocations */
2362 if (need<2*outlen)
2363 need = 2*outlen;
2364 if (_PyString_Resize(&result, need)) {
2365 Py_DECREF(item);
2366 return NULL;
2368 outlen = need;
2370 memcpy(
2371 PyString_AS_STRING(result) + j,
2372 PyString_AS_STRING(item),
2373 reslen
2375 j += reslen;
2378 Py_DECREF(item);
2381 if (j < outlen)
2382 _PyString_Resize(&result, j);
2384 return result;
2386 Fail_1:
2387 Py_DECREF(result);
2388 return NULL;
2391 #ifdef Py_USING_UNICODE
2392 /* Helper for filter(): filter a Unicode object through a function */
2394 static PyObject *
2395 filterunicode(PyObject *func, PyObject *strobj)
2397 PyObject *result;
2398 register int i, j;
2399 int len = PyUnicode_GetSize(strobj);
2400 int outlen = len;
2402 if (func == Py_None) {
2403 /* If it's a real string we can return the original,
2404 * as no character is ever false and __getitem__
2405 * does return this character. If it's a subclass
2406 * we must go through the __getitem__ loop */
2407 if (PyUnicode_CheckExact(strobj)) {
2408 Py_INCREF(strobj);
2409 return strobj;
2412 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2413 return NULL;
2415 for (i = j = 0; i < len; ++i) {
2416 PyObject *item, *arg, *good;
2417 int ok;
2419 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2420 if (item == NULL)
2421 goto Fail_1;
2422 if (func == Py_None) {
2423 ok = 1;
2424 } else {
2425 arg = PyTuple_Pack(1, item);
2426 if (arg == NULL) {
2427 Py_DECREF(item);
2428 goto Fail_1;
2430 good = PyEval_CallObject(func, arg);
2431 Py_DECREF(arg);
2432 if (good == NULL) {
2433 Py_DECREF(item);
2434 goto Fail_1;
2436 ok = PyObject_IsTrue(good);
2437 Py_DECREF(good);
2439 if (ok) {
2440 int reslen;
2441 if (!PyUnicode_Check(item)) {
2442 PyErr_SetString(PyExc_TypeError,
2443 "can't filter unicode to unicode:"
2444 " __getitem__ returned different type");
2445 Py_DECREF(item);
2446 goto Fail_1;
2448 reslen = PyUnicode_GET_SIZE(item);
2449 if (reslen == 1)
2450 PyUnicode_AS_UNICODE(result)[j++] =
2451 PyUnicode_AS_UNICODE(item)[0];
2452 else {
2453 /* do we need more space? */
2454 int need = j + reslen + len - i - 1;
2455 if (need > outlen) {
2456 /* overallocate,
2457 to avoid reallocations */
2458 if (need < 2 * outlen)
2459 need = 2 * outlen;
2460 if (PyUnicode_Resize(
2461 &result, need) < 0) {
2462 Py_DECREF(item);
2463 goto Fail_1;
2465 outlen = need;
2467 memcpy(PyUnicode_AS_UNICODE(result) + j,
2468 PyUnicode_AS_UNICODE(item),
2469 reslen*sizeof(Py_UNICODE));
2470 j += reslen;
2473 Py_DECREF(item);
2476 if (j < outlen)
2477 PyUnicode_Resize(&result, j);
2479 return result;
2481 Fail_1:
2482 Py_DECREF(result);
2483 return NULL;
2485 #endif