Misc/NEWS entries for issue 7117.
[python.git] / Python / bltinmodule.c
bloba8d8d97399c67ecc0c0f6e246af27a8af9950c46
1 /* Built-in functions */
3 #include "Python.h"
4 #include "Python-ast.h"
6 #include "node.h"
7 #include "code.h"
8 #include "eval.h"
10 #include <ctype.h>
11 #include <float.h> /* for DBL_MANT_DIG and friends */
13 #ifdef RISCOS
14 #include "unixstuff.h"
15 #endif
17 /* The default encoding used by the platform file system APIs
18 Can remain NULL for all platforms that don't have such a concept
20 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
21 const char *Py_FileSystemDefaultEncoding = "mbcs";
22 #elif defined(__APPLE__)
23 const char *Py_FileSystemDefaultEncoding = "utf-8";
24 #else
25 const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
26 #endif
28 /* Forward */
29 static PyObject *filterstring(PyObject *, PyObject *);
30 #ifdef Py_USING_UNICODE
31 static PyObject *filterunicode(PyObject *, PyObject *);
32 #endif
33 static PyObject *filtertuple (PyObject *, PyObject *);
35 static PyObject *
36 builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
38 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
39 "level", 0};
40 char *name;
41 PyObject *globals = NULL;
42 PyObject *locals = NULL;
43 PyObject *fromlist = NULL;
44 int level = -1;
46 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
47 kwlist, &name, &globals, &locals, &fromlist, &level))
48 return NULL;
49 return PyImport_ImportModuleLevel(name, globals, locals,
50 fromlist, level);
53 PyDoc_STRVAR(import_doc,
54 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
55 \n\
56 Import a module. The globals are only used to determine the context;\n\
57 they are not modified. The locals are currently unused. The fromlist\n\
58 should be a list of names to emulate ``from name import ...'', or an\n\
59 empty list to emulate ``import name''.\n\
60 When importing a module from a package, note that __import__('A.B', ...)\n\
61 returns package A when fromlist is empty, but its submodule B when\n\
62 fromlist is not empty. Level is used to determine whether to perform \n\
63 absolute or relative imports. -1 is the original strategy of attempting\n\
64 both absolute and relative imports, 0 is absolute, a positive number\n\
65 is the number of parent directories to search relative to the current module.");
68 static PyObject *
69 builtin_abs(PyObject *self, PyObject *v)
71 return PyNumber_Absolute(v);
74 PyDoc_STRVAR(abs_doc,
75 "abs(number) -> number\n\
76 \n\
77 Return the absolute value of the argument.");
79 static PyObject *
80 builtin_all(PyObject *self, PyObject *v)
82 PyObject *it, *item;
83 PyObject *(*iternext)(PyObject *);
84 int cmp;
86 it = PyObject_GetIter(v);
87 if (it == NULL)
88 return NULL;
89 iternext = *Py_TYPE(it)->tp_iternext;
91 for (;;) {
92 item = iternext(it);
93 if (item == NULL)
94 break;
95 cmp = PyObject_IsTrue(item);
96 Py_DECREF(item);
97 if (cmp < 0) {
98 Py_DECREF(it);
99 return NULL;
101 if (cmp == 0) {
102 Py_DECREF(it);
103 Py_RETURN_FALSE;
106 Py_DECREF(it);
107 if (PyErr_Occurred()) {
108 if (PyErr_ExceptionMatches(PyExc_StopIteration))
109 PyErr_Clear();
110 else
111 return NULL;
113 Py_RETURN_TRUE;
116 PyDoc_STRVAR(all_doc,
117 "all(iterable) -> bool\n\
119 Return True if bool(x) is True for all values x in the iterable.");
121 static PyObject *
122 builtin_any(PyObject *self, PyObject *v)
124 PyObject *it, *item;
125 PyObject *(*iternext)(PyObject *);
126 int cmp;
128 it = PyObject_GetIter(v);
129 if (it == NULL)
130 return NULL;
131 iternext = *Py_TYPE(it)->tp_iternext;
133 for (;;) {
134 item = iternext(it);
135 if (item == NULL)
136 break;
137 cmp = PyObject_IsTrue(item);
138 Py_DECREF(item);
139 if (cmp < 0) {
140 Py_DECREF(it);
141 return NULL;
143 if (cmp == 1) {
144 Py_DECREF(it);
145 Py_RETURN_TRUE;
148 Py_DECREF(it);
149 if (PyErr_Occurred()) {
150 if (PyErr_ExceptionMatches(PyExc_StopIteration))
151 PyErr_Clear();
152 else
153 return NULL;
155 Py_RETURN_FALSE;
158 PyDoc_STRVAR(any_doc,
159 "any(iterable) -> bool\n\
161 Return True if bool(x) is True for any x in the iterable.");
163 static PyObject *
164 builtin_apply(PyObject *self, PyObject *args)
166 PyObject *func, *alist = NULL, *kwdict = NULL;
167 PyObject *t = NULL, *retval = NULL;
169 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
170 "use func(*args, **kwargs)", 1) < 0)
171 return NULL;
173 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
174 return NULL;
175 if (alist != NULL) {
176 if (!PyTuple_Check(alist)) {
177 if (!PySequence_Check(alist)) {
178 PyErr_Format(PyExc_TypeError,
179 "apply() arg 2 expected sequence, found %s",
180 alist->ob_type->tp_name);
181 return NULL;
183 t = PySequence_Tuple(alist);
184 if (t == NULL)
185 return NULL;
186 alist = t;
189 if (kwdict != NULL && !PyDict_Check(kwdict)) {
190 PyErr_Format(PyExc_TypeError,
191 "apply() arg 3 expected dictionary, found %s",
192 kwdict->ob_type->tp_name);
193 goto finally;
195 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
196 finally:
197 Py_XDECREF(t);
198 return retval;
201 PyDoc_STRVAR(apply_doc,
202 "apply(object[, args[, kwargs]]) -> value\n\
204 Call a callable object with positional arguments taken from the tuple args,\n\
205 and keyword arguments taken from the optional dictionary kwargs.\n\
206 Note that classes are callable, as are instances with a __call__() method.\n\
208 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
209 function(*args, **keywords).");
212 static PyObject *
213 builtin_bin(PyObject *self, PyObject *v)
215 return PyNumber_ToBase(v, 2);
218 PyDoc_STRVAR(bin_doc,
219 "bin(number) -> string\n\
221 Return the binary representation of an integer or long integer.");
224 static PyObject *
225 builtin_callable(PyObject *self, PyObject *v)
227 if (PyErr_WarnPy3k("callable() not supported in 3.x; "
228 "use isinstance(x, collections.Callable)", 1) < 0)
229 return NULL;
230 return PyBool_FromLong((long)PyCallable_Check(v));
233 PyDoc_STRVAR(callable_doc,
234 "callable(object) -> bool\n\
236 Return whether the object is callable (i.e., some kind of function).\n\
237 Note that classes are callable, as are instances with a __call__() method.");
240 static PyObject *
241 builtin_filter(PyObject *self, PyObject *args)
243 PyObject *func, *seq, *result, *it, *arg;
244 Py_ssize_t len; /* guess for result list size */
245 register Py_ssize_t j;
247 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
248 return NULL;
250 /* Strings and tuples return a result of the same type. */
251 if (PyString_Check(seq))
252 return filterstring(func, seq);
253 #ifdef Py_USING_UNICODE
254 if (PyUnicode_Check(seq))
255 return filterunicode(func, seq);
256 #endif
257 if (PyTuple_Check(seq))
258 return filtertuple(func, seq);
260 /* Pre-allocate argument list tuple. */
261 arg = PyTuple_New(1);
262 if (arg == NULL)
263 return NULL;
265 /* Get iterator. */
266 it = PyObject_GetIter(seq);
267 if (it == NULL)
268 goto Fail_arg;
270 /* Guess a result list size. */
271 len = _PyObject_LengthHint(seq, 8);
272 if (len == -1)
273 goto Fail_it;
275 /* Get a result list. */
276 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
277 /* Eww - can modify the list in-place. */
278 Py_INCREF(seq);
279 result = seq;
281 else {
282 result = PyList_New(len);
283 if (result == NULL)
284 goto Fail_it;
287 /* Build the result list. */
288 j = 0;
289 for (;;) {
290 PyObject *item;
291 int ok;
293 item = PyIter_Next(it);
294 if (item == NULL) {
295 if (PyErr_Occurred())
296 goto Fail_result_it;
297 break;
300 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
301 ok = PyObject_IsTrue(item);
303 else {
304 PyObject *good;
305 PyTuple_SET_ITEM(arg, 0, item);
306 good = PyObject_Call(func, arg, NULL);
307 PyTuple_SET_ITEM(arg, 0, NULL);
308 if (good == NULL) {
309 Py_DECREF(item);
310 goto Fail_result_it;
312 ok = PyObject_IsTrue(good);
313 Py_DECREF(good);
315 if (ok) {
316 if (j < len)
317 PyList_SET_ITEM(result, j, item);
318 else {
319 int status = PyList_Append(result, item);
320 Py_DECREF(item);
321 if (status < 0)
322 goto Fail_result_it;
324 ++j;
326 else
327 Py_DECREF(item);
331 /* Cut back result list if len is too big. */
332 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
333 goto Fail_result_it;
335 Py_DECREF(it);
336 Py_DECREF(arg);
337 return result;
339 Fail_result_it:
340 Py_DECREF(result);
341 Fail_it:
342 Py_DECREF(it);
343 Fail_arg:
344 Py_DECREF(arg);
345 return NULL;
348 PyDoc_STRVAR(filter_doc,
349 "filter(function or None, sequence) -> list, tuple, or string\n"
350 "\n"
351 "Return those items of sequence for which function(item) is true. If\n"
352 "function is None, return the items that are true. If sequence is a tuple\n"
353 "or string, return the same type, else return a list.");
355 static PyObject *
356 builtin_format(PyObject *self, PyObject *args)
358 PyObject *value;
359 PyObject *format_spec = NULL;
361 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
362 return NULL;
364 return PyObject_Format(value, format_spec);
367 PyDoc_STRVAR(format_doc,
368 "format(value[, format_spec]) -> string\n\
370 Returns value.__format__(format_spec)\n\
371 format_spec defaults to \"\"");
373 static PyObject *
374 builtin_chr(PyObject *self, PyObject *args)
376 long x;
377 char s[1];
379 if (!PyArg_ParseTuple(args, "l:chr", &x))
380 return NULL;
381 if (x < 0 || x >= 256) {
382 PyErr_SetString(PyExc_ValueError,
383 "chr() arg not in range(256)");
384 return NULL;
386 s[0] = (char)x;
387 return PyString_FromStringAndSize(s, 1);
390 PyDoc_STRVAR(chr_doc,
391 "chr(i) -> character\n\
393 Return a string of one character with ordinal i; 0 <= i < 256.");
396 #ifdef Py_USING_UNICODE
397 static PyObject *
398 builtin_unichr(PyObject *self, PyObject *args)
400 int x;
402 if (!PyArg_ParseTuple(args, "i:unichr", &x))
403 return NULL;
405 return PyUnicode_FromOrdinal(x);
408 PyDoc_STRVAR(unichr_doc,
409 "unichr(i) -> Unicode character\n\
411 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
412 #endif
415 static PyObject *
416 builtin_cmp(PyObject *self, PyObject *args)
418 PyObject *a, *b;
419 int c;
421 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
422 return NULL;
423 if (PyObject_Cmp(a, b, &c) < 0)
424 return NULL;
425 return PyInt_FromLong((long)c);
428 PyDoc_STRVAR(cmp_doc,
429 "cmp(x, y) -> integer\n\
431 Return negative if x<y, zero if x==y, positive if x>y.");
434 static PyObject *
435 builtin_coerce(PyObject *self, PyObject *args)
437 PyObject *v, *w;
438 PyObject *res;
440 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
441 return NULL;
443 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
444 return NULL;
445 if (PyNumber_Coerce(&v, &w) < 0)
446 return NULL;
447 res = PyTuple_Pack(2, v, w);
448 Py_DECREF(v);
449 Py_DECREF(w);
450 return res;
453 PyDoc_STRVAR(coerce_doc,
454 "coerce(x, y) -> (x1, y1)\n\
456 Return a tuple consisting of the two numeric arguments converted to\n\
457 a common type, using the same rules as used by arithmetic operations.\n\
458 If coercion is not possible, raise TypeError.");
460 static PyObject *
461 builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
463 char *str;
464 char *filename;
465 char *startstr;
466 int mode = -1;
467 int dont_inherit = 0;
468 int supplied_flags = 0;
469 PyCompilerFlags cf;
470 PyObject *result = NULL, *cmd, *tmp = NULL;
471 Py_ssize_t length;
472 static char *kwlist[] = {"source", "filename", "mode", "flags",
473 "dont_inherit", NULL};
474 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
476 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
477 kwlist, &cmd, &filename, &startstr,
478 &supplied_flags, &dont_inherit))
479 return NULL;
481 cf.cf_flags = supplied_flags;
483 if (supplied_flags &
484 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
486 PyErr_SetString(PyExc_ValueError,
487 "compile(): unrecognised flags");
488 return NULL;
490 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
492 if (!dont_inherit) {
493 PyEval_MergeCompilerFlags(&cf);
496 if (strcmp(startstr, "exec") == 0)
497 mode = 0;
498 else if (strcmp(startstr, "eval") == 0)
499 mode = 1;
500 else if (strcmp(startstr, "single") == 0)
501 mode = 2;
502 else {
503 PyErr_SetString(PyExc_ValueError,
504 "compile() arg 3 must be 'exec', 'eval' or 'single'");
505 return NULL;
508 if (PyAST_Check(cmd)) {
509 if (supplied_flags & PyCF_ONLY_AST) {
510 Py_INCREF(cmd);
511 result = cmd;
513 else {
514 PyArena *arena;
515 mod_ty mod;
517 arena = PyArena_New();
518 mod = PyAST_obj2mod(cmd, arena, mode);
519 if (mod == NULL) {
520 PyArena_Free(arena);
521 return NULL;
523 result = (PyObject*)PyAST_Compile(mod, filename,
524 &cf, arena);
525 PyArena_Free(arena);
527 return result;
530 #ifdef Py_USING_UNICODE
531 if (PyUnicode_Check(cmd)) {
532 tmp = PyUnicode_AsUTF8String(cmd);
533 if (tmp == NULL)
534 return NULL;
535 cmd = tmp;
536 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
538 #endif
540 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
541 goto cleanup;
542 if ((size_t)length != strlen(str)) {
543 PyErr_SetString(PyExc_TypeError,
544 "compile() expected string without null bytes");
545 goto cleanup;
547 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
548 cleanup:
549 Py_XDECREF(tmp);
550 return result;
553 PyDoc_STRVAR(compile_doc,
554 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
556 Compile the source string (a Python module, statement or expression)\n\
557 into a code object that can be executed by the exec statement or eval().\n\
558 The filename will be used for run-time error messages.\n\
559 The mode must be 'exec' to compile a module, 'single' to compile a\n\
560 single (interactive) statement, or 'eval' to compile an expression.\n\
561 The flags argument, if present, controls which future statements influence\n\
562 the compilation of the code.\n\
563 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
564 the effects of any future statements in effect in the code calling\n\
565 compile; if absent or zero these statements do influence the compilation,\n\
566 in addition to any features explicitly specified.");
568 static PyObject *
569 builtin_dir(PyObject *self, PyObject *args)
571 PyObject *arg = NULL;
573 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
574 return NULL;
575 return PyObject_Dir(arg);
578 PyDoc_STRVAR(dir_doc,
579 "dir([object]) -> list of strings\n"
580 "\n"
581 "If called without an argument, return the names in the current scope.\n"
582 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
583 "of the given object, and of attributes reachable from it.\n"
584 "If the object supplies a method named __dir__, it will be used; otherwise\n"
585 "the default dir() logic is used and returns:\n"
586 " for a module object: the module's attributes.\n"
587 " for a class object: its attributes, and recursively the attributes\n"
588 " of its bases.\n"
589 " for any other object: its attributes, its class's attributes, and\n"
590 " recursively the attributes of its class's base classes.");
592 static PyObject *
593 builtin_divmod(PyObject *self, PyObject *args)
595 PyObject *v, *w;
597 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
598 return NULL;
599 return PyNumber_Divmod(v, w);
602 PyDoc_STRVAR(divmod_doc,
603 "divmod(x, y) -> (div, mod)\n\
605 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
608 static PyObject *
609 builtin_eval(PyObject *self, PyObject *args)
611 PyObject *cmd, *result, *tmp = NULL;
612 PyObject *globals = Py_None, *locals = Py_None;
613 char *str;
614 PyCompilerFlags cf;
616 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
617 return NULL;
618 if (locals != Py_None && !PyMapping_Check(locals)) {
619 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
620 return NULL;
622 if (globals != Py_None && !PyDict_Check(globals)) {
623 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
624 "globals must be a real dict; try eval(expr, {}, mapping)"
625 : "globals must be a dict");
626 return NULL;
628 if (globals == Py_None) {
629 globals = PyEval_GetGlobals();
630 if (locals == Py_None)
631 locals = PyEval_GetLocals();
633 else if (locals == Py_None)
634 locals = globals;
636 if (globals == NULL || locals == NULL) {
637 PyErr_SetString(PyExc_TypeError,
638 "eval must be given globals and locals "
639 "when called without a frame");
640 return NULL;
643 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
644 if (PyDict_SetItemString(globals, "__builtins__",
645 PyEval_GetBuiltins()) != 0)
646 return NULL;
649 if (PyCode_Check(cmd)) {
650 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
651 PyErr_SetString(PyExc_TypeError,
652 "code object passed to eval() may not contain free variables");
653 return NULL;
655 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
658 if (!PyString_Check(cmd) &&
659 !PyUnicode_Check(cmd)) {
660 PyErr_SetString(PyExc_TypeError,
661 "eval() arg 1 must be a string or code object");
662 return NULL;
664 cf.cf_flags = 0;
666 #ifdef Py_USING_UNICODE
667 if (PyUnicode_Check(cmd)) {
668 tmp = PyUnicode_AsUTF8String(cmd);
669 if (tmp == NULL)
670 return NULL;
671 cmd = tmp;
672 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
674 #endif
675 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
676 Py_XDECREF(tmp);
677 return NULL;
679 while (*str == ' ' || *str == '\t')
680 str++;
682 (void)PyEval_MergeCompilerFlags(&cf);
683 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
684 Py_XDECREF(tmp);
685 return result;
688 PyDoc_STRVAR(eval_doc,
689 "eval(source[, globals[, locals]]) -> value\n\
691 Evaluate the source in the context of globals and locals.\n\
692 The source may be a string representing a Python expression\n\
693 or a code object as returned by compile().\n\
694 The globals must be a dictionary and locals can be any mapping,\n\
695 defaulting to the current globals and locals.\n\
696 If only globals is given, locals defaults to it.\n");
699 static PyObject *
700 builtin_execfile(PyObject *self, PyObject *args)
702 char *filename;
703 PyObject *globals = Py_None, *locals = Py_None;
704 PyObject *res;
705 FILE* fp = NULL;
706 PyCompilerFlags cf;
707 int exists;
709 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
710 1) < 0)
711 return NULL;
713 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
714 &filename,
715 &PyDict_Type, &globals,
716 &locals))
717 return NULL;
718 if (locals != Py_None && !PyMapping_Check(locals)) {
719 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
720 return NULL;
722 if (globals == Py_None) {
723 globals = PyEval_GetGlobals();
724 if (locals == Py_None)
725 locals = PyEval_GetLocals();
727 else if (locals == Py_None)
728 locals = globals;
729 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
730 if (PyDict_SetItemString(globals, "__builtins__",
731 PyEval_GetBuiltins()) != 0)
732 return NULL;
735 exists = 0;
736 /* Test for existence or directory. */
737 #if defined(PLAN9)
739 Dir *d;
741 if ((d = dirstat(filename))!=nil) {
742 if(d->mode & DMDIR)
743 werrstr("is a directory");
744 else
745 exists = 1;
746 free(d);
749 #elif defined(RISCOS)
750 if (object_exists(filename)) {
751 if (isdir(filename))
752 errno = EISDIR;
753 else
754 exists = 1;
756 #else /* standard Posix */
758 struct stat s;
759 if (stat(filename, &s) == 0) {
760 if (S_ISDIR(s.st_mode))
761 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
762 errno = EOS2ERR;
763 # else
764 errno = EISDIR;
765 # endif
766 else
767 exists = 1;
770 #endif
772 if (exists) {
773 Py_BEGIN_ALLOW_THREADS
774 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
775 Py_END_ALLOW_THREADS
777 if (fp == NULL) {
778 exists = 0;
782 if (!exists) {
783 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
784 return NULL;
786 cf.cf_flags = 0;
787 if (PyEval_MergeCompilerFlags(&cf))
788 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
789 locals, 1, &cf);
790 else
791 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
792 locals, 1);
793 return res;
796 PyDoc_STRVAR(execfile_doc,
797 "execfile(filename[, globals[, locals]])\n\
799 Read and execute a Python script from a file.\n\
800 The globals and locals are dictionaries, defaulting to the current\n\
801 globals and locals. If only globals is given, locals defaults to it.");
804 static PyObject *
805 builtin_getattr(PyObject *self, PyObject *args)
807 PyObject *v, *result, *dflt = NULL;
808 PyObject *name;
810 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
811 return NULL;
812 #ifdef Py_USING_UNICODE
813 if (PyUnicode_Check(name)) {
814 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
815 if (name == NULL)
816 return NULL;
818 #endif
820 if (!PyString_Check(name)) {
821 PyErr_SetString(PyExc_TypeError,
822 "getattr(): attribute name must be string");
823 return NULL;
825 result = PyObject_GetAttr(v, name);
826 if (result == NULL && dflt != NULL &&
827 PyErr_ExceptionMatches(PyExc_AttributeError))
829 PyErr_Clear();
830 Py_INCREF(dflt);
831 result = dflt;
833 return result;
836 PyDoc_STRVAR(getattr_doc,
837 "getattr(object, name[, default]) -> value\n\
839 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
840 When a default argument is given, it is returned when the attribute doesn't\n\
841 exist; without it, an exception is raised in that case.");
844 static PyObject *
845 builtin_globals(PyObject *self)
847 PyObject *d;
849 d = PyEval_GetGlobals();
850 Py_XINCREF(d);
851 return d;
854 PyDoc_STRVAR(globals_doc,
855 "globals() -> dictionary\n\
857 Return the dictionary containing the current scope's global variables.");
860 static PyObject *
861 builtin_hasattr(PyObject *self, PyObject *args)
863 PyObject *v;
864 PyObject *name;
866 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
867 return NULL;
868 #ifdef Py_USING_UNICODE
869 if (PyUnicode_Check(name)) {
870 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
871 if (name == NULL)
872 return NULL;
874 #endif
876 if (!PyString_Check(name)) {
877 PyErr_SetString(PyExc_TypeError,
878 "hasattr(): attribute name must be string");
879 return NULL;
881 v = PyObject_GetAttr(v, name);
882 if (v == NULL) {
883 if (!PyErr_ExceptionMatches(PyExc_Exception))
884 return NULL;
885 else {
886 PyErr_Clear();
887 Py_INCREF(Py_False);
888 return Py_False;
891 Py_DECREF(v);
892 Py_INCREF(Py_True);
893 return Py_True;
896 PyDoc_STRVAR(hasattr_doc,
897 "hasattr(object, name) -> bool\n\
899 Return whether the object has an attribute with the given name.\n\
900 (This is done by calling getattr(object, name) and catching exceptions.)");
903 static PyObject *
904 builtin_id(PyObject *self, PyObject *v)
906 return PyLong_FromVoidPtr(v);
909 PyDoc_STRVAR(id_doc,
910 "id(object) -> integer\n\
912 Return the identity of an object. This is guaranteed to be unique among\n\
913 simultaneously existing objects. (Hint: it's the object's memory address.)");
916 static PyObject *
917 builtin_map(PyObject *self, PyObject *args)
919 typedef struct {
920 PyObject *it; /* the iterator object */
921 int saw_StopIteration; /* bool: did the iterator end? */
922 } sequence;
924 PyObject *func, *result;
925 sequence *seqs = NULL, *sqp;
926 Py_ssize_t n, len;
927 register int i, j;
929 n = PyTuple_Size(args);
930 if (n < 2) {
931 PyErr_SetString(PyExc_TypeError,
932 "map() requires at least two args");
933 return NULL;
936 func = PyTuple_GetItem(args, 0);
937 n--;
939 if (func == Py_None) {
940 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
941 "use list(...)", 1) < 0)
942 return NULL;
943 if (n == 1) {
944 /* map(None, S) is the same as list(S). */
945 return PySequence_List(PyTuple_GetItem(args, 1));
949 /* Get space for sequence descriptors. Must NULL out the iterator
950 * pointers so that jumping to Fail_2 later doesn't see trash.
952 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
953 PyErr_NoMemory();
954 return NULL;
956 for (i = 0; i < n; ++i) {
957 seqs[i].it = (PyObject*)NULL;
958 seqs[i].saw_StopIteration = 0;
961 /* Do a first pass to obtain iterators for the arguments, and set len
962 * to the largest of their lengths.
964 len = 0;
965 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
966 PyObject *curseq;
967 Py_ssize_t curlen;
969 /* Get iterator. */
970 curseq = PyTuple_GetItem(args, i+1);
971 sqp->it = PyObject_GetIter(curseq);
972 if (sqp->it == NULL) {
973 static char errmsg[] =
974 "argument %d to map() must support iteration";
975 char errbuf[sizeof(errmsg) + 25];
976 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
977 PyErr_SetString(PyExc_TypeError, errbuf);
978 goto Fail_2;
981 /* Update len. */
982 curlen = _PyObject_LengthHint(curseq, 8);
983 if (curlen > len)
984 len = curlen;
987 /* Get space for the result list. */
988 if ((result = (PyObject *) PyList_New(len)) == NULL)
989 goto Fail_2;
991 /* Iterate over the sequences until all have stopped. */
992 for (i = 0; ; ++i) {
993 PyObject *alist, *item=NULL, *value;
994 int numactive = 0;
996 if (func == Py_None && n == 1)
997 alist = NULL;
998 else if ((alist = PyTuple_New(n)) == NULL)
999 goto Fail_1;
1001 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1002 if (sqp->saw_StopIteration) {
1003 Py_INCREF(Py_None);
1004 item = Py_None;
1006 else {
1007 item = PyIter_Next(sqp->it);
1008 if (item)
1009 ++numactive;
1010 else {
1011 if (PyErr_Occurred()) {
1012 Py_XDECREF(alist);
1013 goto Fail_1;
1015 Py_INCREF(Py_None);
1016 item = Py_None;
1017 sqp->saw_StopIteration = 1;
1020 if (alist)
1021 PyTuple_SET_ITEM(alist, j, item);
1022 else
1023 break;
1026 if (!alist)
1027 alist = item;
1029 if (numactive == 0) {
1030 Py_DECREF(alist);
1031 break;
1034 if (func == Py_None)
1035 value = alist;
1036 else {
1037 value = PyEval_CallObject(func, alist);
1038 Py_DECREF(alist);
1039 if (value == NULL)
1040 goto Fail_1;
1042 if (i >= len) {
1043 int status = PyList_Append(result, value);
1044 Py_DECREF(value);
1045 if (status < 0)
1046 goto Fail_1;
1048 else if (PyList_SetItem(result, i, value) < 0)
1049 goto Fail_1;
1052 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1053 goto Fail_1;
1055 goto Succeed;
1057 Fail_1:
1058 Py_DECREF(result);
1059 Fail_2:
1060 result = NULL;
1061 Succeed:
1062 assert(seqs);
1063 for (i = 0; i < n; ++i)
1064 Py_XDECREF(seqs[i].it);
1065 PyMem_DEL(seqs);
1066 return result;
1069 PyDoc_STRVAR(map_doc,
1070 "map(function, sequence[, sequence, ...]) -> list\n\
1072 Return a list of the results of applying the function to the items of\n\
1073 the argument sequence(s). If more than one sequence is given, the\n\
1074 function is called with an argument list consisting of the corresponding\n\
1075 item of each sequence, substituting None for missing values when not all\n\
1076 sequences have the same length. If the function is None, return a list of\n\
1077 the items of the sequence (or a list of tuples if more than one sequence).");
1080 static PyObject *
1081 builtin_next(PyObject *self, PyObject *args)
1083 PyObject *it, *res;
1084 PyObject *def = NULL;
1086 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1087 return NULL;
1088 if (!PyIter_Check(it)) {
1089 PyErr_Format(PyExc_TypeError,
1090 "%.200s object is not an iterator",
1091 it->ob_type->tp_name);
1092 return NULL;
1095 res = (*it->ob_type->tp_iternext)(it);
1096 if (res != NULL) {
1097 return res;
1098 } else if (def != NULL) {
1099 if (PyErr_Occurred()) {
1100 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1101 return NULL;
1102 PyErr_Clear();
1104 Py_INCREF(def);
1105 return def;
1106 } else if (PyErr_Occurred()) {
1107 return NULL;
1108 } else {
1109 PyErr_SetNone(PyExc_StopIteration);
1110 return NULL;
1114 PyDoc_STRVAR(next_doc,
1115 "next(iterator[, default])\n\
1117 Return the next item from the iterator. If default is given and the iterator\n\
1118 is exhausted, it is returned instead of raising StopIteration.");
1121 static PyObject *
1122 builtin_setattr(PyObject *self, PyObject *args)
1124 PyObject *v;
1125 PyObject *name;
1126 PyObject *value;
1128 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1129 return NULL;
1130 if (PyObject_SetAttr(v, name, value) != 0)
1131 return NULL;
1132 Py_INCREF(Py_None);
1133 return Py_None;
1136 PyDoc_STRVAR(setattr_doc,
1137 "setattr(object, name, value)\n\
1139 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1140 ``x.y = v''.");
1143 static PyObject *
1144 builtin_delattr(PyObject *self, PyObject *args)
1146 PyObject *v;
1147 PyObject *name;
1149 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1150 return NULL;
1151 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1152 return NULL;
1153 Py_INCREF(Py_None);
1154 return Py_None;
1157 PyDoc_STRVAR(delattr_doc,
1158 "delattr(object, name)\n\
1160 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1161 ``del x.y''.");
1164 static PyObject *
1165 builtin_hash(PyObject *self, PyObject *v)
1167 long x;
1169 x = PyObject_Hash(v);
1170 if (x == -1)
1171 return NULL;
1172 return PyInt_FromLong(x);
1175 PyDoc_STRVAR(hash_doc,
1176 "hash(object) -> integer\n\
1178 Return a hash value for the object. Two objects with the same value have\n\
1179 the same hash value. The reverse is not necessarily true, but likely.");
1182 static PyObject *
1183 builtin_hex(PyObject *self, PyObject *v)
1185 PyNumberMethods *nb;
1186 PyObject *res;
1188 if ((nb = v->ob_type->tp_as_number) == NULL ||
1189 nb->nb_hex == NULL) {
1190 PyErr_SetString(PyExc_TypeError,
1191 "hex() argument can't be converted to hex");
1192 return NULL;
1194 res = (*nb->nb_hex)(v);
1195 if (res && !PyString_Check(res)) {
1196 PyErr_Format(PyExc_TypeError,
1197 "__hex__ returned non-string (type %.200s)",
1198 res->ob_type->tp_name);
1199 Py_DECREF(res);
1200 return NULL;
1202 return res;
1205 PyDoc_STRVAR(hex_doc,
1206 "hex(number) -> string\n\
1208 Return the hexadecimal representation of an integer or long integer.");
1211 static PyObject *builtin_raw_input(PyObject *, PyObject *);
1213 static PyObject *
1214 builtin_input(PyObject *self, PyObject *args)
1216 PyObject *line;
1217 char *str;
1218 PyObject *res;
1219 PyObject *globals, *locals;
1220 PyCompilerFlags cf;
1222 line = builtin_raw_input(self, args);
1223 if (line == NULL)
1224 return line;
1225 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1226 return NULL;
1227 while (*str == ' ' || *str == '\t')
1228 str++;
1229 globals = PyEval_GetGlobals();
1230 locals = PyEval_GetLocals();
1231 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1232 if (PyDict_SetItemString(globals, "__builtins__",
1233 PyEval_GetBuiltins()) != 0)
1234 return NULL;
1236 cf.cf_flags = 0;
1237 PyEval_MergeCompilerFlags(&cf);
1238 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1239 Py_DECREF(line);
1240 return res;
1243 PyDoc_STRVAR(input_doc,
1244 "input([prompt]) -> value\n\
1246 Equivalent to eval(raw_input(prompt)).");
1249 static PyObject *
1250 builtin_intern(PyObject *self, PyObject *args)
1252 PyObject *s;
1253 if (!PyArg_ParseTuple(args, "S:intern", &s))
1254 return NULL;
1255 if (!PyString_CheckExact(s)) {
1256 PyErr_SetString(PyExc_TypeError,
1257 "can't intern subclass of string");
1258 return NULL;
1260 Py_INCREF(s);
1261 PyString_InternInPlace(&s);
1262 return s;
1265 PyDoc_STRVAR(intern_doc,
1266 "intern(string) -> string\n\
1268 ``Intern'' the given string. This enters the string in the (global)\n\
1269 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1270 Return the string itself or the previously interned string object with the\n\
1271 same value.");
1274 static PyObject *
1275 builtin_iter(PyObject *self, PyObject *args)
1277 PyObject *v, *w = NULL;
1279 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1280 return NULL;
1281 if (w == NULL)
1282 return PyObject_GetIter(v);
1283 if (!PyCallable_Check(v)) {
1284 PyErr_SetString(PyExc_TypeError,
1285 "iter(v, w): v must be callable");
1286 return NULL;
1288 return PyCallIter_New(v, w);
1291 PyDoc_STRVAR(iter_doc,
1292 "iter(collection) -> iterator\n\
1293 iter(callable, sentinel) -> iterator\n\
1295 Get an iterator from an object. In the first form, the argument must\n\
1296 supply its own iterator, or be a sequence.\n\
1297 In the second form, the callable is called until it returns the sentinel.");
1300 static PyObject *
1301 builtin_len(PyObject *self, PyObject *v)
1303 Py_ssize_t res;
1305 res = PyObject_Size(v);
1306 if (res < 0 && PyErr_Occurred())
1307 return NULL;
1308 return PyInt_FromSsize_t(res);
1311 PyDoc_STRVAR(len_doc,
1312 "len(object) -> integer\n\
1314 Return the number of items of a sequence or mapping.");
1317 static PyObject *
1318 builtin_locals(PyObject *self)
1320 PyObject *d;
1322 d = PyEval_GetLocals();
1323 Py_XINCREF(d);
1324 return d;
1327 PyDoc_STRVAR(locals_doc,
1328 "locals() -> dictionary\n\
1330 Update and return a dictionary containing the current scope's local variables.");
1333 static PyObject *
1334 min_max(PyObject *args, PyObject *kwds, int op)
1336 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1337 const char *name = op == Py_LT ? "min" : "max";
1339 if (PyTuple_Size(args) > 1)
1340 v = args;
1341 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1342 return NULL;
1344 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1345 keyfunc = PyDict_GetItemString(kwds, "key");
1346 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1347 PyErr_Format(PyExc_TypeError,
1348 "%s() got an unexpected keyword argument", name);
1349 return NULL;
1351 Py_INCREF(keyfunc);
1354 it = PyObject_GetIter(v);
1355 if (it == NULL) {
1356 Py_XDECREF(keyfunc);
1357 return NULL;
1360 maxitem = NULL; /* the result */
1361 maxval = NULL; /* the value associated with the result */
1362 while (( item = PyIter_Next(it) )) {
1363 /* get the value from the key function */
1364 if (keyfunc != NULL) {
1365 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1366 if (val == NULL)
1367 goto Fail_it_item;
1369 /* no key function; the value is the item */
1370 else {
1371 val = item;
1372 Py_INCREF(val);
1375 /* maximum value and item are unset; set them */
1376 if (maxval == NULL) {
1377 maxitem = item;
1378 maxval = val;
1380 /* maximum value and item are set; update them as necessary */
1381 else {
1382 int cmp = PyObject_RichCompareBool(val, maxval, op);
1383 if (cmp < 0)
1384 goto Fail_it_item_and_val;
1385 else if (cmp > 0) {
1386 Py_DECREF(maxval);
1387 Py_DECREF(maxitem);
1388 maxval = val;
1389 maxitem = item;
1391 else {
1392 Py_DECREF(item);
1393 Py_DECREF(val);
1397 if (PyErr_Occurred())
1398 goto Fail_it;
1399 if (maxval == NULL) {
1400 PyErr_Format(PyExc_ValueError,
1401 "%s() arg is an empty sequence", name);
1402 assert(maxitem == NULL);
1404 else
1405 Py_DECREF(maxval);
1406 Py_DECREF(it);
1407 Py_XDECREF(keyfunc);
1408 return maxitem;
1410 Fail_it_item_and_val:
1411 Py_DECREF(val);
1412 Fail_it_item:
1413 Py_DECREF(item);
1414 Fail_it:
1415 Py_XDECREF(maxval);
1416 Py_XDECREF(maxitem);
1417 Py_DECREF(it);
1418 Py_XDECREF(keyfunc);
1419 return NULL;
1422 static PyObject *
1423 builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1425 return min_max(args, kwds, Py_LT);
1428 PyDoc_STRVAR(min_doc,
1429 "min(iterable[, key=func]) -> value\n\
1430 min(a, b, c, ...[, key=func]) -> value\n\
1432 With a single iterable argument, return its smallest item.\n\
1433 With two or more arguments, return the smallest argument.");
1436 static PyObject *
1437 builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1439 return min_max(args, kwds, Py_GT);
1442 PyDoc_STRVAR(max_doc,
1443 "max(iterable[, key=func]) -> value\n\
1444 max(a, b, c, ...[, key=func]) -> value\n\
1446 With a single iterable argument, return its largest item.\n\
1447 With two or more arguments, return the largest argument.");
1450 static PyObject *
1451 builtin_oct(PyObject *self, PyObject *v)
1453 PyNumberMethods *nb;
1454 PyObject *res;
1456 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1457 nb->nb_oct == NULL) {
1458 PyErr_SetString(PyExc_TypeError,
1459 "oct() argument can't be converted to oct");
1460 return NULL;
1462 res = (*nb->nb_oct)(v);
1463 if (res && !PyString_Check(res)) {
1464 PyErr_Format(PyExc_TypeError,
1465 "__oct__ returned non-string (type %.200s)",
1466 res->ob_type->tp_name);
1467 Py_DECREF(res);
1468 return NULL;
1470 return res;
1473 PyDoc_STRVAR(oct_doc,
1474 "oct(number) -> string\n\
1476 Return the octal representation of an integer or long integer.");
1479 static PyObject *
1480 builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1482 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
1485 PyDoc_STRVAR(open_doc,
1486 "open(name[, mode[, buffering]]) -> file object\n\
1488 Open a file using the file() type, returns a file object. This is the\n\
1489 preferred way to open a file. See file.__doc__ for further information.");
1492 static PyObject *
1493 builtin_ord(PyObject *self, PyObject* obj)
1495 long ord;
1496 Py_ssize_t size;
1498 if (PyString_Check(obj)) {
1499 size = PyString_GET_SIZE(obj);
1500 if (size == 1) {
1501 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1502 return PyInt_FromLong(ord);
1504 } else if (PyByteArray_Check(obj)) {
1505 size = PyByteArray_GET_SIZE(obj);
1506 if (size == 1) {
1507 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1508 return PyInt_FromLong(ord);
1511 #ifdef Py_USING_UNICODE
1512 } else if (PyUnicode_Check(obj)) {
1513 size = PyUnicode_GET_SIZE(obj);
1514 if (size == 1) {
1515 ord = (long)*PyUnicode_AS_UNICODE(obj);
1516 return PyInt_FromLong(ord);
1518 #endif
1519 } else {
1520 PyErr_Format(PyExc_TypeError,
1521 "ord() expected string of length 1, but " \
1522 "%.200s found", obj->ob_type->tp_name);
1523 return NULL;
1526 PyErr_Format(PyExc_TypeError,
1527 "ord() expected a character, "
1528 "but string of length %zd found",
1529 size);
1530 return NULL;
1533 PyDoc_STRVAR(ord_doc,
1534 "ord(c) -> integer\n\
1536 Return the integer ordinal of a one-character string.");
1539 static PyObject *
1540 builtin_pow(PyObject *self, PyObject *args)
1542 PyObject *v, *w, *z = Py_None;
1544 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1545 return NULL;
1546 return PyNumber_Power(v, w, z);
1549 PyDoc_STRVAR(pow_doc,
1550 "pow(x, y[, z]) -> number\n\
1552 With two arguments, equivalent to x**y. With three arguments,\n\
1553 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1556 static PyObject *
1557 builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1559 static char *kwlist[] = {"sep", "end", "file", 0};
1560 static PyObject *dummy_args = NULL;
1561 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1562 static PyObject *str_newline = NULL, *str_space = NULL;
1563 PyObject *newline, *space;
1564 PyObject *sep = NULL, *end = NULL, *file = NULL;
1565 int i, err, use_unicode = 0;
1567 if (dummy_args == NULL) {
1568 if (!(dummy_args = PyTuple_New(0)))
1569 return NULL;
1571 if (str_newline == NULL) {
1572 str_newline = PyString_FromString("\n");
1573 if (str_newline == NULL)
1574 return NULL;
1575 str_space = PyString_FromString(" ");
1576 if (str_space == NULL) {
1577 Py_CLEAR(str_newline);
1578 return NULL;
1580 unicode_newline = PyUnicode_FromString("\n");
1581 if (unicode_newline == NULL) {
1582 Py_CLEAR(str_newline);
1583 Py_CLEAR(str_space);
1584 return NULL;
1586 unicode_space = PyUnicode_FromString(" ");
1587 if (unicode_space == NULL) {
1588 Py_CLEAR(str_newline);
1589 Py_CLEAR(str_space);
1590 Py_CLEAR(unicode_space);
1591 return NULL;
1594 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1595 kwlist, &sep, &end, &file))
1596 return NULL;
1597 if (file == NULL || file == Py_None) {
1598 file = PySys_GetObject("stdout");
1599 /* sys.stdout may be None when FILE* stdout isn't connected */
1600 if (file == Py_None)
1601 Py_RETURN_NONE;
1603 if (sep == Py_None) {
1604 sep = NULL;
1606 else if (sep) {
1607 if (PyUnicode_Check(sep)) {
1608 use_unicode = 1;
1610 else if (!PyString_Check(sep)) {
1611 PyErr_Format(PyExc_TypeError,
1612 "sep must be None, str or unicode, not %.200s",
1613 sep->ob_type->tp_name);
1614 return NULL;
1617 if (end == Py_None)
1618 end = NULL;
1619 else if (end) {
1620 if (PyUnicode_Check(end)) {
1621 use_unicode = 1;
1623 else if (!PyString_Check(end)) {
1624 PyErr_Format(PyExc_TypeError,
1625 "end must be None, str or unicode, not %.200s",
1626 end->ob_type->tp_name);
1627 return NULL;
1631 if (!use_unicode) {
1632 for (i = 0; i < PyTuple_Size(args); i++) {
1633 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1634 use_unicode = 1;
1635 break;
1639 if (use_unicode) {
1640 newline = unicode_newline;
1641 space = unicode_space;
1643 else {
1644 newline = str_newline;
1645 space = str_space;
1648 for (i = 0; i < PyTuple_Size(args); i++) {
1649 if (i > 0) {
1650 if (sep == NULL)
1651 err = PyFile_WriteObject(space, file,
1652 Py_PRINT_RAW);
1653 else
1654 err = PyFile_WriteObject(sep, file,
1655 Py_PRINT_RAW);
1656 if (err)
1657 return NULL;
1659 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1660 Py_PRINT_RAW);
1661 if (err)
1662 return NULL;
1665 if (end == NULL)
1666 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1667 else
1668 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1669 if (err)
1670 return NULL;
1672 Py_RETURN_NONE;
1675 PyDoc_STRVAR(print_doc,
1676 "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1678 Prints the values to a stream, or to sys.stdout by default.\n\
1679 Optional keyword arguments:\n\
1680 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1681 sep: string inserted between values, default a space.\n\
1682 end: string appended after the last value, default a newline.");
1685 /* Return number of items in range (lo, hi, step), when arguments are
1686 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1687 * & only if the true value is too large to fit in a signed long.
1688 * Arguments MUST return 1 with either PyInt_Check() or
1689 * PyLong_Check(). Return -1 when there is an error.
1691 static long
1692 get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1694 /* -------------------------------------------------------------
1695 Algorithm is equal to that of get_len_of_range(), but it operates
1696 on PyObjects (which are assumed to be PyLong or PyInt objects).
1697 ---------------------------------------------------------------*/
1698 long n;
1699 PyObject *diff = NULL;
1700 PyObject *one = NULL;
1701 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1702 /* holds sub-expression evaluations */
1704 /* if (lo >= hi), return length of 0. */
1705 if (PyObject_Compare(lo, hi) >= 0)
1706 return 0;
1708 if ((one = PyLong_FromLong(1L)) == NULL)
1709 goto Fail;
1711 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1712 goto Fail;
1714 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1715 goto Fail;
1717 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1718 goto Fail;
1720 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1721 goto Fail;
1723 n = PyLong_AsLong(tmp3);
1724 if (PyErr_Occurred()) { /* Check for Overflow */
1725 PyErr_Clear();
1726 goto Fail;
1729 Py_DECREF(tmp3);
1730 Py_DECREF(tmp2);
1731 Py_DECREF(diff);
1732 Py_DECREF(tmp1);
1733 Py_DECREF(one);
1734 return n;
1736 Fail:
1737 Py_XDECREF(tmp3);
1738 Py_XDECREF(tmp2);
1739 Py_XDECREF(diff);
1740 Py_XDECREF(tmp1);
1741 Py_XDECREF(one);
1742 return -1;
1745 /* An extension of builtin_range() that handles the case when PyLong
1746 * arguments are given. */
1747 static PyObject *
1748 handle_range_longs(PyObject *self, PyObject *args)
1750 PyObject *ilow;
1751 PyObject *ihigh = NULL;
1752 PyObject *istep = NULL;
1754 PyObject *curnum = NULL;
1755 PyObject *v = NULL;
1756 long bign;
1757 int i, n;
1758 int cmp_result;
1760 PyObject *zero = PyLong_FromLong(0);
1762 if (zero == NULL)
1763 return NULL;
1765 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1766 Py_DECREF(zero);
1767 return NULL;
1770 /* Figure out which way we were called, supply defaults, and be
1771 * sure to incref everything so that the decrefs at the end
1772 * are correct.
1774 assert(ilow != NULL);
1775 if (ihigh == NULL) {
1776 /* only 1 arg -- it's the upper limit */
1777 ihigh = ilow;
1778 ilow = NULL;
1780 assert(ihigh != NULL);
1781 Py_INCREF(ihigh);
1783 /* ihigh correct now; do ilow */
1784 if (ilow == NULL)
1785 ilow = zero;
1786 Py_INCREF(ilow);
1788 /* ilow and ihigh correct now; do istep */
1789 if (istep == NULL) {
1790 istep = PyLong_FromLong(1L);
1791 if (istep == NULL)
1792 goto Fail;
1794 else {
1795 Py_INCREF(istep);
1798 if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
1799 PyErr_Format(PyExc_TypeError,
1800 "range() integer start argument expected, got %s.",
1801 ilow->ob_type->tp_name);
1802 goto Fail;
1805 if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
1806 PyErr_Format(PyExc_TypeError,
1807 "range() integer end argument expected, got %s.",
1808 ihigh->ob_type->tp_name);
1809 goto Fail;
1812 if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
1813 PyErr_Format(PyExc_TypeError,
1814 "range() integer step argument expected, got %s.",
1815 istep->ob_type->tp_name);
1816 goto Fail;
1819 if (PyObject_Cmp(istep, zero, &cmp_result) == -1)
1820 goto Fail;
1821 if (cmp_result == 0) {
1822 PyErr_SetString(PyExc_ValueError,
1823 "range() step argument must not be zero");
1824 goto Fail;
1827 if (cmp_result > 0)
1828 bign = get_len_of_range_longs(ilow, ihigh, istep);
1829 else {
1830 PyObject *neg_istep = PyNumber_Negative(istep);
1831 if (neg_istep == NULL)
1832 goto Fail;
1833 bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
1834 Py_DECREF(neg_istep);
1837 n = (int)bign;
1838 if (bign < 0 || (long)n != bign) {
1839 PyErr_SetString(PyExc_OverflowError,
1840 "range() result has too many items");
1841 goto Fail;
1844 v = PyList_New(n);
1845 if (v == NULL)
1846 goto Fail;
1848 curnum = ilow;
1849 Py_INCREF(curnum);
1851 for (i = 0; i < n; i++) {
1852 PyObject *w = PyNumber_Long(curnum);
1853 PyObject *tmp_num;
1854 if (w == NULL)
1855 goto Fail;
1857 PyList_SET_ITEM(v, i, w);
1859 tmp_num = PyNumber_Add(curnum, istep);
1860 if (tmp_num == NULL)
1861 goto Fail;
1863 Py_DECREF(curnum);
1864 curnum = tmp_num;
1866 Py_DECREF(ilow);
1867 Py_DECREF(ihigh);
1868 Py_DECREF(istep);
1869 Py_DECREF(zero);
1870 Py_DECREF(curnum);
1871 return v;
1873 Fail:
1874 Py_DECREF(ilow);
1875 Py_DECREF(ihigh);
1876 Py_XDECREF(istep);
1877 Py_DECREF(zero);
1878 Py_XDECREF(curnum);
1879 Py_XDECREF(v);
1880 return NULL;
1883 /* Return number of items in range/xrange (lo, hi, step). step > 0
1884 * required. Return a value < 0 if & only if the true value is too
1885 * large to fit in a signed long.
1887 static long
1888 get_len_of_range(long lo, long hi, long step)
1890 /* -------------------------------------------------------------
1891 If lo >= hi, the range is empty.
1892 Else if n values are in the range, the last one is
1893 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1894 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1895 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1896 the RHS is non-negative and so truncation is the same as the
1897 floor. Letting M be the largest positive long, the worst case
1898 for the RHS numerator is hi=M, lo=-M-1, and then
1899 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1900 precision to compute the RHS exactly.
1901 ---------------------------------------------------------------*/
1902 long n = 0;
1903 if (lo < hi) {
1904 unsigned long uhi = (unsigned long)hi;
1905 unsigned long ulo = (unsigned long)lo;
1906 unsigned long diff = uhi - ulo - 1;
1907 n = (long)(diff / (unsigned long)step + 1);
1909 return n;
1912 static PyObject *
1913 builtin_range(PyObject *self, PyObject *args)
1915 long ilow = 0, ihigh = 0, istep = 1;
1916 long bign;
1917 int i, n;
1919 PyObject *v;
1921 if (PyTuple_Size(args) <= 1) {
1922 if (!PyArg_ParseTuple(args,
1923 "l;range() requires 1-3 int arguments",
1924 &ihigh)) {
1925 PyErr_Clear();
1926 return handle_range_longs(self, args);
1929 else {
1930 if (!PyArg_ParseTuple(args,
1931 "ll|l;range() requires 1-3 int arguments",
1932 &ilow, &ihigh, &istep)) {
1933 PyErr_Clear();
1934 return handle_range_longs(self, args);
1937 if (istep == 0) {
1938 PyErr_SetString(PyExc_ValueError,
1939 "range() step argument must not be zero");
1940 return NULL;
1942 if (istep > 0)
1943 bign = get_len_of_range(ilow, ihigh, istep);
1944 else
1945 bign = get_len_of_range(ihigh, ilow, -istep);
1946 n = (int)bign;
1947 if (bign < 0 || (long)n != bign) {
1948 PyErr_SetString(PyExc_OverflowError,
1949 "range() result has too many items");
1950 return NULL;
1952 v = PyList_New(n);
1953 if (v == NULL)
1954 return NULL;
1955 for (i = 0; i < n; i++) {
1956 PyObject *w = PyInt_FromLong(ilow);
1957 if (w == NULL) {
1958 Py_DECREF(v);
1959 return NULL;
1961 PyList_SET_ITEM(v, i, w);
1962 ilow += istep;
1964 return v;
1967 PyDoc_STRVAR(range_doc,
1968 "range([start,] stop[, step]) -> list of integers\n\
1970 Return a list containing an arithmetic progression of integers.\n\
1971 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1972 When step is given, it specifies the increment (or decrement).\n\
1973 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1974 These are exactly the valid indices for a list of 4 elements.");
1977 static PyObject *
1978 builtin_raw_input(PyObject *self, PyObject *args)
1980 PyObject *v = NULL;
1981 PyObject *fin = PySys_GetObject("stdin");
1982 PyObject *fout = PySys_GetObject("stdout");
1984 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
1985 return NULL;
1987 if (fin == NULL) {
1988 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
1989 return NULL;
1991 if (fout == NULL) {
1992 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
1993 return NULL;
1995 if (PyFile_SoftSpace(fout, 0)) {
1996 if (PyFile_WriteString(" ", fout) != 0)
1997 return NULL;
1999 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2000 && isatty(fileno(PyFile_AsFile(fin)))
2001 && isatty(fileno(PyFile_AsFile(fout)))) {
2002 PyObject *po;
2003 char *prompt;
2004 char *s;
2005 PyObject *result;
2006 if (v != NULL) {
2007 po = PyObject_Str(v);
2008 if (po == NULL)
2009 return NULL;
2010 prompt = PyString_AsString(po);
2011 if (prompt == NULL)
2012 return NULL;
2014 else {
2015 po = NULL;
2016 prompt = "";
2018 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2019 prompt);
2020 Py_XDECREF(po);
2021 if (s == NULL) {
2022 if (!PyErr_Occurred())
2023 PyErr_SetNone(PyExc_KeyboardInterrupt);
2024 return NULL;
2026 if (*s == '\0') {
2027 PyErr_SetNone(PyExc_EOFError);
2028 result = NULL;
2030 else { /* strip trailing '\n' */
2031 size_t len = strlen(s);
2032 if (len > PY_SSIZE_T_MAX) {
2033 PyErr_SetString(PyExc_OverflowError,
2034 "[raw_]input: input too long");
2035 result = NULL;
2037 else {
2038 result = PyString_FromStringAndSize(s, len-1);
2041 PyMem_FREE(s);
2042 return result;
2044 if (v != NULL) {
2045 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2046 return NULL;
2048 return PyFile_GetLine(fin, -1);
2051 PyDoc_STRVAR(raw_input_doc,
2052 "raw_input([prompt]) -> string\n\
2054 Read a string from standard input. The trailing newline is stripped.\n\
2055 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2056 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
2057 is printed without a trailing newline before reading.");
2060 static PyObject *
2061 builtin_reduce(PyObject *self, PyObject *args)
2063 static PyObject *functools_reduce = NULL;
2065 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2066 "use functools.reduce()", 1) < 0)
2067 return NULL;
2069 if (functools_reduce == NULL) {
2070 PyObject *functools = PyImport_ImportModule("functools");
2071 if (functools == NULL)
2072 return NULL;
2073 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2074 Py_DECREF(functools);
2075 if (functools_reduce == NULL)
2076 return NULL;
2078 return PyObject_Call(functools_reduce, args, NULL);
2081 PyDoc_STRVAR(reduce_doc,
2082 "reduce(function, sequence[, initial]) -> value\n\
2084 Apply a function of two arguments cumulatively to the items of a sequence,\n\
2085 from left to right, so as to reduce the sequence to a single value.\n\
2086 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2087 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2088 of the sequence in the calculation, and serves as a default when the\n\
2089 sequence is empty.");
2092 static PyObject *
2093 builtin_reload(PyObject *self, PyObject *v)
2095 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2096 1) < 0)
2097 return NULL;
2099 return PyImport_ReloadModule(v);
2102 PyDoc_STRVAR(reload_doc,
2103 "reload(module) -> module\n\
2105 Reload the module. The module must have been successfully imported before.");
2108 static PyObject *
2109 builtin_repr(PyObject *self, PyObject *v)
2111 return PyObject_Repr(v);
2114 PyDoc_STRVAR(repr_doc,
2115 "repr(object) -> string\n\
2117 Return the canonical string representation of the object.\n\
2118 For most object types, eval(repr(object)) == object.");
2121 static PyObject *
2122 builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
2124 double x;
2125 PyObject *o_ndigits = NULL;
2126 Py_ssize_t ndigits;
2127 static char *kwlist[] = {"number", "ndigits", 0};
2129 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2130 kwlist, &x, &o_ndigits))
2131 return NULL;
2133 /* nans, infinities and zeros round to themselves */
2134 if (!Py_IS_FINITE(x) || x == 0.0)
2135 return PyFloat_FromDouble(x);
2137 if (o_ndigits == NULL) {
2138 /* second argument defaults to 0 */
2139 ndigits = 0;
2141 else {
2142 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2143 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2144 if (ndigits == -1 && PyErr_Occurred())
2145 return NULL;
2148 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2149 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2150 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
2151 #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2152 #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
2153 if (ndigits > NDIGITS_MAX)
2154 /* return x */
2155 return PyFloat_FromDouble(x);
2156 else if (ndigits < NDIGITS_MIN)
2157 /* return 0.0, but with sign of x */
2158 return PyFloat_FromDouble(0.0*x);
2159 else
2160 /* finite x, and ndigits is not unreasonably large */
2161 /* _Py_double_round is defined in floatobject.c */
2162 return _Py_double_round(x, (int)ndigits);
2163 #undef NDIGITS_MAX
2164 #undef NDIGITS_MIN
2167 PyDoc_STRVAR(round_doc,
2168 "round(number[, ndigits]) -> floating point number\n\
2170 Round a number to a given precision in decimal digits (default 0 digits).\n\
2171 This always returns a floating point number. Precision may be negative.");
2173 static PyObject *
2174 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2176 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2177 PyObject *callable;
2178 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2179 int reverse;
2181 /* args 1-4 should match listsort in Objects/listobject.c */
2182 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2183 kwlist, &seq, &compare, &keyfunc, &reverse))
2184 return NULL;
2186 newlist = PySequence_List(seq);
2187 if (newlist == NULL)
2188 return NULL;
2190 callable = PyObject_GetAttrString(newlist, "sort");
2191 if (callable == NULL) {
2192 Py_DECREF(newlist);
2193 return NULL;
2196 newargs = PyTuple_GetSlice(args, 1, 4);
2197 if (newargs == NULL) {
2198 Py_DECREF(newlist);
2199 Py_DECREF(callable);
2200 return NULL;
2203 v = PyObject_Call(callable, newargs, kwds);
2204 Py_DECREF(newargs);
2205 Py_DECREF(callable);
2206 if (v == NULL) {
2207 Py_DECREF(newlist);
2208 return NULL;
2210 Py_DECREF(v);
2211 return newlist;
2214 PyDoc_STRVAR(sorted_doc,
2215 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2217 static PyObject *
2218 builtin_vars(PyObject *self, PyObject *args)
2220 PyObject *v = NULL;
2221 PyObject *d;
2223 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2224 return NULL;
2225 if (v == NULL) {
2226 d = PyEval_GetLocals();
2227 if (d == NULL) {
2228 if (!PyErr_Occurred())
2229 PyErr_SetString(PyExc_SystemError,
2230 "vars(): no locals!?");
2232 else
2233 Py_INCREF(d);
2235 else {
2236 d = PyObject_GetAttrString(v, "__dict__");
2237 if (d == NULL) {
2238 PyErr_SetString(PyExc_TypeError,
2239 "vars() argument must have __dict__ attribute");
2240 return NULL;
2243 return d;
2246 PyDoc_STRVAR(vars_doc,
2247 "vars([object]) -> dictionary\n\
2249 Without arguments, equivalent to locals().\n\
2250 With an argument, equivalent to object.__dict__.");
2253 static PyObject*
2254 builtin_sum(PyObject *self, PyObject *args)
2256 PyObject *seq;
2257 PyObject *result = NULL;
2258 PyObject *temp, *item, *iter;
2260 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2261 return NULL;
2263 iter = PyObject_GetIter(seq);
2264 if (iter == NULL)
2265 return NULL;
2267 if (result == NULL) {
2268 result = PyInt_FromLong(0);
2269 if (result == NULL) {
2270 Py_DECREF(iter);
2271 return NULL;
2273 } else {
2274 /* reject string values for 'start' parameter */
2275 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2276 PyErr_SetString(PyExc_TypeError,
2277 "sum() can't sum strings [use ''.join(seq) instead]");
2278 Py_DECREF(iter);
2279 return NULL;
2281 Py_INCREF(result);
2284 #ifndef SLOW_SUM
2285 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2286 Assumes all inputs are the same type. If the assumption fails, default
2287 to the more general routine.
2289 if (PyInt_CheckExact(result)) {
2290 long i_result = PyInt_AS_LONG(result);
2291 Py_DECREF(result);
2292 result = NULL;
2293 while(result == NULL) {
2294 item = PyIter_Next(iter);
2295 if (item == NULL) {
2296 Py_DECREF(iter);
2297 if (PyErr_Occurred())
2298 return NULL;
2299 return PyInt_FromLong(i_result);
2301 if (PyInt_CheckExact(item)) {
2302 long b = PyInt_AS_LONG(item);
2303 long x = i_result + b;
2304 if ((x^i_result) >= 0 || (x^b) >= 0) {
2305 i_result = x;
2306 Py_DECREF(item);
2307 continue;
2310 /* Either overflowed or is not an int. Restore real objects and process normally */
2311 result = PyInt_FromLong(i_result);
2312 temp = PyNumber_Add(result, item);
2313 Py_DECREF(result);
2314 Py_DECREF(item);
2315 result = temp;
2316 if (result == NULL) {
2317 Py_DECREF(iter);
2318 return NULL;
2323 if (PyFloat_CheckExact(result)) {
2324 double f_result = PyFloat_AS_DOUBLE(result);
2325 Py_DECREF(result);
2326 result = NULL;
2327 while(result == NULL) {
2328 item = PyIter_Next(iter);
2329 if (item == NULL) {
2330 Py_DECREF(iter);
2331 if (PyErr_Occurred())
2332 return NULL;
2333 return PyFloat_FromDouble(f_result);
2335 if (PyFloat_CheckExact(item)) {
2336 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2337 f_result += PyFloat_AS_DOUBLE(item);
2338 PyFPE_END_PROTECT(f_result)
2339 Py_DECREF(item);
2340 continue;
2342 if (PyInt_CheckExact(item)) {
2343 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2344 f_result += (double)PyInt_AS_LONG(item);
2345 PyFPE_END_PROTECT(f_result)
2346 Py_DECREF(item);
2347 continue;
2349 result = PyFloat_FromDouble(f_result);
2350 temp = PyNumber_Add(result, item);
2351 Py_DECREF(result);
2352 Py_DECREF(item);
2353 result = temp;
2354 if (result == NULL) {
2355 Py_DECREF(iter);
2356 return NULL;
2360 #endif
2362 for(;;) {
2363 item = PyIter_Next(iter);
2364 if (item == NULL) {
2365 /* error, or end-of-sequence */
2366 if (PyErr_Occurred()) {
2367 Py_DECREF(result);
2368 result = NULL;
2370 break;
2372 /* It's tempting to use PyNumber_InPlaceAdd instead of
2373 PyNumber_Add here, to avoid quadratic running time
2374 when doing 'sum(list_of_lists, [])'. However, this
2375 would produce a change in behaviour: a snippet like
2377 empty = []
2378 sum([[x] for x in range(10)], empty)
2380 would change the value of empty. */
2381 temp = PyNumber_Add(result, item);
2382 Py_DECREF(result);
2383 Py_DECREF(item);
2384 result = temp;
2385 if (result == NULL)
2386 break;
2388 Py_DECREF(iter);
2389 return result;
2392 PyDoc_STRVAR(sum_doc,
2393 "sum(sequence[, start]) -> value\n\
2395 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2396 of parameter 'start' (which defaults to 0). When the sequence is\n\
2397 empty, returns start.");
2400 static PyObject *
2401 builtin_isinstance(PyObject *self, PyObject *args)
2403 PyObject *inst;
2404 PyObject *cls;
2405 int retval;
2407 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2408 return NULL;
2410 retval = PyObject_IsInstance(inst, cls);
2411 if (retval < 0)
2412 return NULL;
2413 return PyBool_FromLong(retval);
2416 PyDoc_STRVAR(isinstance_doc,
2417 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2419 Return whether an object is an instance of a class or of a subclass thereof.\n\
2420 With a type as second argument, return whether that is the object's type.\n\
2421 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2422 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2425 static PyObject *
2426 builtin_issubclass(PyObject *self, PyObject *args)
2428 PyObject *derived;
2429 PyObject *cls;
2430 int retval;
2432 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2433 return NULL;
2435 retval = PyObject_IsSubclass(derived, cls);
2436 if (retval < 0)
2437 return NULL;
2438 return PyBool_FromLong(retval);
2441 PyDoc_STRVAR(issubclass_doc,
2442 "issubclass(C, B) -> bool\n\
2444 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2445 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2446 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2449 static PyObject*
2450 builtin_zip(PyObject *self, PyObject *args)
2452 PyObject *ret;
2453 const Py_ssize_t itemsize = PySequence_Length(args);
2454 Py_ssize_t i;
2455 PyObject *itlist; /* tuple of iterators */
2456 Py_ssize_t len; /* guess at result length */
2458 if (itemsize == 0)
2459 return PyList_New(0);
2461 /* args must be a tuple */
2462 assert(PyTuple_Check(args));
2464 /* Guess at result length: the shortest of the input lengths.
2465 If some argument refuses to say, we refuse to guess too, lest
2466 an argument like xrange(sys.maxint) lead us astray.*/
2467 len = -1; /* unknown */
2468 for (i = 0; i < itemsize; ++i) {
2469 PyObject *item = PyTuple_GET_ITEM(args, i);
2470 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2471 if (thislen < 0) {
2472 if (thislen == -1)
2473 return NULL;
2474 len = -1;
2475 break;
2477 else if (len < 0 || thislen < len)
2478 len = thislen;
2481 /* allocate result list */
2482 if (len < 0)
2483 len = 10; /* arbitrary */
2484 if ((ret = PyList_New(len)) == NULL)
2485 return NULL;
2487 /* obtain iterators */
2488 itlist = PyTuple_New(itemsize);
2489 if (itlist == NULL)
2490 goto Fail_ret;
2491 for (i = 0; i < itemsize; ++i) {
2492 PyObject *item = PyTuple_GET_ITEM(args, i);
2493 PyObject *it = PyObject_GetIter(item);
2494 if (it == NULL) {
2495 if (PyErr_ExceptionMatches(PyExc_TypeError))
2496 PyErr_Format(PyExc_TypeError,
2497 "zip argument #%zd must support iteration",
2498 i+1);
2499 goto Fail_ret_itlist;
2501 PyTuple_SET_ITEM(itlist, i, it);
2504 /* build result into ret list */
2505 for (i = 0; ; ++i) {
2506 int j;
2507 PyObject *next = PyTuple_New(itemsize);
2508 if (!next)
2509 goto Fail_ret_itlist;
2511 for (j = 0; j < itemsize; j++) {
2512 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2513 PyObject *item = PyIter_Next(it);
2514 if (!item) {
2515 if (PyErr_Occurred()) {
2516 Py_DECREF(ret);
2517 ret = NULL;
2519 Py_DECREF(next);
2520 Py_DECREF(itlist);
2521 goto Done;
2523 PyTuple_SET_ITEM(next, j, item);
2526 if (i < len)
2527 PyList_SET_ITEM(ret, i, next);
2528 else {
2529 int status = PyList_Append(ret, next);
2530 Py_DECREF(next);
2531 ++len;
2532 if (status < 0)
2533 goto Fail_ret_itlist;
2537 Done:
2538 if (ret != NULL && i < len) {
2539 /* The list is too big. */
2540 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2541 return NULL;
2543 return ret;
2545 Fail_ret_itlist:
2546 Py_DECREF(itlist);
2547 Fail_ret:
2548 Py_DECREF(ret);
2549 return NULL;
2553 PyDoc_STRVAR(zip_doc,
2554 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2556 Return a list of tuples, where each tuple contains the i-th element\n\
2557 from each of the argument sequences. The returned list is truncated\n\
2558 in length to the length of the shortest argument sequence.");
2561 static PyMethodDef builtin_methods[] = {
2562 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2563 {"abs", builtin_abs, METH_O, abs_doc},
2564 {"all", builtin_all, METH_O, all_doc},
2565 {"any", builtin_any, METH_O, any_doc},
2566 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2567 {"bin", builtin_bin, METH_O, bin_doc},
2568 {"callable", builtin_callable, METH_O, callable_doc},
2569 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2570 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2571 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2572 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2573 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2574 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2575 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2576 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2577 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2578 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2579 {"format", builtin_format, METH_VARARGS, format_doc},
2580 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2581 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2582 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2583 {"hash", builtin_hash, METH_O, hash_doc},
2584 {"hex", builtin_hex, METH_O, hex_doc},
2585 {"id", builtin_id, METH_O, id_doc},
2586 {"input", builtin_input, METH_VARARGS, input_doc},
2587 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2588 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2589 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2590 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2591 {"len", builtin_len, METH_O, len_doc},
2592 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2593 {"map", builtin_map, METH_VARARGS, map_doc},
2594 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2595 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2596 {"next", builtin_next, METH_VARARGS, next_doc},
2597 {"oct", builtin_oct, METH_O, oct_doc},
2598 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2599 {"ord", builtin_ord, METH_O, ord_doc},
2600 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2601 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2602 {"range", builtin_range, METH_VARARGS, range_doc},
2603 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2604 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2605 {"reload", builtin_reload, METH_O, reload_doc},
2606 {"repr", builtin_repr, METH_O, repr_doc},
2607 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2608 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2609 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2610 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2611 #ifdef Py_USING_UNICODE
2612 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
2613 #endif
2614 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2615 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2616 {NULL, NULL},
2619 PyDoc_STRVAR(builtin_doc,
2620 "Built-in functions, exceptions, and other objects.\n\
2622 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2624 PyObject *
2625 _PyBuiltin_Init(void)
2627 PyObject *mod, *dict, *debug;
2628 mod = Py_InitModule4("__builtin__", builtin_methods,
2629 builtin_doc, (PyObject *)NULL,
2630 PYTHON_API_VERSION);
2631 if (mod == NULL)
2632 return NULL;
2633 dict = PyModule_GetDict(mod);
2635 #ifdef Py_TRACE_REFS
2636 /* __builtin__ exposes a number of statically allocated objects
2637 * that, before this code was added in 2.3, never showed up in
2638 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2639 * result, programs leaking references to None and False (etc)
2640 * couldn't be diagnosed by examining sys.getobjects(0).
2642 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2643 #else
2644 #define ADD_TO_ALL(OBJECT) (void)0
2645 #endif
2647 #define SETBUILTIN(NAME, OBJECT) \
2648 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2649 return NULL; \
2650 ADD_TO_ALL(OBJECT)
2652 SETBUILTIN("None", Py_None);
2653 SETBUILTIN("Ellipsis", Py_Ellipsis);
2654 SETBUILTIN("NotImplemented", Py_NotImplemented);
2655 SETBUILTIN("False", Py_False);
2656 SETBUILTIN("True", Py_True);
2657 SETBUILTIN("basestring", &PyBaseString_Type);
2658 SETBUILTIN("bool", &PyBool_Type);
2659 SETBUILTIN("memoryview", &PyMemoryView_Type);
2660 SETBUILTIN("bytearray", &PyByteArray_Type);
2661 SETBUILTIN("bytes", &PyString_Type);
2662 SETBUILTIN("buffer", &PyBuffer_Type);
2663 SETBUILTIN("classmethod", &PyClassMethod_Type);
2664 #ifndef WITHOUT_COMPLEX
2665 SETBUILTIN("complex", &PyComplex_Type);
2666 #endif
2667 SETBUILTIN("dict", &PyDict_Type);
2668 SETBUILTIN("enumerate", &PyEnum_Type);
2669 SETBUILTIN("file", &PyFile_Type);
2670 SETBUILTIN("float", &PyFloat_Type);
2671 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2672 SETBUILTIN("property", &PyProperty_Type);
2673 SETBUILTIN("int", &PyInt_Type);
2674 SETBUILTIN("list", &PyList_Type);
2675 SETBUILTIN("long", &PyLong_Type);
2676 SETBUILTIN("object", &PyBaseObject_Type);
2677 SETBUILTIN("reversed", &PyReversed_Type);
2678 SETBUILTIN("set", &PySet_Type);
2679 SETBUILTIN("slice", &PySlice_Type);
2680 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2681 SETBUILTIN("str", &PyString_Type);
2682 SETBUILTIN("super", &PySuper_Type);
2683 SETBUILTIN("tuple", &PyTuple_Type);
2684 SETBUILTIN("type", &PyType_Type);
2685 SETBUILTIN("xrange", &PyRange_Type);
2686 #ifdef Py_USING_UNICODE
2687 SETBUILTIN("unicode", &PyUnicode_Type);
2688 #endif
2689 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2690 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2691 Py_XDECREF(debug);
2692 return NULL;
2694 Py_XDECREF(debug);
2696 return mod;
2697 #undef ADD_TO_ALL
2698 #undef SETBUILTIN
2701 /* Helper for filter(): filter a tuple through a function */
2703 static PyObject *
2704 filtertuple(PyObject *func, PyObject *tuple)
2706 PyObject *result;
2707 Py_ssize_t i, j;
2708 Py_ssize_t len = PyTuple_Size(tuple);
2710 if (len == 0) {
2711 if (PyTuple_CheckExact(tuple))
2712 Py_INCREF(tuple);
2713 else
2714 tuple = PyTuple_New(0);
2715 return tuple;
2718 if ((result = PyTuple_New(len)) == NULL)
2719 return NULL;
2721 for (i = j = 0; i < len; ++i) {
2722 PyObject *item, *good;
2723 int ok;
2725 if (tuple->ob_type->tp_as_sequence &&
2726 tuple->ob_type->tp_as_sequence->sq_item) {
2727 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2728 if (item == NULL)
2729 goto Fail_1;
2730 } else {
2731 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2732 goto Fail_1;
2734 if (func == Py_None) {
2735 Py_INCREF(item);
2736 good = item;
2738 else {
2739 PyObject *arg = PyTuple_Pack(1, item);
2740 if (arg == NULL) {
2741 Py_DECREF(item);
2742 goto Fail_1;
2744 good = PyEval_CallObject(func, arg);
2745 Py_DECREF(arg);
2746 if (good == NULL) {
2747 Py_DECREF(item);
2748 goto Fail_1;
2751 ok = PyObject_IsTrue(good);
2752 Py_DECREF(good);
2753 if (ok) {
2754 if (PyTuple_SetItem(result, j++, item) < 0)
2755 goto Fail_1;
2757 else
2758 Py_DECREF(item);
2761 if (_PyTuple_Resize(&result, j) < 0)
2762 return NULL;
2764 return result;
2766 Fail_1:
2767 Py_DECREF(result);
2768 return NULL;
2772 /* Helper for filter(): filter a string through a function */
2774 static PyObject *
2775 filterstring(PyObject *func, PyObject *strobj)
2777 PyObject *result;
2778 Py_ssize_t i, j;
2779 Py_ssize_t len = PyString_Size(strobj);
2780 Py_ssize_t outlen = len;
2782 if (func == Py_None) {
2783 /* If it's a real string we can return the original,
2784 * as no character is ever false and __getitem__
2785 * does return this character. If it's a subclass
2786 * we must go through the __getitem__ loop */
2787 if (PyString_CheckExact(strobj)) {
2788 Py_INCREF(strobj);
2789 return strobj;
2792 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2793 return NULL;
2795 for (i = j = 0; i < len; ++i) {
2796 PyObject *item;
2797 int ok;
2799 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2800 if (item == NULL)
2801 goto Fail_1;
2802 if (func==Py_None) {
2803 ok = 1;
2804 } else {
2805 PyObject *arg, *good;
2806 arg = PyTuple_Pack(1, item);
2807 if (arg == NULL) {
2808 Py_DECREF(item);
2809 goto Fail_1;
2811 good = PyEval_CallObject(func, arg);
2812 Py_DECREF(arg);
2813 if (good == NULL) {
2814 Py_DECREF(item);
2815 goto Fail_1;
2817 ok = PyObject_IsTrue(good);
2818 Py_DECREF(good);
2820 if (ok) {
2821 Py_ssize_t reslen;
2822 if (!PyString_Check(item)) {
2823 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2824 " __getitem__ returned different type");
2825 Py_DECREF(item);
2826 goto Fail_1;
2828 reslen = PyString_GET_SIZE(item);
2829 if (reslen == 1) {
2830 PyString_AS_STRING(result)[j++] =
2831 PyString_AS_STRING(item)[0];
2832 } else {
2833 /* do we need more space? */
2834 Py_ssize_t need = j;
2836 /* calculate space requirements while checking for overflow */
2837 if (need > PY_SSIZE_T_MAX - reslen) {
2838 Py_DECREF(item);
2839 goto Fail_1;
2842 need += reslen;
2844 if (need > PY_SSIZE_T_MAX - len) {
2845 Py_DECREF(item);
2846 goto Fail_1;
2849 need += len;
2851 if (need <= i) {
2852 Py_DECREF(item);
2853 goto Fail_1;
2856 need = need - i - 1;
2858 assert(need >= 0);
2859 assert(outlen >= 0);
2861 if (need > outlen) {
2862 /* overallocate, to avoid reallocations */
2863 if (outlen > PY_SSIZE_T_MAX / 2) {
2864 Py_DECREF(item);
2865 return NULL;
2868 if (need<2*outlen) {
2869 need = 2*outlen;
2871 if (_PyString_Resize(&result, need)) {
2872 Py_DECREF(item);
2873 return NULL;
2875 outlen = need;
2877 memcpy(
2878 PyString_AS_STRING(result) + j,
2879 PyString_AS_STRING(item),
2880 reslen
2882 j += reslen;
2885 Py_DECREF(item);
2888 if (j < outlen)
2889 _PyString_Resize(&result, j);
2891 return result;
2893 Fail_1:
2894 Py_DECREF(result);
2895 return NULL;
2898 #ifdef Py_USING_UNICODE
2899 /* Helper for filter(): filter a Unicode object through a function */
2901 static PyObject *
2902 filterunicode(PyObject *func, PyObject *strobj)
2904 PyObject *result;
2905 register Py_ssize_t i, j;
2906 Py_ssize_t len = PyUnicode_GetSize(strobj);
2907 Py_ssize_t outlen = len;
2909 if (func == Py_None) {
2910 /* If it's a real string we can return the original,
2911 * as no character is ever false and __getitem__
2912 * does return this character. If it's a subclass
2913 * we must go through the __getitem__ loop */
2914 if (PyUnicode_CheckExact(strobj)) {
2915 Py_INCREF(strobj);
2916 return strobj;
2919 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2920 return NULL;
2922 for (i = j = 0; i < len; ++i) {
2923 PyObject *item, *arg, *good;
2924 int ok;
2926 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2927 if (item == NULL)
2928 goto Fail_1;
2929 if (func == Py_None) {
2930 ok = 1;
2931 } else {
2932 arg = PyTuple_Pack(1, item);
2933 if (arg == NULL) {
2934 Py_DECREF(item);
2935 goto Fail_1;
2937 good = PyEval_CallObject(func, arg);
2938 Py_DECREF(arg);
2939 if (good == NULL) {
2940 Py_DECREF(item);
2941 goto Fail_1;
2943 ok = PyObject_IsTrue(good);
2944 Py_DECREF(good);
2946 if (ok) {
2947 Py_ssize_t reslen;
2948 if (!PyUnicode_Check(item)) {
2949 PyErr_SetString(PyExc_TypeError,
2950 "can't filter unicode to unicode:"
2951 " __getitem__ returned different type");
2952 Py_DECREF(item);
2953 goto Fail_1;
2955 reslen = PyUnicode_GET_SIZE(item);
2956 if (reslen == 1)
2957 PyUnicode_AS_UNICODE(result)[j++] =
2958 PyUnicode_AS_UNICODE(item)[0];
2959 else {
2960 /* do we need more space? */
2961 Py_ssize_t need = j + reslen + len - i - 1;
2963 /* check that didnt overflow */
2964 if ((j > PY_SSIZE_T_MAX - reslen) ||
2965 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
2966 ((j + reslen + len) < i) ||
2967 ((j + reslen + len - i) <= 0)) {
2968 Py_DECREF(item);
2969 return NULL;
2972 assert(need >= 0);
2973 assert(outlen >= 0);
2975 if (need > outlen) {
2976 /* overallocate,
2977 to avoid reallocations */
2978 if (need < 2 * outlen) {
2979 if (outlen > PY_SSIZE_T_MAX / 2) {
2980 Py_DECREF(item);
2981 return NULL;
2982 } else {
2983 need = 2 * outlen;
2987 if (PyUnicode_Resize(
2988 &result, need) < 0) {
2989 Py_DECREF(item);
2990 goto Fail_1;
2992 outlen = need;
2994 memcpy(PyUnicode_AS_UNICODE(result) + j,
2995 PyUnicode_AS_UNICODE(item),
2996 reslen*sizeof(Py_UNICODE));
2997 j += reslen;
3000 Py_DECREF(item);
3003 if (j < outlen)
3004 PyUnicode_Resize(&result, j);
3006 return result;
3008 Fail_1:
3009 Py_DECREF(result);
3010 return NULL;
3012 #endif