This commit was manufactured by cvs2svn to create tag 'r23b1-mac'.
[python/dscho.git] / Python / bltinmodule.c
blob49fcc09cfc04a1cfab40a31fabcbaf04b3616f02
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 (PyErr_Warn(PyExc_PendingDeprecationWarning,
79 "use func(*args, **kwargs) instead of "
80 "apply(func, args, kwargs)") < 0)
81 return NULL;
82 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
83 return NULL;
84 if (alist != NULL) {
85 if (!PyTuple_Check(alist)) {
86 if (!PySequence_Check(alist)) {
87 PyErr_Format(PyExc_TypeError,
88 "apply() arg 2 expected sequence, found %s",
89 alist->ob_type->tp_name);
90 return NULL;
92 t = PySequence_Tuple(alist);
93 if (t == NULL)
94 return NULL;
95 alist = t;
98 if (kwdict != NULL && !PyDict_Check(kwdict)) {
99 PyErr_Format(PyExc_TypeError,
100 "apply() arg 3 expected dictionary, found %s",
101 kwdict->ob_type->tp_name);
102 goto finally;
104 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
105 finally:
106 Py_XDECREF(t);
107 return retval;
110 PyDoc_STRVAR(apply_doc,
111 "apply(object[, args[, kwargs]]) -> value\n\
113 Call a callable object with positional arguments taken from the tuple args,\n\
114 and keyword arguments taken from the optional dictionary kwargs.\n\
115 Note that classes are callable, as are instances with a __call__() method.\n\
117 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
118 function(*args, **keywords).");
121 static PyObject *
122 builtin_callable(PyObject *self, PyObject *v)
124 return PyBool_FromLong((long)PyCallable_Check(v));
127 PyDoc_STRVAR(callable_doc,
128 "callable(object) -> bool\n\
130 Return whether the object is callable (i.e., some kind of function).\n\
131 Note that classes are callable, as are instances with a __call__() method.");
134 static PyObject *
135 builtin_filter(PyObject *self, PyObject *args)
137 PyObject *func, *seq, *result, *it, *arg;
138 int len; /* guess for result list size */
139 register int j;
141 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
142 return NULL;
144 /* Strings and tuples return a result of the same type. */
145 if (PyString_Check(seq))
146 return filterstring(func, seq);
147 #ifdef Py_USING_UNICODE
148 if (PyUnicode_Check(seq))
149 return filterunicode(func, seq);
150 #endif
151 if (PyTuple_Check(seq))
152 return filtertuple(func, seq);
154 /* Get iterator. */
155 it = PyObject_GetIter(seq);
156 if (it == NULL)
157 return NULL;
159 /* Guess a result list size. */
160 len = -1; /* unknown */
161 if (PySequence_Check(seq) &&
162 seq->ob_type->tp_as_sequence->sq_length) {
163 len = PySequence_Size(seq);
164 if (len < 0)
165 PyErr_Clear();
167 if (len < 0)
168 len = 8; /* arbitrary */
170 /* Pre-allocate argument list tuple. */
171 arg = PyTuple_New(1);
172 if (arg == NULL)
173 goto Fail_arg;
175 /* Get a result list. */
176 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
177 /* Eww - can modify the list in-place. */
178 Py_INCREF(seq);
179 result = seq;
181 else {
182 result = PyList_New(len);
183 if (result == NULL)
184 goto Fail_it;
187 /* Build the result list. */
188 j = 0;
189 for (;;) {
190 PyObject *item;
191 int ok;
193 item = PyIter_Next(it);
194 if (item == NULL) {
195 if (PyErr_Occurred())
196 goto Fail_result_it;
197 break;
200 if (func == Py_None) {
201 ok = PyObject_IsTrue(item);
203 else {
204 PyObject *good;
205 PyTuple_SET_ITEM(arg, 0, item);
206 good = PyObject_Call(func, arg, NULL);
207 PyTuple_SET_ITEM(arg, 0, NULL);
208 if (good == NULL) {
209 Py_DECREF(item);
210 goto Fail_result_it;
212 ok = PyObject_IsTrue(good);
213 Py_DECREF(good);
215 if (ok) {
216 if (j < len)
217 PyList_SET_ITEM(result, j, item);
218 else {
219 int status = PyList_Append(result, item);
220 Py_DECREF(item);
221 if (status < 0)
222 goto Fail_result_it;
224 ++j;
226 else
227 Py_DECREF(item);
231 /* Cut back result list if len is too big. */
232 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
233 goto Fail_result_it;
235 Py_DECREF(it);
236 Py_DECREF(arg);
237 return result;
239 Fail_result_it:
240 Py_DECREF(result);
241 Fail_it:
242 Py_DECREF(it);
243 Fail_arg:
244 Py_DECREF(arg);
245 return NULL;
248 PyDoc_STRVAR(filter_doc,
249 "filter(function or None, sequence) -> list, tuple, or string\n"
250 "\n"
251 "Return those items of sequence for which function(item) is true. If\n"
252 "function is None, return the items that are true. If sequence is a tuple\n"
253 "or string, return the same type, else return a list.");
255 static PyObject *
256 builtin_chr(PyObject *self, PyObject *args)
258 long x;
259 char s[1];
261 if (!PyArg_ParseTuple(args, "l:chr", &x))
262 return NULL;
263 if (x < 0 || x >= 256) {
264 PyErr_SetString(PyExc_ValueError,
265 "chr() arg not in range(256)");
266 return NULL;
268 s[0] = (char)x;
269 return PyString_FromStringAndSize(s, 1);
272 PyDoc_STRVAR(chr_doc,
273 "chr(i) -> character\n\
275 Return a string of one character with ordinal i; 0 <= i < 256.");
278 #ifdef Py_USING_UNICODE
279 static PyObject *
280 builtin_unichr(PyObject *self, PyObject *args)
282 long x;
284 if (!PyArg_ParseTuple(args, "l:unichr", &x))
285 return NULL;
287 return PyUnicode_FromOrdinal(x);
290 PyDoc_STRVAR(unichr_doc,
291 "unichr(i) -> Unicode character\n\
293 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
294 #endif
297 static PyObject *
298 builtin_cmp(PyObject *self, PyObject *args)
300 PyObject *a, *b;
301 int c;
303 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
304 return NULL;
305 if (PyObject_Cmp(a, b, &c) < 0)
306 return NULL;
307 return PyInt_FromLong((long)c);
310 PyDoc_STRVAR(cmp_doc,
311 "cmp(x, y) -> integer\n\
313 Return negative if x<y, zero if x==y, positive if x>y.");
316 static PyObject *
317 builtin_coerce(PyObject *self, PyObject *args)
319 PyObject *v, *w;
320 PyObject *res;
322 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
323 return NULL;
324 if (PyNumber_Coerce(&v, &w) < 0)
325 return NULL;
326 res = Py_BuildValue("(OO)", v, w);
327 Py_DECREF(v);
328 Py_DECREF(w);
329 return res;
332 PyDoc_STRVAR(coerce_doc,
333 "coerce(x, y) -> None or (x1, y1)\n\
335 When x and y can be coerced to values of the same type, return a tuple\n\
336 containing the coerced values. When they can't be coerced, return None.");
339 static PyObject *
340 builtin_compile(PyObject *self, PyObject *args)
342 char *str;
343 char *filename;
344 char *startstr;
345 int start;
346 int dont_inherit = 0;
347 int supplied_flags = 0;
348 PyCompilerFlags cf;
349 PyObject *result, *cmd, *tmp = NULL;
350 int length;
352 if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename,
353 &startstr, &supplied_flags, &dont_inherit))
354 return NULL;
356 cf.cf_flags = supplied_flags;
358 #ifdef Py_USING_UNICODE
359 if (PyUnicode_Check(cmd)) {
360 tmp = PyUnicode_AsUTF8String(cmd);
361 if (tmp == NULL)
362 return NULL;
363 cmd = tmp;
364 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
366 #endif
367 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
368 return NULL;
369 if ((size_t)length != strlen(str)) {
370 PyErr_SetString(PyExc_TypeError,
371 "compile() expected string without null bytes");
372 return NULL;
375 if (strcmp(startstr, "exec") == 0)
376 start = Py_file_input;
377 else if (strcmp(startstr, "eval") == 0)
378 start = Py_eval_input;
379 else if (strcmp(startstr, "single") == 0)
380 start = Py_single_input;
381 else {
382 PyErr_SetString(PyExc_ValueError,
383 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
384 return NULL;
387 if (supplied_flags &
388 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT))
390 PyErr_SetString(PyExc_ValueError,
391 "compile(): unrecognised flags");
392 return NULL;
394 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
396 if (!dont_inherit) {
397 PyEval_MergeCompilerFlags(&cf);
399 result = Py_CompileStringFlags(str, filename, start, &cf);
400 Py_XDECREF(tmp);
401 return result;
404 PyDoc_STRVAR(compile_doc,
405 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
407 Compile the source string (a Python module, statement or expression)\n\
408 into a code object that can be executed by the exec statement or eval().\n\
409 The filename will be used for run-time error messages.\n\
410 The mode must be 'exec' to compile a module, 'single' to compile a\n\
411 single (interactive) statement, or 'eval' to compile an expression.\n\
412 The flags argument, if present, controls which future statements influence\n\
413 the compilation of the code.\n\
414 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
415 the effects of any future statements in effect in the code calling\n\
416 compile; if absent or zero these statements do influence the compilation,\n\
417 in addition to any features explicitly specified.");
419 static PyObject *
420 builtin_dir(PyObject *self, PyObject *args)
422 PyObject *arg = NULL;
424 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
425 return NULL;
426 return PyObject_Dir(arg);
429 PyDoc_STRVAR(dir_doc,
430 "dir([object]) -> list of strings\n"
431 "\n"
432 "Return an alphabetized list of names comprising (some of) the attributes\n"
433 "of the given object, and of attributes reachable from it:\n"
434 "\n"
435 "No argument: the names in the current scope.\n"
436 "Module object: the module attributes.\n"
437 "Type or class object: its attributes, and recursively the attributes of\n"
438 " its bases.\n"
439 "Otherwise: its attributes, its class's attributes, and recursively the\n"
440 " attributes of its class's base classes.");
442 static PyObject *
443 builtin_divmod(PyObject *self, PyObject *args)
445 PyObject *v, *w;
447 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
448 return NULL;
449 return PyNumber_Divmod(v, w);
452 PyDoc_STRVAR(divmod_doc,
453 "divmod(x, y) -> (div, mod)\n\
455 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
458 static PyObject *
459 builtin_eval(PyObject *self, PyObject *args)
461 PyObject *cmd, *result, *tmp = NULL;
462 PyObject *globals = Py_None, *locals = Py_None;
463 char *str;
464 PyCompilerFlags cf;
466 if (!PyArg_ParseTuple(args, "O|O!O!:eval",
467 &cmd,
468 &PyDict_Type, &globals,
469 &PyDict_Type, &locals))
470 return NULL;
471 if (globals == Py_None) {
472 globals = PyEval_GetGlobals();
473 if (locals == Py_None)
474 locals = PyEval_GetLocals();
476 else if (locals == Py_None)
477 locals = globals;
479 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
480 if (PyDict_SetItemString(globals, "__builtins__",
481 PyEval_GetBuiltins()) != 0)
482 return NULL;
485 if (PyCode_Check(cmd)) {
486 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
487 PyErr_SetString(PyExc_TypeError,
488 "code object passed to eval() may not contain free variables");
489 return NULL;
491 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
494 if (!PyString_Check(cmd) &&
495 !PyUnicode_Check(cmd)) {
496 PyErr_SetString(PyExc_TypeError,
497 "eval() arg 1 must be a string or code object");
498 return NULL;
500 cf.cf_flags = 0;
502 #ifdef Py_USING_UNICODE
503 if (PyUnicode_Check(cmd)) {
504 tmp = PyUnicode_AsUTF8String(cmd);
505 if (tmp == NULL)
506 return NULL;
507 cmd = tmp;
508 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
510 #endif
511 if (PyString_AsStringAndSize(cmd, &str, NULL))
512 return NULL;
513 while (*str == ' ' || *str == '\t')
514 str++;
516 (void)PyEval_MergeCompilerFlags(&cf);
517 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
518 Py_XDECREF(tmp);
519 return result;
522 PyDoc_STRVAR(eval_doc,
523 "eval(source[, globals[, locals]]) -> value\n\
525 Evaluate the source in the context of globals and locals.\n\
526 The source may be a string representing a Python expression\n\
527 or a code object as returned by compile().\n\
528 The globals and locals are dictionaries, defaulting to the current\n\
529 globals and locals. If only globals is given, locals defaults to it.");
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 &PyDict_Type, &locals))
546 return NULL;
547 if (globals == Py_None) {
548 globals = PyEval_GetGlobals();
549 if (locals == Py_None)
550 locals = PyEval_GetLocals();
552 else if (locals == Py_None)
553 locals = globals;
554 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
555 if (PyDict_SetItemString(globals, "__builtins__",
556 PyEval_GetBuiltins()) != 0)
557 return NULL;
560 exists = 0;
561 /* Test for existence or directory. */
562 #if defined(PLAN9)
564 Dir *d;
566 if ((d = dirstat(filename))!=nil) {
567 if(d->mode & DMDIR)
568 werrstr("is a directory");
569 else
570 exists = 1;
571 free(d);
574 #elif defined(RISCOS)
575 if (object_exists(filename)) {
576 if (isdir(filename))
577 errno = EISDIR;
578 else
579 exists = 1;
581 #else /* standard Posix */
583 struct stat s;
584 if (stat(filename, &s) == 0) {
585 if (S_ISDIR(s.st_mode))
586 # if defined(PY_OS2) && defined(PYCC_VACPP)
587 errno = EOS2ERR;
588 # else
589 errno = EISDIR;
590 # endif
591 else
592 exists = 1;
595 #endif
597 if (exists) {
598 Py_BEGIN_ALLOW_THREADS
599 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
600 Py_END_ALLOW_THREADS
602 if (fp == NULL) {
603 exists = 0;
607 if (!exists) {
608 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
609 return NULL;
611 cf.cf_flags = 0;
612 if (PyEval_MergeCompilerFlags(&cf))
613 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
614 locals, 1, &cf);
615 else
616 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
617 locals, 1);
618 return res;
621 PyDoc_STRVAR(execfile_doc,
622 "execfile(filename[, globals[, locals]])\n\
624 Read and execute a Python script from a file.\n\
625 The globals and locals are dictionaries, defaulting to the current\n\
626 globals and locals. If only globals is given, locals defaults to it.");
629 static PyObject *
630 builtin_getattr(PyObject *self, PyObject *args)
632 PyObject *v, *result, *dflt = NULL;
633 PyObject *name;
635 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
636 return NULL;
637 #ifdef Py_USING_UNICODE
638 if (PyUnicode_Check(name)) {
639 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
640 if (name == NULL)
641 return NULL;
643 #endif
645 if (!PyString_Check(name)) {
646 PyErr_SetString(PyExc_TypeError,
647 "getattr(): attribute name must be string");
648 return NULL;
650 result = PyObject_GetAttr(v, name);
651 if (result == NULL && dflt != NULL &&
652 PyErr_ExceptionMatches(PyExc_AttributeError))
654 PyErr_Clear();
655 Py_INCREF(dflt);
656 result = dflt;
658 return result;
661 PyDoc_STRVAR(getattr_doc,
662 "getattr(object, name[, default]) -> value\n\
664 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
665 When a default argument is given, it is returned when the attribute doesn't\n\
666 exist; without it, an exception is raised in that case.");
669 static PyObject *
670 builtin_globals(PyObject *self)
672 PyObject *d;
674 d = PyEval_GetGlobals();
675 Py_INCREF(d);
676 return d;
679 PyDoc_STRVAR(globals_doc,
680 "globals() -> dictionary\n\
682 Return the dictionary containing the current scope's global variables.");
685 static PyObject *
686 builtin_hasattr(PyObject *self, PyObject *args)
688 PyObject *v;
689 PyObject *name;
691 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
692 return NULL;
693 #ifdef Py_USING_UNICODE
694 if (PyUnicode_Check(name)) {
695 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
696 if (name == NULL)
697 return NULL;
699 #endif
701 if (!PyString_Check(name)) {
702 PyErr_SetString(PyExc_TypeError,
703 "hasattr(): attribute name must be string");
704 return NULL;
706 v = PyObject_GetAttr(v, name);
707 if (v == NULL) {
708 PyErr_Clear();
709 Py_INCREF(Py_False);
710 return Py_False;
712 Py_DECREF(v);
713 Py_INCREF(Py_True);
714 return Py_True;
717 PyDoc_STRVAR(hasattr_doc,
718 "hasattr(object, name) -> bool\n\
720 Return whether the object has an attribute with the given name.\n\
721 (This is done by calling getattr(object, name) and catching exceptions.)");
724 static PyObject *
725 builtin_id(PyObject *self, PyObject *v)
727 return PyLong_FromVoidPtr(v);
730 PyDoc_STRVAR(id_doc,
731 "id(object) -> integer\n\
733 Return the identity of an object. This is guaranteed to be unique among\n\
734 simultaneously existing objects. (Hint: it's the object's memory address.)");
737 static PyObject *
738 builtin_map(PyObject *self, PyObject *args)
740 typedef struct {
741 PyObject *it; /* the iterator object */
742 int saw_StopIteration; /* bool: did the iterator end? */
743 } sequence;
745 PyObject *func, *result;
746 sequence *seqs = NULL, *sqp;
747 int n, len;
748 register int i, j;
750 n = PyTuple_Size(args);
751 if (n < 2) {
752 PyErr_SetString(PyExc_TypeError,
753 "map() requires at least two args");
754 return NULL;
757 func = PyTuple_GetItem(args, 0);
758 n--;
760 if (func == Py_None && n == 1) {
761 /* map(None, S) is the same as list(S). */
762 return PySequence_List(PyTuple_GetItem(args, 1));
765 /* Get space for sequence descriptors. Must NULL out the iterator
766 * pointers so that jumping to Fail_2 later doesn't see trash.
768 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
769 PyErr_NoMemory();
770 return NULL;
772 for (i = 0; i < n; ++i) {
773 seqs[i].it = (PyObject*)NULL;
774 seqs[i].saw_StopIteration = 0;
777 /* Do a first pass to obtain iterators for the arguments, and set len
778 * to the largest of their lengths.
780 len = 0;
781 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
782 PyObject *curseq;
783 int curlen;
785 /* Get iterator. */
786 curseq = PyTuple_GetItem(args, i+1);
787 sqp->it = PyObject_GetIter(curseq);
788 if (sqp->it == NULL) {
789 static char errmsg[] =
790 "argument %d to map() must support iteration";
791 char errbuf[sizeof(errmsg) + 25];
792 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
793 PyErr_SetString(PyExc_TypeError, errbuf);
794 goto Fail_2;
797 /* Update len. */
798 curlen = -1; /* unknown */
799 if (PySequence_Check(curseq) &&
800 curseq->ob_type->tp_as_sequence->sq_length) {
801 curlen = PySequence_Size(curseq);
802 if (curlen < 0)
803 PyErr_Clear();
805 if (curlen < 0)
806 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;
970 if ((nb = v->ob_type->tp_as_number) == NULL ||
971 nb->nb_hex == NULL) {
972 PyErr_SetString(PyExc_TypeError,
973 "hex() argument can't be converted to hex");
974 return NULL;
976 return (*nb->nb_hex)(v);
979 PyDoc_STRVAR(hex_doc,
980 "hex(number) -> string\n\
982 Return the hexadecimal representation of an integer or long integer.");
985 static PyObject *builtin_raw_input(PyObject *, PyObject *);
987 static PyObject *
988 builtin_input(PyObject *self, PyObject *args)
990 PyObject *line;
991 char *str;
992 PyObject *res;
993 PyObject *globals, *locals;
995 line = builtin_raw_input(self, args);
996 if (line == NULL)
997 return line;
998 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
999 return NULL;
1000 while (*str == ' ' || *str == '\t')
1001 str++;
1002 globals = PyEval_GetGlobals();
1003 locals = PyEval_GetLocals();
1004 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1005 if (PyDict_SetItemString(globals, "__builtins__",
1006 PyEval_GetBuiltins()) != 0)
1007 return NULL;
1009 res = PyRun_String(str, Py_eval_input, globals, locals);
1010 Py_DECREF(line);
1011 return res;
1014 PyDoc_STRVAR(input_doc,
1015 "input([prompt]) -> value\n\
1017 Equivalent to eval(raw_input(prompt)).");
1020 static PyObject *
1021 builtin_intern(PyObject *self, PyObject *args)
1023 PyObject *s;
1024 if (!PyArg_ParseTuple(args, "S:intern", &s))
1025 return NULL;
1026 Py_INCREF(s);
1027 PyString_InternInPlace(&s);
1028 return s;
1031 PyDoc_STRVAR(intern_doc,
1032 "intern(string) -> string\n\
1034 ``Intern'' the given string. This enters the string in the (global)\n\
1035 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1036 Return the string itself or the previously interned string object with the\n\
1037 same value.");
1040 static PyObject *
1041 builtin_iter(PyObject *self, PyObject *args)
1043 PyObject *v, *w = NULL;
1045 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1046 return NULL;
1047 if (w == NULL)
1048 return PyObject_GetIter(v);
1049 if (!PyCallable_Check(v)) {
1050 PyErr_SetString(PyExc_TypeError,
1051 "iter(v, w): v must be callable");
1052 return NULL;
1054 return PyCallIter_New(v, w);
1057 PyDoc_STRVAR(iter_doc,
1058 "iter(collection) -> iterator\n\
1059 iter(callable, sentinel) -> iterator\n\
1061 Get an iterator from an object. In the first form, the argument must\n\
1062 supply its own iterator, or be a sequence.\n\
1063 In the second form, the callable is called until it returns the sentinel.");
1066 static PyObject *
1067 builtin_len(PyObject *self, PyObject *v)
1069 long res;
1071 res = PyObject_Size(v);
1072 if (res < 0 && PyErr_Occurred())
1073 return NULL;
1074 return PyInt_FromLong(res);
1077 PyDoc_STRVAR(len_doc,
1078 "len(object) -> integer\n\
1080 Return the number of items of a sequence or mapping.");
1083 static PyObject *
1084 builtin_locals(PyObject *self)
1086 PyObject *d;
1088 d = PyEval_GetLocals();
1089 Py_INCREF(d);
1090 return d;
1093 PyDoc_STRVAR(locals_doc,
1094 "locals() -> dictionary\n\
1096 Update and return a dictionary containing the current scope's local variables.");
1099 static PyObject *
1100 min_max(PyObject *args, int op)
1102 PyObject *v, *w, *x, *it;
1104 if (PyTuple_Size(args) > 1)
1105 v = args;
1106 else if (!PyArg_UnpackTuple(args, (op==Py_LT) ? "min" : "max", 1, 1, &v))
1107 return NULL;
1109 it = PyObject_GetIter(v);
1110 if (it == NULL)
1111 return NULL;
1113 w = NULL; /* the result */
1114 for (;;) {
1115 x = PyIter_Next(it);
1116 if (x == NULL) {
1117 if (PyErr_Occurred()) {
1118 Py_XDECREF(w);
1119 Py_DECREF(it);
1120 return NULL;
1122 break;
1125 if (w == NULL)
1126 w = x;
1127 else {
1128 int cmp = PyObject_RichCompareBool(x, w, op);
1129 if (cmp > 0) {
1130 Py_DECREF(w);
1131 w = x;
1133 else if (cmp < 0) {
1134 Py_DECREF(x);
1135 Py_DECREF(w);
1136 Py_DECREF(it);
1137 return NULL;
1139 else
1140 Py_DECREF(x);
1143 if (w == NULL)
1144 PyErr_SetString(PyExc_ValueError,
1145 "min() or max() arg is an empty sequence");
1146 Py_DECREF(it);
1147 return w;
1150 static PyObject *
1151 builtin_min(PyObject *self, PyObject *v)
1153 return min_max(v, Py_LT);
1156 PyDoc_STRVAR(min_doc,
1157 "min(sequence) -> value\n\
1158 min(a, b, c, ...) -> value\n\
1160 With a single sequence argument, return its smallest item.\n\
1161 With two or more arguments, return the smallest argument.");
1164 static PyObject *
1165 builtin_max(PyObject *self, PyObject *v)
1167 return min_max(v, Py_GT);
1170 PyDoc_STRVAR(max_doc,
1171 "max(sequence) -> value\n\
1172 max(a, b, c, ...) -> value\n\
1174 With a single sequence argument, return its largest item.\n\
1175 With two or more arguments, return the largest argument.");
1178 static PyObject *
1179 builtin_oct(PyObject *self, PyObject *v)
1181 PyNumberMethods *nb;
1183 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1184 nb->nb_oct == NULL) {
1185 PyErr_SetString(PyExc_TypeError,
1186 "oct() argument can't be converted to oct");
1187 return NULL;
1189 return (*nb->nb_oct)(v);
1192 PyDoc_STRVAR(oct_doc,
1193 "oct(number) -> string\n\
1195 Return the octal representation of an integer or long integer.");
1198 static PyObject *
1199 builtin_ord(PyObject *self, PyObject* obj)
1201 long ord;
1202 int size;
1204 if (PyString_Check(obj)) {
1205 size = PyString_GET_SIZE(obj);
1206 if (size == 1) {
1207 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1208 return PyInt_FromLong(ord);
1210 #ifdef Py_USING_UNICODE
1211 } else if (PyUnicode_Check(obj)) {
1212 size = PyUnicode_GET_SIZE(obj);
1213 if (size == 1) {
1214 ord = (long)*PyUnicode_AS_UNICODE(obj);
1215 return PyInt_FromLong(ord);
1217 #endif
1218 } else {
1219 PyErr_Format(PyExc_TypeError,
1220 "ord() expected string of length 1, but " \
1221 "%.200s found", obj->ob_type->tp_name);
1222 return NULL;
1225 PyErr_Format(PyExc_TypeError,
1226 "ord() expected a character, "
1227 "but string of length %d found",
1228 size);
1229 return NULL;
1232 PyDoc_STRVAR(ord_doc,
1233 "ord(c) -> integer\n\
1235 Return the integer ordinal of a one-character string.");
1238 static PyObject *
1239 builtin_pow(PyObject *self, PyObject *args)
1241 PyObject *v, *w, *z = Py_None;
1243 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1244 return NULL;
1245 return PyNumber_Power(v, w, z);
1248 PyDoc_STRVAR(pow_doc,
1249 "pow(x, y[, z]) -> number\n\
1251 With two arguments, equivalent to x**y. With three arguments,\n\
1252 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1256 /* Return number of items in range (lo, hi, step), when arguments are
1257 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1258 * & only if the true value is too large to fit in a signed long.
1259 * Arguments MUST return 1 with either PyInt_Check() or
1260 * PyLong_Check(). Return -1 when there is an error.
1262 static long
1263 get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1265 /* -------------------------------------------------------------
1266 Algorithm is equal to that of get_len_of_range(), but it operates
1267 on PyObjects (which are assumed to be PyLong or PyInt objects).
1268 ---------------------------------------------------------------*/
1269 long n;
1270 PyObject *diff = NULL;
1271 PyObject *one = NULL;
1272 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1273 /* holds sub-expression evaluations */
1275 /* if (lo >= hi), return length of 0. */
1276 if (PyObject_Compare(lo, hi) >= 0)
1277 return 0;
1279 if ((one = PyLong_FromLong(1L)) == NULL)
1280 goto Fail;
1282 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1283 goto Fail;
1285 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1286 goto Fail;
1288 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1289 goto Fail;
1291 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1292 goto Fail;
1294 n = PyLong_AsLong(tmp3);
1295 if (PyErr_Occurred()) { /* Check for Overflow */
1296 PyErr_Clear();
1297 goto Fail;
1300 Py_DECREF(tmp3);
1301 Py_DECREF(tmp2);
1302 Py_DECREF(diff);
1303 Py_DECREF(tmp1);
1304 Py_DECREF(one);
1305 return n;
1307 Fail:
1308 Py_XDECREF(tmp3);
1309 Py_XDECREF(tmp2);
1310 Py_XDECREF(diff);
1311 Py_XDECREF(tmp1);
1312 Py_XDECREF(one);
1313 return -1;
1316 /* An extension of builtin_range() that handles the case when PyLong
1317 * arguments are given. */
1318 static PyObject *
1319 handle_range_longs(PyObject *self, PyObject *args)
1321 PyObject *ilow;
1322 PyObject *ihigh = NULL;
1323 PyObject *istep = NULL;
1325 PyObject *curnum = NULL;
1326 PyObject *v = NULL;
1327 long bign;
1328 int i, n;
1329 int cmp_result;
1331 PyObject *zero = PyLong_FromLong(0);
1333 if (zero == NULL)
1334 return NULL;
1336 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1337 Py_DECREF(zero);
1338 return NULL;
1341 /* Figure out which way we were called, supply defaults, and be
1342 * sure to incref everything so that the decrefs at the end
1343 * are correct.
1345 assert(ilow != NULL);
1346 if (ihigh == NULL) {
1347 /* only 1 arg -- it's the upper limit */
1348 ihigh = ilow;
1349 ilow = NULL;
1351 assert(ihigh != NULL);
1352 Py_INCREF(ihigh);
1354 /* ihigh correct now; do ilow */
1355 if (ilow == NULL)
1356 ilow = zero;
1357 Py_INCREF(ilow);
1359 /* ilow and ihigh correct now; do istep */
1360 if (istep == NULL) {
1361 istep = PyLong_FromLong(1L);
1362 if (istep == NULL)
1363 goto Fail;
1365 else {
1366 Py_INCREF(istep);
1369 if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
1370 PyErr_Format(PyExc_TypeError,
1371 "range() integer start argument expected, got %s.",
1372 ilow->ob_type->tp_name);
1373 goto Fail;
1376 if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
1377 PyErr_Format(PyExc_TypeError,
1378 "range() integer end argument expected, got %s.",
1379 ihigh->ob_type->tp_name);
1380 goto Fail;
1383 if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
1384 PyErr_Format(PyExc_TypeError,
1385 "range() integer step argument expected, got %s.",
1386 istep->ob_type->tp_name);
1387 goto Fail;
1390 if (PyObject_Cmp(istep, zero, &cmp_result) == -1)
1391 goto Fail;
1392 if (cmp_result == 0) {
1393 PyErr_SetString(PyExc_ValueError,
1394 "range() step argument must not be zero");
1395 goto Fail;
1398 if (cmp_result > 0)
1399 bign = get_len_of_range_longs(ilow, ihigh, istep);
1400 else {
1401 PyObject *neg_istep = PyNumber_Negative(istep);
1402 if (neg_istep == NULL)
1403 goto Fail;
1404 bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
1405 Py_DECREF(neg_istep);
1408 n = (int)bign;
1409 if (bign < 0 || (long)n != bign) {
1410 PyErr_SetString(PyExc_OverflowError,
1411 "range() result has too many items");
1412 goto Fail;
1415 v = PyList_New(n);
1416 if (v == NULL)
1417 goto Fail;
1419 curnum = ilow;
1420 Py_INCREF(curnum);
1422 for (i = 0; i < n; i++) {
1423 PyObject *w = PyNumber_Long(curnum);
1424 PyObject *tmp_num;
1425 if (w == NULL)
1426 goto Fail;
1428 PyList_SET_ITEM(v, i, w);
1430 tmp_num = PyNumber_Add(curnum, istep);
1431 if (tmp_num == NULL)
1432 goto Fail;
1434 Py_DECREF(curnum);
1435 curnum = tmp_num;
1437 Py_DECREF(ilow);
1438 Py_DECREF(ihigh);
1439 Py_DECREF(istep);
1440 Py_DECREF(zero);
1441 Py_DECREF(curnum);
1442 return v;
1444 Fail:
1445 Py_DECREF(ilow);
1446 Py_DECREF(ihigh);
1447 Py_XDECREF(istep);
1448 Py_DECREF(zero);
1449 Py_XDECREF(curnum);
1450 Py_XDECREF(v);
1451 return NULL;
1454 /* Return number of items in range/xrange (lo, hi, step). step > 0
1455 * required. Return a value < 0 if & only if the true value is too
1456 * large to fit in a signed long.
1458 static long
1459 get_len_of_range(long lo, long hi, long step)
1461 /* -------------------------------------------------------------
1462 If lo >= hi, the range is empty.
1463 Else if n values are in the range, the last one is
1464 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1465 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1466 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1467 the RHS is non-negative and so truncation is the same as the
1468 floor. Letting M be the largest positive long, the worst case
1469 for the RHS numerator is hi=M, lo=-M-1, and then
1470 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1471 precision to compute the RHS exactly.
1472 ---------------------------------------------------------------*/
1473 long n = 0;
1474 if (lo < hi) {
1475 unsigned long uhi = (unsigned long)hi;
1476 unsigned long ulo = (unsigned long)lo;
1477 unsigned long diff = uhi - ulo - 1;
1478 n = (long)(diff / (unsigned long)step + 1);
1480 return n;
1483 static PyObject *
1484 builtin_range(PyObject *self, PyObject *args)
1486 long ilow = 0, ihigh = 0, istep = 1;
1487 long bign;
1488 int i, n;
1490 PyObject *v;
1492 if (PyTuple_Size(args) <= 1) {
1493 if (!PyArg_ParseTuple(args,
1494 "l;range() requires 1-3 int arguments",
1495 &ihigh)) {
1496 PyErr_Clear();
1497 return handle_range_longs(self, args);
1500 else {
1501 if (!PyArg_ParseTuple(args,
1502 "ll|l;range() requires 1-3 int arguments",
1503 &ilow, &ihigh, &istep)) {
1504 PyErr_Clear();
1505 return handle_range_longs(self, args);
1508 if (istep == 0) {
1509 PyErr_SetString(PyExc_ValueError,
1510 "range() step argument must not be zero");
1511 return NULL;
1513 if (istep > 0)
1514 bign = get_len_of_range(ilow, ihigh, istep);
1515 else
1516 bign = get_len_of_range(ihigh, ilow, -istep);
1517 n = (int)bign;
1518 if (bign < 0 || (long)n != bign) {
1519 PyErr_SetString(PyExc_OverflowError,
1520 "range() result has too many items");
1521 return NULL;
1523 v = PyList_New(n);
1524 if (v == NULL)
1525 return NULL;
1526 for (i = 0; i < n; i++) {
1527 PyObject *w = PyInt_FromLong(ilow);
1528 if (w == NULL) {
1529 Py_DECREF(v);
1530 return NULL;
1532 PyList_SET_ITEM(v, i, w);
1533 ilow += istep;
1535 return v;
1538 PyDoc_STRVAR(range_doc,
1539 "range([start,] stop[, step]) -> list of integers\n\
1541 Return a list containing an arithmetic progression of integers.\n\
1542 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1543 When step is given, it specifies the increment (or decrement).\n\
1544 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1545 These are exactly the valid indices for a list of 4 elements.");
1548 static PyObject *
1549 builtin_raw_input(PyObject *self, PyObject *args)
1551 PyObject *v = NULL;
1552 PyObject *fin = PySys_GetObject("stdin");
1553 PyObject *fout = PySys_GetObject("stdout");
1555 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
1556 return NULL;
1558 if (fin == NULL) {
1559 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
1560 return NULL;
1562 if (fout == NULL) {
1563 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
1564 return NULL;
1566 if (PyFile_SoftSpace(fout, 0)) {
1567 if (PyFile_WriteString(" ", fout) != 0)
1568 return NULL;
1570 if (PyFile_Check (fin) && PyFile_Check (fout)
1571 && isatty(fileno(PyFile_AsFile(fin)))
1572 && isatty(fileno(PyFile_AsFile(fout)))) {
1573 PyObject *po;
1574 char *prompt;
1575 char *s;
1576 PyObject *result;
1577 if (v != NULL) {
1578 po = PyObject_Str(v);
1579 if (po == NULL)
1580 return NULL;
1581 prompt = PyString_AsString(po);
1582 if (prompt == NULL)
1583 return NULL;
1585 else {
1586 po = NULL;
1587 prompt = "";
1589 s = PyOS_Readline(PyFile_AsFile (fin), PyFile_AsFile (fout),
1590 prompt);
1591 Py_XDECREF(po);
1592 if (s == NULL) {
1593 PyErr_SetNone(PyExc_KeyboardInterrupt);
1594 return NULL;
1596 if (*s == '\0') {
1597 PyErr_SetNone(PyExc_EOFError);
1598 result = NULL;
1600 else { /* strip trailing '\n' */
1601 size_t len = strlen(s);
1602 if (len > INT_MAX) {
1603 PyErr_SetString(PyExc_OverflowError,
1604 "[raw_]input: input too long");
1605 result = NULL;
1607 else {
1608 result = PyString_FromStringAndSize(s,
1609 (int)(len-1));
1612 PyMem_FREE(s);
1613 return result;
1615 if (v != NULL) {
1616 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
1617 return NULL;
1619 return PyFile_GetLine(fin, -1);
1622 PyDoc_STRVAR(raw_input_doc,
1623 "raw_input([prompt]) -> string\n\
1625 Read a string from standard input. The trailing newline is stripped.\n\
1626 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1627 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1628 is printed without a trailing newline before reading.");
1631 static PyObject *
1632 builtin_reduce(PyObject *self, PyObject *args)
1634 PyObject *seq, *func, *result = NULL, *it;
1636 if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
1637 return NULL;
1638 if (result != NULL)
1639 Py_INCREF(result);
1641 it = PyObject_GetIter(seq);
1642 if (it == NULL) {
1643 PyErr_SetString(PyExc_TypeError,
1644 "reduce() arg 2 must support iteration");
1645 Py_XDECREF(result);
1646 return NULL;
1649 if ((args = PyTuple_New(2)) == NULL)
1650 goto Fail;
1652 for (;;) {
1653 PyObject *op2;
1655 if (args->ob_refcnt > 1) {
1656 Py_DECREF(args);
1657 if ((args = PyTuple_New(2)) == NULL)
1658 goto Fail;
1661 op2 = PyIter_Next(it);
1662 if (op2 == NULL) {
1663 if (PyErr_Occurred())
1664 goto Fail;
1665 break;
1668 if (result == NULL)
1669 result = op2;
1670 else {
1671 PyTuple_SetItem(args, 0, result);
1672 PyTuple_SetItem(args, 1, op2);
1673 if ((result = PyEval_CallObject(func, args)) == NULL)
1674 goto Fail;
1678 Py_DECREF(args);
1680 if (result == NULL)
1681 PyErr_SetString(PyExc_TypeError,
1682 "reduce() of empty sequence with no initial value");
1684 Py_DECREF(it);
1685 return result;
1687 Fail:
1688 Py_XDECREF(args);
1689 Py_XDECREF(result);
1690 Py_DECREF(it);
1691 return NULL;
1694 PyDoc_STRVAR(reduce_doc,
1695 "reduce(function, sequence[, initial]) -> value\n\
1697 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1698 from left to right, so as to reduce the sequence to a single value.\n\
1699 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1700 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1701 of the sequence in the calculation, and serves as a default when the\n\
1702 sequence is empty.");
1705 static PyObject *
1706 builtin_reload(PyObject *self, PyObject *v)
1708 return PyImport_ReloadModule(v);
1711 PyDoc_STRVAR(reload_doc,
1712 "reload(module) -> module\n\
1714 Reload the module. The module must have been successfully imported before.");
1717 static PyObject *
1718 builtin_repr(PyObject *self, PyObject *v)
1720 return PyObject_Repr(v);
1723 PyDoc_STRVAR(repr_doc,
1724 "repr(object) -> string\n\
1726 Return the canonical string representation of the object.\n\
1727 For most object types, eval(repr(object)) == object.");
1730 static PyObject *
1731 builtin_round(PyObject *self, PyObject *args)
1733 double x;
1734 double f;
1735 int ndigits = 0;
1736 int i;
1738 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1739 return NULL;
1740 f = 1.0;
1741 i = abs(ndigits);
1742 while (--i >= 0)
1743 f = f*10.0;
1744 if (ndigits < 0)
1745 x /= f;
1746 else
1747 x *= f;
1748 if (x >= 0.0)
1749 x = floor(x + 0.5);
1750 else
1751 x = ceil(x - 0.5);
1752 if (ndigits < 0)
1753 x *= f;
1754 else
1755 x /= f;
1756 return PyFloat_FromDouble(x);
1759 PyDoc_STRVAR(round_doc,
1760 "round(number[, ndigits]) -> floating point number\n\
1762 Round a number to a given precision in decimal digits (default 0 digits).\n\
1763 This always returns a floating point number. Precision may be negative.");
1766 static PyObject *
1767 builtin_vars(PyObject *self, PyObject *args)
1769 PyObject *v = NULL;
1770 PyObject *d;
1772 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1773 return NULL;
1774 if (v == NULL) {
1775 d = PyEval_GetLocals();
1776 if (d == NULL) {
1777 if (!PyErr_Occurred())
1778 PyErr_SetString(PyExc_SystemError,
1779 "vars(): no locals!?");
1781 else
1782 Py_INCREF(d);
1784 else {
1785 d = PyObject_GetAttrString(v, "__dict__");
1786 if (d == NULL) {
1787 PyErr_SetString(PyExc_TypeError,
1788 "vars() argument must have __dict__ attribute");
1789 return NULL;
1792 return d;
1795 PyDoc_STRVAR(vars_doc,
1796 "vars([object]) -> dictionary\n\
1798 Without arguments, equivalent to locals().\n\
1799 With an argument, equivalent to object.__dict__.");
1802 static PyObject*
1803 builtin_sum(PyObject *self, PyObject *args)
1805 PyObject *seq;
1806 PyObject *result = NULL;
1807 PyObject *temp, *item, *iter;
1809 if (!PyArg_ParseTuple(args, "O|O:sum", &seq, &result))
1810 return NULL;
1812 iter = PyObject_GetIter(seq);
1813 if (iter == NULL)
1814 return NULL;
1816 if (result == NULL) {
1817 result = PyInt_FromLong(0);
1818 if (result == NULL) {
1819 Py_DECREF(iter);
1820 return NULL;
1822 } else {
1823 /* reject string values for 'start' parameter */
1824 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
1825 PyErr_SetString(PyExc_TypeError,
1826 "sum() can't sum strings [use ''.join(seq) instead]");
1827 Py_DECREF(iter);
1828 return NULL;
1830 Py_INCREF(result);
1833 for(;;) {
1834 item = PyIter_Next(iter);
1835 if (item == NULL) {
1836 /* error, or end-of-sequence */
1837 if (PyErr_Occurred()) {
1838 Py_DECREF(result);
1839 result = NULL;
1841 break;
1843 temp = PyNumber_Add(result, item);
1844 Py_DECREF(result);
1845 Py_DECREF(item);
1846 result = temp;
1847 if (result == NULL)
1848 break;
1850 Py_DECREF(iter);
1851 return result;
1854 PyDoc_STRVAR(sum_doc,
1855 "sum(sequence, start=0) -> value\n\
1857 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
1858 of parameter 'start'. When the sequence is empty, returns start.");
1861 static PyObject *
1862 builtin_isinstance(PyObject *self, PyObject *args)
1864 PyObject *inst;
1865 PyObject *cls;
1866 int retval;
1868 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
1869 return NULL;
1871 retval = PyObject_IsInstance(inst, cls);
1872 if (retval < 0)
1873 return NULL;
1874 return PyBool_FromLong(retval);
1877 PyDoc_STRVAR(isinstance_doc,
1878 "isinstance(object, class-or-type-or-tuple) -> bool\n\
1880 Return whether an object is an instance of a class or of a subclass thereof.\n\
1881 With a type as second argument, return whether that is the object's type.\n\
1882 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
1883 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
1886 static PyObject *
1887 builtin_issubclass(PyObject *self, PyObject *args)
1889 PyObject *derived;
1890 PyObject *cls;
1891 int retval;
1893 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
1894 return NULL;
1896 retval = PyObject_IsSubclass(derived, cls);
1897 if (retval < 0)
1898 return NULL;
1899 return PyBool_FromLong(retval);
1902 PyDoc_STRVAR(issubclass_doc,
1903 "issubclass(C, B) -> bool\n\
1905 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1906 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1907 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
1910 static PyObject*
1911 builtin_zip(PyObject *self, PyObject *args)
1913 PyObject *ret;
1914 const int itemsize = PySequence_Length(args);
1915 int i;
1916 PyObject *itlist; /* tuple of iterators */
1917 int len; /* guess at result length */
1919 if (itemsize < 1) {
1920 PyErr_SetString(PyExc_TypeError,
1921 "zip() requires at least one sequence");
1922 return NULL;
1924 /* args must be a tuple */
1925 assert(PyTuple_Check(args));
1927 /* Guess at result length: the shortest of the input lengths.
1928 If some argument refuses to say, we refuse to guess too, lest
1929 an argument like xrange(sys.maxint) lead us astray.*/
1930 len = -1; /* unknown */
1931 for (i = 0; i < itemsize; ++i) {
1932 PyObject *item = PyTuple_GET_ITEM(args, i);
1933 int thislen = PySequence_Length(item);
1934 if (thislen < 0) {
1935 PyErr_Clear();
1936 len = -1;
1937 break;
1939 else if (len < 0 || thislen < len)
1940 len = thislen;
1943 /* allocate result list */
1944 if (len < 0)
1945 len = 10; /* arbitrary */
1946 if ((ret = PyList_New(len)) == NULL)
1947 return NULL;
1949 /* obtain iterators */
1950 itlist = PyTuple_New(itemsize);
1951 if (itlist == NULL)
1952 goto Fail_ret;
1953 for (i = 0; i < itemsize; ++i) {
1954 PyObject *item = PyTuple_GET_ITEM(args, i);
1955 PyObject *it = PyObject_GetIter(item);
1956 if (it == NULL) {
1957 if (PyErr_ExceptionMatches(PyExc_TypeError))
1958 PyErr_Format(PyExc_TypeError,
1959 "zip argument #%d must support iteration",
1960 i+1);
1961 goto Fail_ret_itlist;
1963 PyTuple_SET_ITEM(itlist, i, it);
1966 /* build result into ret list */
1967 for (i = 0; ; ++i) {
1968 int j;
1969 PyObject *next = PyTuple_New(itemsize);
1970 if (!next)
1971 goto Fail_ret_itlist;
1973 for (j = 0; j < itemsize; j++) {
1974 PyObject *it = PyTuple_GET_ITEM(itlist, j);
1975 PyObject *item = PyIter_Next(it);
1976 if (!item) {
1977 if (PyErr_Occurred()) {
1978 Py_DECREF(ret);
1979 ret = NULL;
1981 Py_DECREF(next);
1982 Py_DECREF(itlist);
1983 goto Done;
1985 PyTuple_SET_ITEM(next, j, item);
1988 if (i < len)
1989 PyList_SET_ITEM(ret, i, next);
1990 else {
1991 int status = PyList_Append(ret, next);
1992 Py_DECREF(next);
1993 ++len;
1994 if (status < 0)
1995 goto Fail_ret_itlist;
1999 Done:
2000 if (ret != NULL && i < len) {
2001 /* The list is too big. */
2002 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2003 return NULL;
2005 return ret;
2007 Fail_ret_itlist:
2008 Py_DECREF(itlist);
2009 Fail_ret:
2010 Py_DECREF(ret);
2011 return NULL;
2015 PyDoc_STRVAR(zip_doc,
2016 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2018 Return a list of tuples, where each tuple contains the i-th element\n\
2019 from each of the argument sequences. The returned list is truncated\n\
2020 in length to the length of the shortest argument sequence.");
2023 static PyMethodDef builtin_methods[] = {
2024 {"__import__", builtin___import__, METH_VARARGS, import_doc},
2025 {"abs", builtin_abs, METH_O, abs_doc},
2026 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2027 {"callable", builtin_callable, METH_O, callable_doc},
2028 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2029 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2030 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2031 {"compile", builtin_compile, METH_VARARGS, compile_doc},
2032 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2033 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2034 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2035 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2036 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2037 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2038 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2039 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2040 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2041 {"hash", builtin_hash, METH_O, hash_doc},
2042 {"hex", builtin_hex, METH_O, hex_doc},
2043 {"id", builtin_id, METH_O, id_doc},
2044 {"input", builtin_input, METH_VARARGS, input_doc},
2045 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2046 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2047 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2048 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2049 {"len", builtin_len, METH_O, len_doc},
2050 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2051 {"map", builtin_map, METH_VARARGS, map_doc},
2052 {"max", builtin_max, METH_VARARGS, max_doc},
2053 {"min", builtin_min, METH_VARARGS, min_doc},
2054 {"oct", builtin_oct, METH_O, oct_doc},
2055 {"ord", builtin_ord, METH_O, ord_doc},
2056 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2057 {"range", builtin_range, METH_VARARGS, range_doc},
2058 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2059 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2060 {"reload", builtin_reload, METH_O, reload_doc},
2061 {"repr", builtin_repr, METH_O, repr_doc},
2062 {"round", builtin_round, METH_VARARGS, round_doc},
2063 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2064 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2065 #ifdef Py_USING_UNICODE
2066 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
2067 #endif
2068 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2069 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2070 {NULL, NULL},
2073 PyDoc_STRVAR(builtin_doc,
2074 "Built-in functions, exceptions, and other objects.\n\
2076 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2078 PyObject *
2079 _PyBuiltin_Init(void)
2081 PyObject *mod, *dict, *debug;
2082 mod = Py_InitModule4("__builtin__", builtin_methods,
2083 builtin_doc, (PyObject *)NULL,
2084 PYTHON_API_VERSION);
2085 if (mod == NULL)
2086 return NULL;
2087 dict = PyModule_GetDict(mod);
2089 #ifdef Py_TRACE_REFS
2090 /* __builtin__ exposes a number of statically allocated objects
2091 * that, before this code was added in 2.3, never showed up in
2092 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2093 * result, programs leaking references to None and False (etc)
2094 * couldn't be diagnosed by examining sys.getobjects(0).
2096 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2097 #else
2098 #define ADD_TO_ALL(OBJECT) (void)0
2099 #endif
2101 #define SETBUILTIN(NAME, OBJECT) \
2102 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2103 return NULL; \
2104 ADD_TO_ALL(OBJECT)
2106 SETBUILTIN("None", Py_None);
2107 SETBUILTIN("Ellipsis", Py_Ellipsis);
2108 SETBUILTIN("NotImplemented", Py_NotImplemented);
2109 SETBUILTIN("False", Py_False);
2110 SETBUILTIN("True", Py_True);
2111 SETBUILTIN("basestring", &PyBaseString_Type);
2112 SETBUILTIN("bool", &PyBool_Type);
2113 SETBUILTIN("buffer", &PyBuffer_Type);
2114 SETBUILTIN("classmethod", &PyClassMethod_Type);
2115 #ifndef WITHOUT_COMPLEX
2116 SETBUILTIN("complex", &PyComplex_Type);
2117 #endif
2118 SETBUILTIN("dict", &PyDict_Type);
2119 SETBUILTIN("enumerate", &PyEnum_Type);
2120 SETBUILTIN("float", &PyFloat_Type);
2121 SETBUILTIN("property", &PyProperty_Type);
2122 SETBUILTIN("int", &PyInt_Type);
2123 SETBUILTIN("list", &PyList_Type);
2124 SETBUILTIN("long", &PyLong_Type);
2125 SETBUILTIN("object", &PyBaseObject_Type);
2126 SETBUILTIN("slice", &PySlice_Type);
2127 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2128 SETBUILTIN("str", &PyString_Type);
2129 SETBUILTIN("super", &PySuper_Type);
2130 SETBUILTIN("tuple", &PyTuple_Type);
2131 SETBUILTIN("type", &PyType_Type);
2132 SETBUILTIN("xrange", &PyRange_Type);
2134 /* Note that open() is just an alias of file(). */
2135 SETBUILTIN("open", &PyFile_Type);
2136 SETBUILTIN("file", &PyFile_Type);
2137 #ifdef Py_USING_UNICODE
2138 SETBUILTIN("unicode", &PyUnicode_Type);
2139 #endif
2140 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2141 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2142 Py_XDECREF(debug);
2143 return NULL;
2145 Py_XDECREF(debug);
2147 return mod;
2148 #undef ADD_TO_ALL
2149 #undef SETBUILTIN
2152 /* Helper for filter(): filter a tuple through a function */
2154 static PyObject *
2155 filtertuple(PyObject *func, PyObject *tuple)
2157 PyObject *result;
2158 register int i, j;
2159 int len = PyTuple_Size(tuple);
2161 if (len == 0) {
2162 if (PyTuple_CheckExact(tuple))
2163 Py_INCREF(tuple);
2164 else
2165 tuple = PyTuple_New(0);
2166 return tuple;
2169 if ((result = PyTuple_New(len)) == NULL)
2170 return NULL;
2172 for (i = j = 0; i < len; ++i) {
2173 PyObject *item, *good;
2174 int ok;
2176 if (tuple->ob_type->tp_as_sequence &&
2177 tuple->ob_type->tp_as_sequence->sq_item) {
2178 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2179 } else {
2180 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2181 goto Fail_1;
2183 if (func == Py_None) {
2184 Py_INCREF(item);
2185 good = item;
2187 else {
2188 PyObject *arg = Py_BuildValue("(O)", item);
2189 if (arg == NULL)
2190 goto Fail_1;
2191 good = PyEval_CallObject(func, arg);
2192 Py_DECREF(arg);
2193 if (good == NULL)
2194 goto Fail_1;
2196 ok = PyObject_IsTrue(good);
2197 Py_DECREF(good);
2198 if (ok) {
2199 Py_INCREF(item);
2200 if (PyTuple_SetItem(result, j++, item) < 0)
2201 goto Fail_1;
2205 if (_PyTuple_Resize(&result, j) < 0)
2206 return NULL;
2208 return result;
2210 Fail_1:
2211 Py_DECREF(result);
2212 return NULL;
2216 /* Helper for filter(): filter a string through a function */
2218 static PyObject *
2219 filterstring(PyObject *func, PyObject *strobj)
2221 PyObject *result;
2222 register int i, j;
2223 int len = PyString_Size(strobj);
2224 int outlen = len;
2226 if (func == Py_None) {
2227 /* If it's a real string we can return the original,
2228 * as no character is ever false and __getitem__
2229 * does return this character. If it's a subclass
2230 * we must go through the __getitem__ loop */
2231 if (PyString_CheckExact(strobj)) {
2232 Py_INCREF(strobj);
2233 return strobj;
2236 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2237 return NULL;
2239 for (i = j = 0; i < len; ++i) {
2240 PyObject *item;
2241 int ok;
2243 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2244 if (item == NULL)
2245 goto Fail_1;
2246 if (func==Py_None) {
2247 ok = 1;
2248 } else {
2249 PyObject *arg, *good;
2250 arg = Py_BuildValue("(O)", item);
2251 if (arg == NULL) {
2252 Py_DECREF(item);
2253 goto Fail_1;
2255 good = PyEval_CallObject(func, arg);
2256 Py_DECREF(arg);
2257 if (good == NULL) {
2258 Py_DECREF(item);
2259 goto Fail_1;
2261 ok = PyObject_IsTrue(good);
2262 Py_DECREF(good);
2264 if (ok) {
2265 int reslen;
2266 if (!PyString_Check(item)) {
2267 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2268 " __getitem__ returned different type");
2269 Py_DECREF(item);
2270 goto Fail_1;
2272 reslen = PyString_GET_SIZE(item);
2273 if (reslen == 1) {
2274 PyString_AS_STRING(result)[j++] =
2275 PyString_AS_STRING(item)[0];
2276 } else {
2277 /* do we need more space? */
2278 int need = j + reslen + len-i-1;
2279 if (need > outlen) {
2280 /* overallocate, to avoid reallocations */
2281 if (need<2*outlen)
2282 need = 2*outlen;
2283 if (_PyString_Resize(&result, need)) {
2284 Py_DECREF(item);
2285 return NULL;
2287 outlen = need;
2289 memcpy(
2290 PyString_AS_STRING(result) + j,
2291 PyString_AS_STRING(item),
2292 reslen
2294 j += reslen;
2297 Py_DECREF(item);
2300 if (j < outlen)
2301 _PyString_Resize(&result, j);
2303 return result;
2305 Fail_1:
2306 Py_DECREF(result);
2307 return NULL;
2310 #ifdef Py_USING_UNICODE
2311 /* Helper for filter(): filter a Unicode object through a function */
2313 static PyObject *
2314 filterunicode(PyObject *func, PyObject *strobj)
2316 PyObject *result;
2317 register int i, j;
2318 int len = PyUnicode_GetSize(strobj);
2319 int outlen = len;
2321 if (func == Py_None) {
2322 /* If it's a real string we can return the original,
2323 * as no character is ever false and __getitem__
2324 * does return this character. If it's a subclass
2325 * we must go through the __getitem__ loop */
2326 if (PyUnicode_CheckExact(strobj)) {
2327 Py_INCREF(strobj);
2328 return strobj;
2331 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2332 return NULL;
2334 for (i = j = 0; i < len; ++i) {
2335 PyObject *item, *arg, *good;
2336 int ok;
2338 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2339 if (item == NULL)
2340 goto Fail_1;
2341 if (func == Py_None) {
2342 ok = 1;
2343 } else {
2344 arg = Py_BuildValue("(O)", item);
2345 if (arg == NULL) {
2346 Py_DECREF(item);
2347 goto Fail_1;
2349 good = PyEval_CallObject(func, arg);
2350 Py_DECREF(arg);
2351 if (good == NULL) {
2352 Py_DECREF(item);
2353 goto Fail_1;
2355 ok = PyObject_IsTrue(good);
2356 Py_DECREF(good);
2358 if (ok) {
2359 int reslen;
2360 if (!PyUnicode_Check(item)) {
2361 PyErr_SetString(PyExc_TypeError, "can't filter unicode to unicode:"
2362 " __getitem__ returned different type");
2363 Py_DECREF(item);
2364 goto Fail_1;
2366 reslen = PyUnicode_GET_SIZE(item);
2367 if (reslen == 1) {
2368 PyUnicode_AS_UNICODE(result)[j++] =
2369 PyUnicode_AS_UNICODE(item)[0];
2370 } else {
2371 /* do we need more space? */
2372 int need = j + reslen + len-i-1;
2373 if (need > outlen) {
2374 /* overallocate, to avoid reallocations */
2375 if (need<2*outlen)
2376 need = 2*outlen;
2377 if (PyUnicode_Resize(&result, need)) {
2378 Py_DECREF(item);
2379 goto Fail_1;
2381 outlen = need;
2383 memcpy(
2384 PyUnicode_AS_UNICODE(result) + j,
2385 PyUnicode_AS_UNICODE(item),
2386 reslen*sizeof(Py_UNICODE)
2388 j += reslen;
2391 Py_DECREF(item);
2394 if (j < outlen)
2395 PyUnicode_Resize(&result, j);
2397 return result;
2399 Fail_1:
2400 Py_DECREF(result);
2401 return NULL;
2403 #endif