more cleanup ups of the recently added warnings in the subprocess docs.
[python.git] / Python / bltinmodule.c
blob4a1ffd50f918ea05d08605f905067a099626136b
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>
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, PyObject *kwds)
37 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
38 "level", 0};
39 char *name;
40 PyObject *globals = NULL;
41 PyObject *locals = NULL;
42 PyObject *fromlist = NULL;
43 int level = -1;
45 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
46 kwlist, &name, &globals, &locals, &fromlist, &level))
47 return NULL;
48 return PyImport_ImportModuleLevel(name, globals, locals,
49 fromlist, level);
52 PyDoc_STRVAR(import_doc,
53 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
54 \n\
55 Import a module. The globals are only used to determine the context;\n\
56 they are not modified. The locals are currently unused. The fromlist\n\
57 should be a list of names to emulate ``from name import ...'', or an\n\
58 empty list to emulate ``import name''.\n\
59 When importing a module from a package, note that __import__('A.B', ...)\n\
60 returns package A when fromlist is empty, but its submodule B when\n\
61 fromlist is not empty. Level is used to determine whether to perform \n\
62 absolute or relative imports. -1 is the original strategy of attempting\n\
63 both absolute and relative imports, 0 is absolute, a positive number\n\
64 is the number of parent directories to search relative to the current module.");
67 static PyObject *
68 builtin_abs(PyObject *self, PyObject *v)
70 return PyNumber_Absolute(v);
73 PyDoc_STRVAR(abs_doc,
74 "abs(number) -> number\n\
75 \n\
76 Return the absolute value of the argument.");
78 static PyObject *
79 builtin_all(PyObject *self, PyObject *v)
81 PyObject *it, *item;
82 PyObject *(*iternext)(PyObject *);
83 int cmp;
85 it = PyObject_GetIter(v);
86 if (it == NULL)
87 return NULL;
88 iternext = *Py_TYPE(it)->tp_iternext;
90 for (;;) {
91 item = iternext(it);
92 if (item == NULL)
93 break;
94 cmp = PyObject_IsTrue(item);
95 Py_DECREF(item);
96 if (cmp < 0) {
97 Py_DECREF(it);
98 return NULL;
100 if (cmp == 0) {
101 Py_DECREF(it);
102 Py_RETURN_FALSE;
105 Py_DECREF(it);
106 if (PyErr_Occurred()) {
107 if (PyErr_ExceptionMatches(PyExc_StopIteration))
108 PyErr_Clear();
109 else
110 return NULL;
112 Py_RETURN_TRUE;
115 PyDoc_STRVAR(all_doc,
116 "all(iterable) -> bool\n\
118 Return True if bool(x) is True for all values x in the iterable.");
120 static PyObject *
121 builtin_any(PyObject *self, PyObject *v)
123 PyObject *it, *item;
124 PyObject *(*iternext)(PyObject *);
125 int cmp;
127 it = PyObject_GetIter(v);
128 if (it == NULL)
129 return NULL;
130 iternext = *Py_TYPE(it)->tp_iternext;
132 for (;;) {
133 item = iternext(it);
134 if (item == NULL)
135 break;
136 cmp = PyObject_IsTrue(item);
137 Py_DECREF(item);
138 if (cmp < 0) {
139 Py_DECREF(it);
140 return NULL;
142 if (cmp == 1) {
143 Py_DECREF(it);
144 Py_RETURN_TRUE;
147 Py_DECREF(it);
148 if (PyErr_Occurred()) {
149 if (PyErr_ExceptionMatches(PyExc_StopIteration))
150 PyErr_Clear();
151 else
152 return NULL;
154 Py_RETURN_FALSE;
157 PyDoc_STRVAR(any_doc,
158 "any(iterable) -> bool\n\
160 Return True if bool(x) is True for any x in the iterable.");
162 static PyObject *
163 builtin_apply(PyObject *self, PyObject *args)
165 PyObject *func, *alist = NULL, *kwdict = NULL;
166 PyObject *t = NULL, *retval = NULL;
168 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
169 "use func(*args, **kwargs)", 1) < 0)
170 return NULL;
172 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
173 return NULL;
174 if (alist != NULL) {
175 if (!PyTuple_Check(alist)) {
176 if (!PySequence_Check(alist)) {
177 PyErr_Format(PyExc_TypeError,
178 "apply() arg 2 expected sequence, found %s",
179 alist->ob_type->tp_name);
180 return NULL;
182 t = PySequence_Tuple(alist);
183 if (t == NULL)
184 return NULL;
185 alist = t;
188 if (kwdict != NULL && !PyDict_Check(kwdict)) {
189 PyErr_Format(PyExc_TypeError,
190 "apply() arg 3 expected dictionary, found %s",
191 kwdict->ob_type->tp_name);
192 goto finally;
194 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
195 finally:
196 Py_XDECREF(t);
197 return retval;
200 PyDoc_STRVAR(apply_doc,
201 "apply(object[, args[, kwargs]]) -> value\n\
203 Call a callable object with positional arguments taken from the tuple args,\n\
204 and keyword arguments taken from the optional dictionary kwargs.\n\
205 Note that classes are callable, as are instances with a __call__() method.\n\
207 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
208 function(*args, **keywords).");
211 static PyObject *
212 builtin_bin(PyObject *self, PyObject *v)
214 return PyNumber_ToBase(v, 2);
217 PyDoc_STRVAR(bin_doc,
218 "bin(number) -> string\n\
220 Return the binary representation of an integer or long integer.");
223 static PyObject *
224 builtin_callable(PyObject *self, PyObject *v)
226 if (PyErr_WarnPy3k("callable() not supported in 3.x; "
227 "use hasattr(o, '__call__')", 1) < 0)
228 return NULL;
229 return PyBool_FromLong((long)PyCallable_Check(v));
232 PyDoc_STRVAR(callable_doc,
233 "callable(object) -> bool\n\
235 Return whether the object is callable (i.e., some kind of function).\n\
236 Note that classes are callable, as are instances with a __call__() method.");
239 static PyObject *
240 builtin_filter(PyObject *self, PyObject *args)
242 PyObject *func, *seq, *result, *it, *arg;
243 Py_ssize_t len; /* guess for result list size */
244 register Py_ssize_t j;
246 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
247 return NULL;
249 /* Strings and tuples return a result of the same type. */
250 if (PyString_Check(seq))
251 return filterstring(func, seq);
252 #ifdef Py_USING_UNICODE
253 if (PyUnicode_Check(seq))
254 return filterunicode(func, seq);
255 #endif
256 if (PyTuple_Check(seq))
257 return filtertuple(func, seq);
259 /* Pre-allocate argument list tuple. */
260 arg = PyTuple_New(1);
261 if (arg == NULL)
262 return NULL;
264 /* Get iterator. */
265 it = PyObject_GetIter(seq);
266 if (it == NULL)
267 goto Fail_arg;
269 /* Guess a result list size. */
270 len = _PyObject_LengthHint(seq, 8);
272 /* Get a result list. */
273 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
274 /* Eww - can modify the list in-place. */
275 Py_INCREF(seq);
276 result = seq;
278 else {
279 result = PyList_New(len);
280 if (result == NULL)
281 goto Fail_it;
284 /* Build the result list. */
285 j = 0;
286 for (;;) {
287 PyObject *item;
288 int ok;
290 item = PyIter_Next(it);
291 if (item == NULL) {
292 if (PyErr_Occurred())
293 goto Fail_result_it;
294 break;
297 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
298 ok = PyObject_IsTrue(item);
300 else {
301 PyObject *good;
302 PyTuple_SET_ITEM(arg, 0, item);
303 good = PyObject_Call(func, arg, NULL);
304 PyTuple_SET_ITEM(arg, 0, NULL);
305 if (good == NULL) {
306 Py_DECREF(item);
307 goto Fail_result_it;
309 ok = PyObject_IsTrue(good);
310 Py_DECREF(good);
312 if (ok) {
313 if (j < len)
314 PyList_SET_ITEM(result, j, item);
315 else {
316 int status = PyList_Append(result, item);
317 Py_DECREF(item);
318 if (status < 0)
319 goto Fail_result_it;
321 ++j;
323 else
324 Py_DECREF(item);
328 /* Cut back result list if len is too big. */
329 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
330 goto Fail_result_it;
332 Py_DECREF(it);
333 Py_DECREF(arg);
334 return result;
336 Fail_result_it:
337 Py_DECREF(result);
338 Fail_it:
339 Py_DECREF(it);
340 Fail_arg:
341 Py_DECREF(arg);
342 return NULL;
345 PyDoc_STRVAR(filter_doc,
346 "filter(function or None, sequence) -> list, tuple, or string\n"
347 "\n"
348 "Return those items of sequence for which function(item) is true. If\n"
349 "function is None, return the items that are true. If sequence is a tuple\n"
350 "or string, return the same type, else return a list.");
352 static PyObject *
353 builtin_format(PyObject *self, PyObject *args)
355 PyObject *value;
356 PyObject *format_spec = NULL;
358 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
359 return NULL;
361 return PyObject_Format(value, format_spec);
364 PyDoc_STRVAR(format_doc,
365 "format(value[, format_spec]) -> string\n\
367 Returns value.__format__(format_spec)\n\
368 format_spec defaults to \"\"");
370 static PyObject *
371 builtin_chr(PyObject *self, PyObject *args)
373 long x;
374 char s[1];
376 if (!PyArg_ParseTuple(args, "l:chr", &x))
377 return NULL;
378 if (x < 0 || x >= 256) {
379 PyErr_SetString(PyExc_ValueError,
380 "chr() arg not in range(256)");
381 return NULL;
383 s[0] = (char)x;
384 return PyString_FromStringAndSize(s, 1);
387 PyDoc_STRVAR(chr_doc,
388 "chr(i) -> character\n\
390 Return a string of one character with ordinal i; 0 <= i < 256.");
393 #ifdef Py_USING_UNICODE
394 static PyObject *
395 builtin_unichr(PyObject *self, PyObject *args)
397 int x;
399 if (!PyArg_ParseTuple(args, "i:unichr", &x))
400 return NULL;
402 return PyUnicode_FromOrdinal(x);
405 PyDoc_STRVAR(unichr_doc,
406 "unichr(i) -> Unicode character\n\
408 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
409 #endif
412 static PyObject *
413 builtin_cmp(PyObject *self, PyObject *args)
415 PyObject *a, *b;
416 int c;
418 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
419 return NULL;
420 if (PyObject_Cmp(a, b, &c) < 0)
421 return NULL;
422 return PyInt_FromLong((long)c);
425 PyDoc_STRVAR(cmp_doc,
426 "cmp(x, y) -> integer\n\
428 Return negative if x<y, zero if x==y, positive if x>y.");
431 static PyObject *
432 builtin_coerce(PyObject *self, PyObject *args)
434 PyObject *v, *w;
435 PyObject *res;
437 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
438 return NULL;
440 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
441 return NULL;
442 if (PyNumber_Coerce(&v, &w) < 0)
443 return NULL;
444 res = PyTuple_Pack(2, v, w);
445 Py_DECREF(v);
446 Py_DECREF(w);
447 return res;
450 PyDoc_STRVAR(coerce_doc,
451 "coerce(x, y) -> (x1, y1)\n\
453 Return a tuple consisting of the two numeric arguments converted to\n\
454 a common type, using the same rules as used by arithmetic operations.\n\
455 If coercion is not possible, raise TypeError.");
457 static PyObject *
458 builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
460 char *str;
461 char *filename;
462 char *startstr;
463 int mode = -1;
464 int dont_inherit = 0;
465 int supplied_flags = 0;
466 PyCompilerFlags cf;
467 PyObject *result = NULL, *cmd, *tmp = NULL;
468 Py_ssize_t length;
469 static char *kwlist[] = {"source", "filename", "mode", "flags",
470 "dont_inherit", NULL};
471 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
473 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
474 kwlist, &cmd, &filename, &startstr,
475 &supplied_flags, &dont_inherit))
476 return NULL;
478 cf.cf_flags = supplied_flags;
480 if (supplied_flags &
481 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
483 PyErr_SetString(PyExc_ValueError,
484 "compile(): unrecognised flags");
485 return NULL;
487 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
489 if (!dont_inherit) {
490 PyEval_MergeCompilerFlags(&cf);
493 if (strcmp(startstr, "exec") == 0)
494 mode = 0;
495 else if (strcmp(startstr, "eval") == 0)
496 mode = 1;
497 else if (strcmp(startstr, "single") == 0)
498 mode = 2;
499 else {
500 PyErr_SetString(PyExc_ValueError,
501 "compile() arg 3 must be 'exec', 'eval' or 'single'");
502 return NULL;
505 if (PyAST_Check(cmd)) {
506 if (supplied_flags & PyCF_ONLY_AST) {
507 Py_INCREF(cmd);
508 result = cmd;
510 else {
511 PyArena *arena;
512 mod_ty mod;
514 arena = PyArena_New();
515 mod = PyAST_obj2mod(cmd, arena, mode);
516 if (mod == NULL) {
517 PyArena_Free(arena);
518 return NULL;
520 result = (PyObject*)PyAST_Compile(mod, filename,
521 &cf, arena);
522 PyArena_Free(arena);
524 return result;
527 #ifdef Py_USING_UNICODE
528 if (PyUnicode_Check(cmd)) {
529 tmp = PyUnicode_AsUTF8String(cmd);
530 if (tmp == NULL)
531 return NULL;
532 cmd = tmp;
533 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
535 #endif
537 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
538 goto cleanup;
539 if ((size_t)length != strlen(str)) {
540 PyErr_SetString(PyExc_TypeError,
541 "compile() expected string without null bytes");
542 goto cleanup;
544 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
545 cleanup:
546 Py_XDECREF(tmp);
547 return result;
550 PyDoc_STRVAR(compile_doc,
551 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
553 Compile the source string (a Python module, statement or expression)\n\
554 into a code object that can be executed by the exec statement or eval().\n\
555 The filename will be used for run-time error messages.\n\
556 The mode must be 'exec' to compile a module, 'single' to compile a\n\
557 single (interactive) statement, or 'eval' to compile an expression.\n\
558 The flags argument, if present, controls which future statements influence\n\
559 the compilation of the code.\n\
560 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
561 the effects of any future statements in effect in the code calling\n\
562 compile; if absent or zero these statements do influence the compilation,\n\
563 in addition to any features explicitly specified.");
565 static PyObject *
566 builtin_dir(PyObject *self, PyObject *args)
568 PyObject *arg = NULL;
570 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
571 return NULL;
572 return PyObject_Dir(arg);
575 PyDoc_STRVAR(dir_doc,
576 "dir([object]) -> list of strings\n"
577 "\n"
578 "If called without an argument, return the names in the current scope.\n"
579 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
580 "of the given object, and of attributes reachable from it.\n"
581 "If the object supplies a method named __dir__, it will be used; otherwise\n"
582 "the default dir() logic is used and returns:\n"
583 " for a module object: the module's attributes.\n"
584 " for a class object: its attributes, and recursively the attributes\n"
585 " of its bases.\n"
586 " for any other object: its attributes, its class's attributes, and\n"
587 " recursively the attributes of its class's base classes.");
589 static PyObject *
590 builtin_divmod(PyObject *self, PyObject *args)
592 PyObject *v, *w;
594 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
595 return NULL;
596 return PyNumber_Divmod(v, w);
599 PyDoc_STRVAR(divmod_doc,
600 "divmod(x, y) -> (div, mod)\n\
602 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
605 static PyObject *
606 builtin_eval(PyObject *self, PyObject *args)
608 PyObject *cmd, *result, *tmp = NULL;
609 PyObject *globals = Py_None, *locals = Py_None;
610 char *str;
611 PyCompilerFlags cf;
613 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
614 return NULL;
615 if (locals != Py_None && !PyMapping_Check(locals)) {
616 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
617 return NULL;
619 if (globals != Py_None && !PyDict_Check(globals)) {
620 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
621 "globals must be a real dict; try eval(expr, {}, mapping)"
622 : "globals must be a dict");
623 return NULL;
625 if (globals == Py_None) {
626 globals = PyEval_GetGlobals();
627 if (locals == Py_None)
628 locals = PyEval_GetLocals();
630 else if (locals == Py_None)
631 locals = globals;
633 if (globals == NULL || locals == NULL) {
634 PyErr_SetString(PyExc_TypeError,
635 "eval must be given globals and locals "
636 "when called without a frame");
637 return NULL;
640 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
641 if (PyDict_SetItemString(globals, "__builtins__",
642 PyEval_GetBuiltins()) != 0)
643 return NULL;
646 if (PyCode_Check(cmd)) {
647 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
648 PyErr_SetString(PyExc_TypeError,
649 "code object passed to eval() may not contain free variables");
650 return NULL;
652 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
655 if (!PyString_Check(cmd) &&
656 !PyUnicode_Check(cmd)) {
657 PyErr_SetString(PyExc_TypeError,
658 "eval() arg 1 must be a string or code object");
659 return NULL;
661 cf.cf_flags = 0;
663 #ifdef Py_USING_UNICODE
664 if (PyUnicode_Check(cmd)) {
665 tmp = PyUnicode_AsUTF8String(cmd);
666 if (tmp == NULL)
667 return NULL;
668 cmd = tmp;
669 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
671 #endif
672 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
673 Py_XDECREF(tmp);
674 return NULL;
676 while (*str == ' ' || *str == '\t')
677 str++;
679 (void)PyEval_MergeCompilerFlags(&cf);
680 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
681 Py_XDECREF(tmp);
682 return result;
685 PyDoc_STRVAR(eval_doc,
686 "eval(source[, globals[, locals]]) -> value\n\
688 Evaluate the source in the context of globals and locals.\n\
689 The source may be a string representing a Python expression\n\
690 or a code object as returned by compile().\n\
691 The globals must be a dictionary and locals can be any mapping,\n\
692 defaulting to the current globals and locals.\n\
693 If only globals is given, locals defaults to it.\n");
696 static PyObject *
697 builtin_execfile(PyObject *self, PyObject *args)
699 char *filename;
700 PyObject *globals = Py_None, *locals = Py_None;
701 PyObject *res;
702 FILE* fp = NULL;
703 PyCompilerFlags cf;
704 int exists;
706 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
707 1) < 0)
708 return NULL;
710 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
711 &filename,
712 &PyDict_Type, &globals,
713 &locals))
714 return NULL;
715 if (locals != Py_None && !PyMapping_Check(locals)) {
716 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
717 return NULL;
719 if (globals == Py_None) {
720 globals = PyEval_GetGlobals();
721 if (locals == Py_None)
722 locals = PyEval_GetLocals();
724 else if (locals == Py_None)
725 locals = globals;
726 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
727 if (PyDict_SetItemString(globals, "__builtins__",
728 PyEval_GetBuiltins()) != 0)
729 return NULL;
732 exists = 0;
733 /* Test for existence or directory. */
734 #if defined(PLAN9)
736 Dir *d;
738 if ((d = dirstat(filename))!=nil) {
739 if(d->mode & DMDIR)
740 werrstr("is a directory");
741 else
742 exists = 1;
743 free(d);
746 #elif defined(RISCOS)
747 if (object_exists(filename)) {
748 if (isdir(filename))
749 errno = EISDIR;
750 else
751 exists = 1;
753 #else /* standard Posix */
755 struct stat s;
756 if (stat(filename, &s) == 0) {
757 if (S_ISDIR(s.st_mode))
758 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
759 errno = EOS2ERR;
760 # else
761 errno = EISDIR;
762 # endif
763 else
764 exists = 1;
767 #endif
769 if (exists) {
770 Py_BEGIN_ALLOW_THREADS
771 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
772 Py_END_ALLOW_THREADS
774 if (fp == NULL) {
775 exists = 0;
779 if (!exists) {
780 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
781 return NULL;
783 cf.cf_flags = 0;
784 if (PyEval_MergeCompilerFlags(&cf))
785 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
786 locals, 1, &cf);
787 else
788 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
789 locals, 1);
790 return res;
793 PyDoc_STRVAR(execfile_doc,
794 "execfile(filename[, globals[, locals]])\n\
796 Read and execute a Python script from a file.\n\
797 The globals and locals are dictionaries, defaulting to the current\n\
798 globals and locals. If only globals is given, locals defaults to it.");
801 static PyObject *
802 builtin_getattr(PyObject *self, PyObject *args)
804 PyObject *v, *result, *dflt = NULL;
805 PyObject *name;
807 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
808 return NULL;
809 #ifdef Py_USING_UNICODE
810 if (PyUnicode_Check(name)) {
811 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
812 if (name == NULL)
813 return NULL;
815 #endif
817 if (!PyString_Check(name)) {
818 PyErr_SetString(PyExc_TypeError,
819 "getattr(): attribute name must be string");
820 return NULL;
822 result = PyObject_GetAttr(v, name);
823 if (result == NULL && dflt != NULL &&
824 PyErr_ExceptionMatches(PyExc_AttributeError))
826 PyErr_Clear();
827 Py_INCREF(dflt);
828 result = dflt;
830 return result;
833 PyDoc_STRVAR(getattr_doc,
834 "getattr(object, name[, default]) -> value\n\
836 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
837 When a default argument is given, it is returned when the attribute doesn't\n\
838 exist; without it, an exception is raised in that case.");
841 static PyObject *
842 builtin_globals(PyObject *self)
844 PyObject *d;
846 d = PyEval_GetGlobals();
847 Py_XINCREF(d);
848 return d;
851 PyDoc_STRVAR(globals_doc,
852 "globals() -> dictionary\n\
854 Return the dictionary containing the current scope's global variables.");
857 static PyObject *
858 builtin_hasattr(PyObject *self, PyObject *args)
860 PyObject *v;
861 PyObject *name;
863 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
864 return NULL;
865 #ifdef Py_USING_UNICODE
866 if (PyUnicode_Check(name)) {
867 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
868 if (name == NULL)
869 return NULL;
871 #endif
873 if (!PyString_Check(name)) {
874 PyErr_SetString(PyExc_TypeError,
875 "hasattr(): attribute name must be string");
876 return NULL;
878 v = PyObject_GetAttr(v, name);
879 if (v == NULL) {
880 if (!PyErr_ExceptionMatches(PyExc_Exception))
881 return NULL;
882 else {
883 PyErr_Clear();
884 Py_INCREF(Py_False);
885 return Py_False;
888 Py_DECREF(v);
889 Py_INCREF(Py_True);
890 return Py_True;
893 PyDoc_STRVAR(hasattr_doc,
894 "hasattr(object, name) -> bool\n\
896 Return whether the object has an attribute with the given name.\n\
897 (This is done by calling getattr(object, name) and catching exceptions.)");
900 static PyObject *
901 builtin_id(PyObject *self, PyObject *v)
903 return PyLong_FromVoidPtr(v);
906 PyDoc_STRVAR(id_doc,
907 "id(object) -> integer\n\
909 Return the identity of an object. This is guaranteed to be unique among\n\
910 simultaneously existing objects. (Hint: it's the object's memory address.)");
913 static PyObject *
914 builtin_map(PyObject *self, PyObject *args)
916 typedef struct {
917 PyObject *it; /* the iterator object */
918 int saw_StopIteration; /* bool: did the iterator end? */
919 } sequence;
921 PyObject *func, *result;
922 sequence *seqs = NULL, *sqp;
923 Py_ssize_t n, len;
924 register int i, j;
926 n = PyTuple_Size(args);
927 if (n < 2) {
928 PyErr_SetString(PyExc_TypeError,
929 "map() requires at least two args");
930 return NULL;
933 func = PyTuple_GetItem(args, 0);
934 n--;
936 if (func == Py_None) {
937 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
938 "use list(...)", 1) < 0)
939 return NULL;
940 if (n == 1) {
941 /* map(None, S) is the same as list(S). */
942 return PySequence_List(PyTuple_GetItem(args, 1));
946 /* Get space for sequence descriptors. Must NULL out the iterator
947 * pointers so that jumping to Fail_2 later doesn't see trash.
949 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
950 PyErr_NoMemory();
951 return NULL;
953 for (i = 0; i < n; ++i) {
954 seqs[i].it = (PyObject*)NULL;
955 seqs[i].saw_StopIteration = 0;
958 /* Do a first pass to obtain iterators for the arguments, and set len
959 * to the largest of their lengths.
961 len = 0;
962 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
963 PyObject *curseq;
964 Py_ssize_t curlen;
966 /* Get iterator. */
967 curseq = PyTuple_GetItem(args, i+1);
968 sqp->it = PyObject_GetIter(curseq);
969 if (sqp->it == NULL) {
970 static char errmsg[] =
971 "argument %d to map() must support iteration";
972 char errbuf[sizeof(errmsg) + 25];
973 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
974 PyErr_SetString(PyExc_TypeError, errbuf);
975 goto Fail_2;
978 /* Update len. */
979 curlen = _PyObject_LengthHint(curseq, 8);
980 if (curlen > len)
981 len = curlen;
984 /* Get space for the result list. */
985 if ((result = (PyObject *) PyList_New(len)) == NULL)
986 goto Fail_2;
988 /* Iterate over the sequences until all have stopped. */
989 for (i = 0; ; ++i) {
990 PyObject *alist, *item=NULL, *value;
991 int numactive = 0;
993 if (func == Py_None && n == 1)
994 alist = NULL;
995 else if ((alist = PyTuple_New(n)) == NULL)
996 goto Fail_1;
998 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
999 if (sqp->saw_StopIteration) {
1000 Py_INCREF(Py_None);
1001 item = Py_None;
1003 else {
1004 item = PyIter_Next(sqp->it);
1005 if (item)
1006 ++numactive;
1007 else {
1008 if (PyErr_Occurred()) {
1009 Py_XDECREF(alist);
1010 goto Fail_1;
1012 Py_INCREF(Py_None);
1013 item = Py_None;
1014 sqp->saw_StopIteration = 1;
1017 if (alist)
1018 PyTuple_SET_ITEM(alist, j, item);
1019 else
1020 break;
1023 if (!alist)
1024 alist = item;
1026 if (numactive == 0) {
1027 Py_DECREF(alist);
1028 break;
1031 if (func == Py_None)
1032 value = alist;
1033 else {
1034 value = PyEval_CallObject(func, alist);
1035 Py_DECREF(alist);
1036 if (value == NULL)
1037 goto Fail_1;
1039 if (i >= len) {
1040 int status = PyList_Append(result, value);
1041 Py_DECREF(value);
1042 if (status < 0)
1043 goto Fail_1;
1045 else if (PyList_SetItem(result, i, value) < 0)
1046 goto Fail_1;
1049 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1050 goto Fail_1;
1052 goto Succeed;
1054 Fail_1:
1055 Py_DECREF(result);
1056 Fail_2:
1057 result = NULL;
1058 Succeed:
1059 assert(seqs);
1060 for (i = 0; i < n; ++i)
1061 Py_XDECREF(seqs[i].it);
1062 PyMem_DEL(seqs);
1063 return result;
1066 PyDoc_STRVAR(map_doc,
1067 "map(function, sequence[, sequence, ...]) -> list\n\
1069 Return a list of the results of applying the function to the items of\n\
1070 the argument sequence(s). If more than one sequence is given, the\n\
1071 function is called with an argument list consisting of the corresponding\n\
1072 item of each sequence, substituting None for missing values when not all\n\
1073 sequences have the same length. If the function is None, return a list of\n\
1074 the items of the sequence (or a list of tuples if more than one sequence).");
1077 static PyObject *
1078 builtin_next(PyObject *self, PyObject *args)
1080 PyObject *it, *res;
1081 PyObject *def = NULL;
1083 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1084 return NULL;
1085 if (!PyIter_Check(it)) {
1086 PyErr_Format(PyExc_TypeError,
1087 "%.200s object is not an iterator",
1088 it->ob_type->tp_name);
1089 return NULL;
1092 res = (*it->ob_type->tp_iternext)(it);
1093 if (res != NULL) {
1094 return res;
1095 } else if (def != NULL) {
1096 if (PyErr_Occurred()) {
1097 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1098 return NULL;
1099 PyErr_Clear();
1101 Py_INCREF(def);
1102 return def;
1103 } else if (PyErr_Occurred()) {
1104 return NULL;
1105 } else {
1106 PyErr_SetNone(PyExc_StopIteration);
1107 return NULL;
1111 PyDoc_STRVAR(next_doc,
1112 "next(iterator[, default])\n\
1114 Return the next item from the iterator. If default is given and the iterator\n\
1115 is exhausted, it is returned instead of raising StopIteration.");
1118 static PyObject *
1119 builtin_setattr(PyObject *self, PyObject *args)
1121 PyObject *v;
1122 PyObject *name;
1123 PyObject *value;
1125 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1126 return NULL;
1127 if (PyObject_SetAttr(v, name, value) != 0)
1128 return NULL;
1129 Py_INCREF(Py_None);
1130 return Py_None;
1133 PyDoc_STRVAR(setattr_doc,
1134 "setattr(object, name, value)\n\
1136 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1137 ``x.y = v''.");
1140 static PyObject *
1141 builtin_delattr(PyObject *self, PyObject *args)
1143 PyObject *v;
1144 PyObject *name;
1146 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1147 return NULL;
1148 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1149 return NULL;
1150 Py_INCREF(Py_None);
1151 return Py_None;
1154 PyDoc_STRVAR(delattr_doc,
1155 "delattr(object, name)\n\
1157 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1158 ``del x.y''.");
1161 static PyObject *
1162 builtin_hash(PyObject *self, PyObject *v)
1164 long x;
1166 x = PyObject_Hash(v);
1167 if (x == -1)
1168 return NULL;
1169 return PyInt_FromLong(x);
1172 PyDoc_STRVAR(hash_doc,
1173 "hash(object) -> integer\n\
1175 Return a hash value for the object. Two objects with the same value have\n\
1176 the same hash value. The reverse is not necessarily true, but likely.");
1179 static PyObject *
1180 builtin_hex(PyObject *self, PyObject *v)
1182 PyNumberMethods *nb;
1183 PyObject *res;
1185 if ((nb = v->ob_type->tp_as_number) == NULL ||
1186 nb->nb_hex == NULL) {
1187 PyErr_SetString(PyExc_TypeError,
1188 "hex() argument can't be converted to hex");
1189 return NULL;
1191 res = (*nb->nb_hex)(v);
1192 if (res && !PyString_Check(res)) {
1193 PyErr_Format(PyExc_TypeError,
1194 "__hex__ returned non-string (type %.200s)",
1195 res->ob_type->tp_name);
1196 Py_DECREF(res);
1197 return NULL;
1199 return res;
1202 PyDoc_STRVAR(hex_doc,
1203 "hex(number) -> string\n\
1205 Return the hexadecimal representation of an integer or long integer.");
1208 static PyObject *builtin_raw_input(PyObject *, PyObject *);
1210 static PyObject *
1211 builtin_input(PyObject *self, PyObject *args)
1213 PyObject *line;
1214 char *str;
1215 PyObject *res;
1216 PyObject *globals, *locals;
1217 PyCompilerFlags cf;
1219 line = builtin_raw_input(self, args);
1220 if (line == NULL)
1221 return line;
1222 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1223 return NULL;
1224 while (*str == ' ' || *str == '\t')
1225 str++;
1226 globals = PyEval_GetGlobals();
1227 locals = PyEval_GetLocals();
1228 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1229 if (PyDict_SetItemString(globals, "__builtins__",
1230 PyEval_GetBuiltins()) != 0)
1231 return NULL;
1233 cf.cf_flags = 0;
1234 PyEval_MergeCompilerFlags(&cf);
1235 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1236 Py_DECREF(line);
1237 return res;
1240 PyDoc_STRVAR(input_doc,
1241 "input([prompt]) -> value\n\
1243 Equivalent to eval(raw_input(prompt)).");
1246 static PyObject *
1247 builtin_intern(PyObject *self, PyObject *args)
1249 PyObject *s;
1250 if (!PyArg_ParseTuple(args, "S:intern", &s))
1251 return NULL;
1252 if (!PyString_CheckExact(s)) {
1253 PyErr_SetString(PyExc_TypeError,
1254 "can't intern subclass of string");
1255 return NULL;
1257 Py_INCREF(s);
1258 PyString_InternInPlace(&s);
1259 return s;
1262 PyDoc_STRVAR(intern_doc,
1263 "intern(string) -> string\n\
1265 ``Intern'' the given string. This enters the string in the (global)\n\
1266 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1267 Return the string itself or the previously interned string object with the\n\
1268 same value.");
1271 static PyObject *
1272 builtin_iter(PyObject *self, PyObject *args)
1274 PyObject *v, *w = NULL;
1276 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1277 return NULL;
1278 if (w == NULL)
1279 return PyObject_GetIter(v);
1280 if (!PyCallable_Check(v)) {
1281 PyErr_SetString(PyExc_TypeError,
1282 "iter(v, w): v must be callable");
1283 return NULL;
1285 return PyCallIter_New(v, w);
1288 PyDoc_STRVAR(iter_doc,
1289 "iter(collection) -> iterator\n\
1290 iter(callable, sentinel) -> iterator\n\
1292 Get an iterator from an object. In the first form, the argument must\n\
1293 supply its own iterator, or be a sequence.\n\
1294 In the second form, the callable is called until it returns the sentinel.");
1297 static PyObject *
1298 builtin_len(PyObject *self, PyObject *v)
1300 Py_ssize_t res;
1302 res = PyObject_Size(v);
1303 if (res < 0 && PyErr_Occurred())
1304 return NULL;
1305 return PyInt_FromSsize_t(res);
1308 PyDoc_STRVAR(len_doc,
1309 "len(object) -> integer\n\
1311 Return the number of items of a sequence or mapping.");
1314 static PyObject *
1315 builtin_locals(PyObject *self)
1317 PyObject *d;
1319 d = PyEval_GetLocals();
1320 Py_XINCREF(d);
1321 return d;
1324 PyDoc_STRVAR(locals_doc,
1325 "locals() -> dictionary\n\
1327 Update and return a dictionary containing the current scope's local variables.");
1330 static PyObject *
1331 min_max(PyObject *args, PyObject *kwds, int op)
1333 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1334 const char *name = op == Py_LT ? "min" : "max";
1336 if (PyTuple_Size(args) > 1)
1337 v = args;
1338 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1339 return NULL;
1341 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1342 keyfunc = PyDict_GetItemString(kwds, "key");
1343 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1344 PyErr_Format(PyExc_TypeError,
1345 "%s() got an unexpected keyword argument", name);
1346 return NULL;
1348 Py_INCREF(keyfunc);
1351 it = PyObject_GetIter(v);
1352 if (it == NULL) {
1353 Py_XDECREF(keyfunc);
1354 return NULL;
1357 maxitem = NULL; /* the result */
1358 maxval = NULL; /* the value associated with the result */
1359 while (( item = PyIter_Next(it) )) {
1360 /* get the value from the key function */
1361 if (keyfunc != NULL) {
1362 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1363 if (val == NULL)
1364 goto Fail_it_item;
1366 /* no key function; the value is the item */
1367 else {
1368 val = item;
1369 Py_INCREF(val);
1372 /* maximum value and item are unset; set them */
1373 if (maxval == NULL) {
1374 maxitem = item;
1375 maxval = val;
1377 /* maximum value and item are set; update them as necessary */
1378 else {
1379 int cmp = PyObject_RichCompareBool(val, maxval, op);
1380 if (cmp < 0)
1381 goto Fail_it_item_and_val;
1382 else if (cmp > 0) {
1383 Py_DECREF(maxval);
1384 Py_DECREF(maxitem);
1385 maxval = val;
1386 maxitem = item;
1388 else {
1389 Py_DECREF(item);
1390 Py_DECREF(val);
1394 if (PyErr_Occurred())
1395 goto Fail_it;
1396 if (maxval == NULL) {
1397 PyErr_Format(PyExc_ValueError,
1398 "%s() arg is an empty sequence", name);
1399 assert(maxitem == NULL);
1401 else
1402 Py_DECREF(maxval);
1403 Py_DECREF(it);
1404 Py_XDECREF(keyfunc);
1405 return maxitem;
1407 Fail_it_item_and_val:
1408 Py_DECREF(val);
1409 Fail_it_item:
1410 Py_DECREF(item);
1411 Fail_it:
1412 Py_XDECREF(maxval);
1413 Py_XDECREF(maxitem);
1414 Py_DECREF(it);
1415 Py_XDECREF(keyfunc);
1416 return NULL;
1419 static PyObject *
1420 builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1422 return min_max(args, kwds, Py_LT);
1425 PyDoc_STRVAR(min_doc,
1426 "min(iterable[, key=func]) -> value\n\
1427 min(a, b, c, ...[, key=func]) -> value\n\
1429 With a single iterable argument, return its smallest item.\n\
1430 With two or more arguments, return the smallest argument.");
1433 static PyObject *
1434 builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1436 return min_max(args, kwds, Py_GT);
1439 PyDoc_STRVAR(max_doc,
1440 "max(iterable[, key=func]) -> value\n\
1441 max(a, b, c, ...[, key=func]) -> value\n\
1443 With a single iterable argument, return its largest item.\n\
1444 With two or more arguments, return the largest argument.");
1447 static PyObject *
1448 builtin_oct(PyObject *self, PyObject *v)
1450 PyNumberMethods *nb;
1451 PyObject *res;
1453 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1454 nb->nb_oct == NULL) {
1455 PyErr_SetString(PyExc_TypeError,
1456 "oct() argument can't be converted to oct");
1457 return NULL;
1459 res = (*nb->nb_oct)(v);
1460 if (res && !PyString_Check(res)) {
1461 PyErr_Format(PyExc_TypeError,
1462 "__oct__ returned non-string (type %.200s)",
1463 res->ob_type->tp_name);
1464 Py_DECREF(res);
1465 return NULL;
1467 return res;
1470 PyDoc_STRVAR(oct_doc,
1471 "oct(number) -> string\n\
1473 Return the octal representation of an integer or long integer.");
1476 static PyObject *
1477 builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1479 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
1482 PyDoc_STRVAR(open_doc,
1483 "open(name[, mode[, buffering]]) -> file object\n\
1485 Open a file using the file() type, returns a file object. This is the\n\
1486 preferred way to open a file.");
1489 static PyObject *
1490 builtin_ord(PyObject *self, PyObject* obj)
1492 long ord;
1493 Py_ssize_t size;
1495 if (PyString_Check(obj)) {
1496 size = PyString_GET_SIZE(obj);
1497 if (size == 1) {
1498 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1499 return PyInt_FromLong(ord);
1501 } else if (PyByteArray_Check(obj)) {
1502 size = PyByteArray_GET_SIZE(obj);
1503 if (size == 1) {
1504 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1505 return PyInt_FromLong(ord);
1508 #ifdef Py_USING_UNICODE
1509 } else if (PyUnicode_Check(obj)) {
1510 size = PyUnicode_GET_SIZE(obj);
1511 if (size == 1) {
1512 ord = (long)*PyUnicode_AS_UNICODE(obj);
1513 return PyInt_FromLong(ord);
1515 #endif
1516 } else {
1517 PyErr_Format(PyExc_TypeError,
1518 "ord() expected string of length 1, but " \
1519 "%.200s found", obj->ob_type->tp_name);
1520 return NULL;
1523 PyErr_Format(PyExc_TypeError,
1524 "ord() expected a character, "
1525 "but string of length %zd found",
1526 size);
1527 return NULL;
1530 PyDoc_STRVAR(ord_doc,
1531 "ord(c) -> integer\n\
1533 Return the integer ordinal of a one-character string.");
1536 static PyObject *
1537 builtin_pow(PyObject *self, PyObject *args)
1539 PyObject *v, *w, *z = Py_None;
1541 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1542 return NULL;
1543 return PyNumber_Power(v, w, z);
1546 PyDoc_STRVAR(pow_doc,
1547 "pow(x, y[, z]) -> number\n\
1549 With two arguments, equivalent to x**y. With three arguments,\n\
1550 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1553 static PyObject *
1554 builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1556 static char *kwlist[] = {"sep", "end", "file", 0};
1557 static PyObject *dummy_args;
1558 PyObject *sep = NULL, *end = NULL, *file = NULL;
1559 int i, err;
1561 if (dummy_args == NULL) {
1562 if (!(dummy_args = PyTuple_New(0)))
1563 return NULL;
1565 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1566 kwlist, &sep, &end, &file))
1567 return NULL;
1568 if (file == NULL || file == Py_None) {
1569 file = PySys_GetObject("stdout");
1570 /* sys.stdout may be None when FILE* stdout isn't connected */
1571 if (file == Py_None)
1572 Py_RETURN_NONE;
1575 if (sep && sep != Py_None && !PyString_Check(sep) &&
1576 !PyUnicode_Check(sep)) {
1577 PyErr_Format(PyExc_TypeError,
1578 "sep must be None, str or unicode, not %.200s",
1579 sep->ob_type->tp_name);
1580 return NULL;
1582 if (end && end != Py_None && !PyString_Check(end) &&
1583 !PyUnicode_Check(end)) {
1584 PyErr_Format(PyExc_TypeError,
1585 "end must be None, str or unicode, not %.200s",
1586 end->ob_type->tp_name);
1587 return NULL;
1590 for (i = 0; i < PyTuple_Size(args); i++) {
1591 if (i > 0) {
1592 if (sep == NULL || sep == Py_None)
1593 err = PyFile_WriteString(" ", file);
1594 else
1595 err = PyFile_WriteObject(sep, file,
1596 Py_PRINT_RAW);
1597 if (err)
1598 return NULL;
1600 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1601 Py_PRINT_RAW);
1602 if (err)
1603 return NULL;
1606 if (end == NULL || end == Py_None)
1607 err = PyFile_WriteString("\n", file);
1608 else
1609 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1610 if (err)
1611 return NULL;
1613 Py_RETURN_NONE;
1616 PyDoc_STRVAR(print_doc,
1617 "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1619 Prints the values to a stream, or to sys.stdout by default.\n\
1620 Optional keyword arguments:\n\
1621 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1622 sep: string inserted between values, default a space.\n\
1623 end: string appended after the last value, default a newline.");
1626 /* Return number of items in range (lo, hi, step), when arguments are
1627 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1628 * & only if the true value is too large to fit in a signed long.
1629 * Arguments MUST return 1 with either PyInt_Check() or
1630 * PyLong_Check(). Return -1 when there is an error.
1632 static long
1633 get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1635 /* -------------------------------------------------------------
1636 Algorithm is equal to that of get_len_of_range(), but it operates
1637 on PyObjects (which are assumed to be PyLong or PyInt objects).
1638 ---------------------------------------------------------------*/
1639 long n;
1640 PyObject *diff = NULL;
1641 PyObject *one = NULL;
1642 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1643 /* holds sub-expression evaluations */
1645 /* if (lo >= hi), return length of 0. */
1646 if (PyObject_Compare(lo, hi) >= 0)
1647 return 0;
1649 if ((one = PyLong_FromLong(1L)) == NULL)
1650 goto Fail;
1652 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1653 goto Fail;
1655 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1656 goto Fail;
1658 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1659 goto Fail;
1661 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1662 goto Fail;
1664 n = PyLong_AsLong(tmp3);
1665 if (PyErr_Occurred()) { /* Check for Overflow */
1666 PyErr_Clear();
1667 goto Fail;
1670 Py_DECREF(tmp3);
1671 Py_DECREF(tmp2);
1672 Py_DECREF(diff);
1673 Py_DECREF(tmp1);
1674 Py_DECREF(one);
1675 return n;
1677 Fail:
1678 Py_XDECREF(tmp3);
1679 Py_XDECREF(tmp2);
1680 Py_XDECREF(diff);
1681 Py_XDECREF(tmp1);
1682 Py_XDECREF(one);
1683 return -1;
1686 /* An extension of builtin_range() that handles the case when PyLong
1687 * arguments are given. */
1688 static PyObject *
1689 handle_range_longs(PyObject *self, PyObject *args)
1691 PyObject *ilow;
1692 PyObject *ihigh = NULL;
1693 PyObject *istep = NULL;
1695 PyObject *curnum = NULL;
1696 PyObject *v = NULL;
1697 long bign;
1698 int i, n;
1699 int cmp_result;
1701 PyObject *zero = PyLong_FromLong(0);
1703 if (zero == NULL)
1704 return NULL;
1706 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1707 Py_DECREF(zero);
1708 return NULL;
1711 /* Figure out which way we were called, supply defaults, and be
1712 * sure to incref everything so that the decrefs at the end
1713 * are correct.
1715 assert(ilow != NULL);
1716 if (ihigh == NULL) {
1717 /* only 1 arg -- it's the upper limit */
1718 ihigh = ilow;
1719 ilow = NULL;
1721 assert(ihigh != NULL);
1722 Py_INCREF(ihigh);
1724 /* ihigh correct now; do ilow */
1725 if (ilow == NULL)
1726 ilow = zero;
1727 Py_INCREF(ilow);
1729 /* ilow and ihigh correct now; do istep */
1730 if (istep == NULL) {
1731 istep = PyLong_FromLong(1L);
1732 if (istep == NULL)
1733 goto Fail;
1735 else {
1736 Py_INCREF(istep);
1739 if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
1740 PyErr_Format(PyExc_TypeError,
1741 "range() integer start argument expected, got %s.",
1742 ilow->ob_type->tp_name);
1743 goto Fail;
1746 if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
1747 PyErr_Format(PyExc_TypeError,
1748 "range() integer end argument expected, got %s.",
1749 ihigh->ob_type->tp_name);
1750 goto Fail;
1753 if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
1754 PyErr_Format(PyExc_TypeError,
1755 "range() integer step argument expected, got %s.",
1756 istep->ob_type->tp_name);
1757 goto Fail;
1760 if (PyObject_Cmp(istep, zero, &cmp_result) == -1)
1761 goto Fail;
1762 if (cmp_result == 0) {
1763 PyErr_SetString(PyExc_ValueError,
1764 "range() step argument must not be zero");
1765 goto Fail;
1768 if (cmp_result > 0)
1769 bign = get_len_of_range_longs(ilow, ihigh, istep);
1770 else {
1771 PyObject *neg_istep = PyNumber_Negative(istep);
1772 if (neg_istep == NULL)
1773 goto Fail;
1774 bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
1775 Py_DECREF(neg_istep);
1778 n = (int)bign;
1779 if (bign < 0 || (long)n != bign) {
1780 PyErr_SetString(PyExc_OverflowError,
1781 "range() result has too many items");
1782 goto Fail;
1785 v = PyList_New(n);
1786 if (v == NULL)
1787 goto Fail;
1789 curnum = ilow;
1790 Py_INCREF(curnum);
1792 for (i = 0; i < n; i++) {
1793 PyObject *w = PyNumber_Long(curnum);
1794 PyObject *tmp_num;
1795 if (w == NULL)
1796 goto Fail;
1798 PyList_SET_ITEM(v, i, w);
1800 tmp_num = PyNumber_Add(curnum, istep);
1801 if (tmp_num == NULL)
1802 goto Fail;
1804 Py_DECREF(curnum);
1805 curnum = tmp_num;
1807 Py_DECREF(ilow);
1808 Py_DECREF(ihigh);
1809 Py_DECREF(istep);
1810 Py_DECREF(zero);
1811 Py_DECREF(curnum);
1812 return v;
1814 Fail:
1815 Py_DECREF(ilow);
1816 Py_DECREF(ihigh);
1817 Py_XDECREF(istep);
1818 Py_DECREF(zero);
1819 Py_XDECREF(curnum);
1820 Py_XDECREF(v);
1821 return NULL;
1824 /* Return number of items in range/xrange (lo, hi, step). step > 0
1825 * required. Return a value < 0 if & only if the true value is too
1826 * large to fit in a signed long.
1828 static long
1829 get_len_of_range(long lo, long hi, long step)
1831 /* -------------------------------------------------------------
1832 If lo >= hi, the range is empty.
1833 Else if n values are in the range, the last one is
1834 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1835 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1836 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1837 the RHS is non-negative and so truncation is the same as the
1838 floor. Letting M be the largest positive long, the worst case
1839 for the RHS numerator is hi=M, lo=-M-1, and then
1840 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1841 precision to compute the RHS exactly.
1842 ---------------------------------------------------------------*/
1843 long n = 0;
1844 if (lo < hi) {
1845 unsigned long uhi = (unsigned long)hi;
1846 unsigned long ulo = (unsigned long)lo;
1847 unsigned long diff = uhi - ulo - 1;
1848 n = (long)(diff / (unsigned long)step + 1);
1850 return n;
1853 static PyObject *
1854 builtin_range(PyObject *self, PyObject *args)
1856 long ilow = 0, ihigh = 0, istep = 1;
1857 long bign;
1858 int i, n;
1860 PyObject *v;
1862 if (PyTuple_Size(args) <= 1) {
1863 if (!PyArg_ParseTuple(args,
1864 "l;range() requires 1-3 int arguments",
1865 &ihigh)) {
1866 PyErr_Clear();
1867 return handle_range_longs(self, args);
1870 else {
1871 if (!PyArg_ParseTuple(args,
1872 "ll|l;range() requires 1-3 int arguments",
1873 &ilow, &ihigh, &istep)) {
1874 PyErr_Clear();
1875 return handle_range_longs(self, args);
1878 if (istep == 0) {
1879 PyErr_SetString(PyExc_ValueError,
1880 "range() step argument must not be zero");
1881 return NULL;
1883 if (istep > 0)
1884 bign = get_len_of_range(ilow, ihigh, istep);
1885 else
1886 bign = get_len_of_range(ihigh, ilow, -istep);
1887 n = (int)bign;
1888 if (bign < 0 || (long)n != bign) {
1889 PyErr_SetString(PyExc_OverflowError,
1890 "range() result has too many items");
1891 return NULL;
1893 v = PyList_New(n);
1894 if (v == NULL)
1895 return NULL;
1896 for (i = 0; i < n; i++) {
1897 PyObject *w = PyInt_FromLong(ilow);
1898 if (w == NULL) {
1899 Py_DECREF(v);
1900 return NULL;
1902 PyList_SET_ITEM(v, i, w);
1903 ilow += istep;
1905 return v;
1908 PyDoc_STRVAR(range_doc,
1909 "range([start,] stop[, step]) -> list of integers\n\
1911 Return a list containing an arithmetic progression of integers.\n\
1912 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1913 When step is given, it specifies the increment (or decrement).\n\
1914 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1915 These are exactly the valid indices for a list of 4 elements.");
1918 static PyObject *
1919 builtin_raw_input(PyObject *self, PyObject *args)
1921 PyObject *v = NULL;
1922 PyObject *fin = PySys_GetObject("stdin");
1923 PyObject *fout = PySys_GetObject("stdout");
1925 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
1926 return NULL;
1928 if (fin == NULL) {
1929 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
1930 return NULL;
1932 if (fout == NULL) {
1933 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
1934 return NULL;
1936 if (PyFile_SoftSpace(fout, 0)) {
1937 if (PyFile_WriteString(" ", fout) != 0)
1938 return NULL;
1940 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
1941 && isatty(fileno(PyFile_AsFile(fin)))
1942 && isatty(fileno(PyFile_AsFile(fout)))) {
1943 PyObject *po;
1944 char *prompt;
1945 char *s;
1946 PyObject *result;
1947 if (v != NULL) {
1948 po = PyObject_Str(v);
1949 if (po == NULL)
1950 return NULL;
1951 prompt = PyString_AsString(po);
1952 if (prompt == NULL)
1953 return NULL;
1955 else {
1956 po = NULL;
1957 prompt = "";
1959 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
1960 prompt);
1961 Py_XDECREF(po);
1962 if (s == NULL) {
1963 if (!PyErr_Occurred())
1964 PyErr_SetNone(PyExc_KeyboardInterrupt);
1965 return NULL;
1967 if (*s == '\0') {
1968 PyErr_SetNone(PyExc_EOFError);
1969 result = NULL;
1971 else { /* strip trailing '\n' */
1972 size_t len = strlen(s);
1973 if (len > PY_SSIZE_T_MAX) {
1974 PyErr_SetString(PyExc_OverflowError,
1975 "[raw_]input: input too long");
1976 result = NULL;
1978 else {
1979 result = PyString_FromStringAndSize(s, len-1);
1982 PyMem_FREE(s);
1983 return result;
1985 if (v != NULL) {
1986 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
1987 return NULL;
1989 return PyFile_GetLine(fin, -1);
1992 PyDoc_STRVAR(raw_input_doc,
1993 "raw_input([prompt]) -> string\n\
1995 Read a string from standard input. The trailing newline is stripped.\n\
1996 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1997 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1998 is printed without a trailing newline before reading.");
2001 static PyObject *
2002 builtin_reduce(PyObject *self, PyObject *args)
2004 PyObject *seq, *func, *result = NULL, *it;
2006 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2007 "use functools.reduce()", 1) < 0)
2008 return NULL;
2010 if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
2011 return NULL;
2012 if (result != NULL)
2013 Py_INCREF(result);
2015 it = PyObject_GetIter(seq);
2016 if (it == NULL) {
2017 PyErr_SetString(PyExc_TypeError,
2018 "reduce() arg 2 must support iteration");
2019 Py_XDECREF(result);
2020 return NULL;
2023 if ((args = PyTuple_New(2)) == NULL)
2024 goto Fail;
2026 for (;;) {
2027 PyObject *op2;
2029 if (args->ob_refcnt > 1) {
2030 Py_DECREF(args);
2031 if ((args = PyTuple_New(2)) == NULL)
2032 goto Fail;
2035 op2 = PyIter_Next(it);
2036 if (op2 == NULL) {
2037 if (PyErr_Occurred())
2038 goto Fail;
2039 break;
2042 if (result == NULL)
2043 result = op2;
2044 else {
2045 PyTuple_SetItem(args, 0, result);
2046 PyTuple_SetItem(args, 1, op2);
2047 if ((result = PyEval_CallObject(func, args)) == NULL)
2048 goto Fail;
2052 Py_DECREF(args);
2054 if (result == NULL)
2055 PyErr_SetString(PyExc_TypeError,
2056 "reduce() of empty sequence with no initial value");
2058 Py_DECREF(it);
2059 return result;
2061 Fail:
2062 Py_XDECREF(args);
2063 Py_XDECREF(result);
2064 Py_DECREF(it);
2065 return NULL;
2068 PyDoc_STRVAR(reduce_doc,
2069 "reduce(function, sequence[, initial]) -> value\n\
2071 Apply a function of two arguments cumulatively to the items of a sequence,\n\
2072 from left to right, so as to reduce the sequence to a single value.\n\
2073 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2074 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2075 of the sequence in the calculation, and serves as a default when the\n\
2076 sequence is empty.");
2079 static PyObject *
2080 builtin_reload(PyObject *self, PyObject *v)
2082 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2083 1) < 0)
2084 return NULL;
2086 return PyImport_ReloadModule(v);
2089 PyDoc_STRVAR(reload_doc,
2090 "reload(module) -> module\n\
2092 Reload the module. The module must have been successfully imported before.");
2095 static PyObject *
2096 builtin_repr(PyObject *self, PyObject *v)
2098 return PyObject_Repr(v);
2101 PyDoc_STRVAR(repr_doc,
2102 "repr(object) -> string\n\
2104 Return the canonical string representation of the object.\n\
2105 For most object types, eval(repr(object)) == object.");
2108 static PyObject *
2109 builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
2111 double number;
2112 double f;
2113 int ndigits = 0;
2114 int i;
2115 static char *kwlist[] = {"number", "ndigits", 0};
2117 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|i:round",
2118 kwlist, &number, &ndigits))
2119 return NULL;
2120 f = 1.0;
2121 i = abs(ndigits);
2122 while (--i >= 0)
2123 f = f*10.0;
2124 if (ndigits < 0)
2125 number /= f;
2126 else
2127 number *= f;
2128 if (number >= 0.0)
2129 number = floor(number + 0.5);
2130 else
2131 number = ceil(number - 0.5);
2132 if (ndigits < 0)
2133 number *= f;
2134 else
2135 number /= f;
2136 return PyFloat_FromDouble(number);
2139 PyDoc_STRVAR(round_doc,
2140 "round(number[, ndigits]) -> floating point number\n\
2142 Round a number to a given precision in decimal digits (default 0 digits).\n\
2143 This always returns a floating point number. Precision may be negative.");
2145 static PyObject *
2146 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2148 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2149 PyObject *callable;
2150 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2151 int reverse;
2153 /* args 1-4 should match listsort in Objects/listobject.c */
2154 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2155 kwlist, &seq, &compare, &keyfunc, &reverse))
2156 return NULL;
2158 newlist = PySequence_List(seq);
2159 if (newlist == NULL)
2160 return NULL;
2162 callable = PyObject_GetAttrString(newlist, "sort");
2163 if (callable == NULL) {
2164 Py_DECREF(newlist);
2165 return NULL;
2168 newargs = PyTuple_GetSlice(args, 1, 4);
2169 if (newargs == NULL) {
2170 Py_DECREF(newlist);
2171 Py_DECREF(callable);
2172 return NULL;
2175 v = PyObject_Call(callable, newargs, kwds);
2176 Py_DECREF(newargs);
2177 Py_DECREF(callable);
2178 if (v == NULL) {
2179 Py_DECREF(newlist);
2180 return NULL;
2182 Py_DECREF(v);
2183 return newlist;
2186 PyDoc_STRVAR(sorted_doc,
2187 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2189 static PyObject *
2190 builtin_vars(PyObject *self, PyObject *args)
2192 PyObject *v = NULL;
2193 PyObject *d;
2195 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2196 return NULL;
2197 if (v == NULL) {
2198 d = PyEval_GetLocals();
2199 if (d == NULL) {
2200 if (!PyErr_Occurred())
2201 PyErr_SetString(PyExc_SystemError,
2202 "vars(): no locals!?");
2204 else
2205 Py_INCREF(d);
2207 else {
2208 d = PyObject_GetAttrString(v, "__dict__");
2209 if (d == NULL) {
2210 PyErr_SetString(PyExc_TypeError,
2211 "vars() argument must have __dict__ attribute");
2212 return NULL;
2215 return d;
2218 PyDoc_STRVAR(vars_doc,
2219 "vars([object]) -> dictionary\n\
2221 Without arguments, equivalent to locals().\n\
2222 With an argument, equivalent to object.__dict__.");
2225 static PyObject*
2226 builtin_sum(PyObject *self, PyObject *args)
2228 PyObject *seq;
2229 PyObject *result = NULL;
2230 PyObject *temp, *item, *iter;
2232 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2233 return NULL;
2235 iter = PyObject_GetIter(seq);
2236 if (iter == NULL)
2237 return NULL;
2239 if (result == NULL) {
2240 result = PyInt_FromLong(0);
2241 if (result == NULL) {
2242 Py_DECREF(iter);
2243 return NULL;
2245 } else {
2246 /* reject string values for 'start' parameter */
2247 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2248 PyErr_SetString(PyExc_TypeError,
2249 "sum() can't sum strings [use ''.join(seq) instead]");
2250 Py_DECREF(iter);
2251 return NULL;
2253 Py_INCREF(result);
2256 #ifndef SLOW_SUM
2257 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2258 Assumes all inputs are the same type. If the assumption fails, default
2259 to the more general routine.
2261 if (PyInt_CheckExact(result)) {
2262 long i_result = PyInt_AS_LONG(result);
2263 Py_DECREF(result);
2264 result = NULL;
2265 while(result == NULL) {
2266 item = PyIter_Next(iter);
2267 if (item == NULL) {
2268 Py_DECREF(iter);
2269 if (PyErr_Occurred())
2270 return NULL;
2271 return PyInt_FromLong(i_result);
2273 if (PyInt_CheckExact(item)) {
2274 long b = PyInt_AS_LONG(item);
2275 long x = i_result + b;
2276 if ((x^i_result) >= 0 || (x^b) >= 0) {
2277 i_result = x;
2278 Py_DECREF(item);
2279 continue;
2282 /* Either overflowed or is not an int. Restore real objects and process normally */
2283 result = PyInt_FromLong(i_result);
2284 temp = PyNumber_Add(result, item);
2285 Py_DECREF(result);
2286 Py_DECREF(item);
2287 result = temp;
2288 if (result == NULL) {
2289 Py_DECREF(iter);
2290 return NULL;
2295 if (PyFloat_CheckExact(result)) {
2296 double f_result = PyFloat_AS_DOUBLE(result);
2297 Py_DECREF(result);
2298 result = NULL;
2299 while(result == NULL) {
2300 item = PyIter_Next(iter);
2301 if (item == NULL) {
2302 Py_DECREF(iter);
2303 if (PyErr_Occurred())
2304 return NULL;
2305 return PyFloat_FromDouble(f_result);
2307 if (PyFloat_CheckExact(item)) {
2308 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2309 f_result += PyFloat_AS_DOUBLE(item);
2310 PyFPE_END_PROTECT(f_result)
2311 Py_DECREF(item);
2312 continue;
2314 if (PyInt_CheckExact(item)) {
2315 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2316 f_result += (double)PyInt_AS_LONG(item);
2317 PyFPE_END_PROTECT(f_result)
2318 Py_DECREF(item);
2319 continue;
2321 result = PyFloat_FromDouble(f_result);
2322 temp = PyNumber_Add(result, item);
2323 Py_DECREF(result);
2324 Py_DECREF(item);
2325 result = temp;
2326 if (result == NULL) {
2327 Py_DECREF(iter);
2328 return NULL;
2332 #endif
2334 for(;;) {
2335 item = PyIter_Next(iter);
2336 if (item == NULL) {
2337 /* error, or end-of-sequence */
2338 if (PyErr_Occurred()) {
2339 Py_DECREF(result);
2340 result = NULL;
2342 break;
2344 temp = PyNumber_Add(result, item);
2345 Py_DECREF(result);
2346 Py_DECREF(item);
2347 result = temp;
2348 if (result == NULL)
2349 break;
2351 Py_DECREF(iter);
2352 return result;
2355 PyDoc_STRVAR(sum_doc,
2356 "sum(sequence[, start]) -> value\n\
2358 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2359 of parameter 'start' (which defaults to 0). When the sequence is\n\
2360 empty, returns start.");
2363 static PyObject *
2364 builtin_isinstance(PyObject *self, PyObject *args)
2366 PyObject *inst;
2367 PyObject *cls;
2368 int retval;
2370 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2371 return NULL;
2373 retval = PyObject_IsInstance(inst, cls);
2374 if (retval < 0)
2375 return NULL;
2376 return PyBool_FromLong(retval);
2379 PyDoc_STRVAR(isinstance_doc,
2380 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2382 Return whether an object is an instance of a class or of a subclass thereof.\n\
2383 With a type as second argument, return whether that is the object's type.\n\
2384 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2385 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2388 static PyObject *
2389 builtin_issubclass(PyObject *self, PyObject *args)
2391 PyObject *derived;
2392 PyObject *cls;
2393 int retval;
2395 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2396 return NULL;
2398 retval = PyObject_IsSubclass(derived, cls);
2399 if (retval < 0)
2400 return NULL;
2401 return PyBool_FromLong(retval);
2404 PyDoc_STRVAR(issubclass_doc,
2405 "issubclass(C, B) -> bool\n\
2407 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2408 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2409 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2412 static PyObject*
2413 builtin_zip(PyObject *self, PyObject *args)
2415 PyObject *ret;
2416 const Py_ssize_t itemsize = PySequence_Length(args);
2417 Py_ssize_t i;
2418 PyObject *itlist; /* tuple of iterators */
2419 Py_ssize_t len; /* guess at result length */
2421 if (itemsize == 0)
2422 return PyList_New(0);
2424 /* args must be a tuple */
2425 assert(PyTuple_Check(args));
2427 /* Guess at result length: the shortest of the input lengths.
2428 If some argument refuses to say, we refuse to guess too, lest
2429 an argument like xrange(sys.maxint) lead us astray.*/
2430 len = -1; /* unknown */
2431 for (i = 0; i < itemsize; ++i) {
2432 PyObject *item = PyTuple_GET_ITEM(args, i);
2433 Py_ssize_t thislen = _PyObject_LengthHint(item, -1);
2434 if (thislen < 0) {
2435 len = -1;
2436 break;
2438 else if (len < 0 || thislen < len)
2439 len = thislen;
2442 /* allocate result list */
2443 if (len < 0)
2444 len = 10; /* arbitrary */
2445 if ((ret = PyList_New(len)) == NULL)
2446 return NULL;
2448 /* obtain iterators */
2449 itlist = PyTuple_New(itemsize);
2450 if (itlist == NULL)
2451 goto Fail_ret;
2452 for (i = 0; i < itemsize; ++i) {
2453 PyObject *item = PyTuple_GET_ITEM(args, i);
2454 PyObject *it = PyObject_GetIter(item);
2455 if (it == NULL) {
2456 if (PyErr_ExceptionMatches(PyExc_TypeError))
2457 PyErr_Format(PyExc_TypeError,
2458 "zip argument #%zd must support iteration",
2459 i+1);
2460 goto Fail_ret_itlist;
2462 PyTuple_SET_ITEM(itlist, i, it);
2465 /* build result into ret list */
2466 for (i = 0; ; ++i) {
2467 int j;
2468 PyObject *next = PyTuple_New(itemsize);
2469 if (!next)
2470 goto Fail_ret_itlist;
2472 for (j = 0; j < itemsize; j++) {
2473 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2474 PyObject *item = PyIter_Next(it);
2475 if (!item) {
2476 if (PyErr_Occurred()) {
2477 Py_DECREF(ret);
2478 ret = NULL;
2480 Py_DECREF(next);
2481 Py_DECREF(itlist);
2482 goto Done;
2484 PyTuple_SET_ITEM(next, j, item);
2487 if (i < len)
2488 PyList_SET_ITEM(ret, i, next);
2489 else {
2490 int status = PyList_Append(ret, next);
2491 Py_DECREF(next);
2492 ++len;
2493 if (status < 0)
2494 goto Fail_ret_itlist;
2498 Done:
2499 if (ret != NULL && i < len) {
2500 /* The list is too big. */
2501 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2502 return NULL;
2504 return ret;
2506 Fail_ret_itlist:
2507 Py_DECREF(itlist);
2508 Fail_ret:
2509 Py_DECREF(ret);
2510 return NULL;
2514 PyDoc_STRVAR(zip_doc,
2515 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2517 Return a list of tuples, where each tuple contains the i-th element\n\
2518 from each of the argument sequences. The returned list is truncated\n\
2519 in length to the length of the shortest argument sequence.");
2522 static PyMethodDef builtin_methods[] = {
2523 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2524 {"abs", builtin_abs, METH_O, abs_doc},
2525 {"all", builtin_all, METH_O, all_doc},
2526 {"any", builtin_any, METH_O, any_doc},
2527 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2528 {"bin", builtin_bin, METH_O, bin_doc},
2529 {"callable", builtin_callable, METH_O, callable_doc},
2530 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2531 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2532 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2533 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2534 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2535 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2536 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2537 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2538 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2539 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2540 {"format", builtin_format, METH_VARARGS, format_doc},
2541 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2542 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2543 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2544 {"hash", builtin_hash, METH_O, hash_doc},
2545 {"hex", builtin_hex, METH_O, hex_doc},
2546 {"id", builtin_id, METH_O, id_doc},
2547 {"input", builtin_input, METH_VARARGS, input_doc},
2548 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2549 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2550 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2551 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2552 {"len", builtin_len, METH_O, len_doc},
2553 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2554 {"map", builtin_map, METH_VARARGS, map_doc},
2555 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2556 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2557 {"next", builtin_next, METH_VARARGS, next_doc},
2558 {"oct", builtin_oct, METH_O, oct_doc},
2559 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2560 {"ord", builtin_ord, METH_O, ord_doc},
2561 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2562 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2563 {"range", builtin_range, METH_VARARGS, range_doc},
2564 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2565 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2566 {"reload", builtin_reload, METH_O, reload_doc},
2567 {"repr", builtin_repr, METH_O, repr_doc},
2568 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2569 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2570 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2571 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2572 #ifdef Py_USING_UNICODE
2573 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
2574 #endif
2575 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2576 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2577 {NULL, NULL},
2580 PyDoc_STRVAR(builtin_doc,
2581 "Built-in functions, exceptions, and other objects.\n\
2583 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2585 PyObject *
2586 _PyBuiltin_Init(void)
2588 PyObject *mod, *dict, *debug;
2589 mod = Py_InitModule4("__builtin__", builtin_methods,
2590 builtin_doc, (PyObject *)NULL,
2591 PYTHON_API_VERSION);
2592 if (mod == NULL)
2593 return NULL;
2594 dict = PyModule_GetDict(mod);
2596 #ifdef Py_TRACE_REFS
2597 /* __builtin__ exposes a number of statically allocated objects
2598 * that, before this code was added in 2.3, never showed up in
2599 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2600 * result, programs leaking references to None and False (etc)
2601 * couldn't be diagnosed by examining sys.getobjects(0).
2603 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2604 #else
2605 #define ADD_TO_ALL(OBJECT) (void)0
2606 #endif
2608 #define SETBUILTIN(NAME, OBJECT) \
2609 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2610 return NULL; \
2611 ADD_TO_ALL(OBJECT)
2613 SETBUILTIN("None", Py_None);
2614 SETBUILTIN("Ellipsis", Py_Ellipsis);
2615 SETBUILTIN("NotImplemented", Py_NotImplemented);
2616 SETBUILTIN("False", Py_False);
2617 SETBUILTIN("True", Py_True);
2618 SETBUILTIN("basestring", &PyBaseString_Type);
2619 SETBUILTIN("bool", &PyBool_Type);
2620 /* SETBUILTIN("memoryview", &PyMemoryView_Type); */
2621 SETBUILTIN("bytearray", &PyByteArray_Type);
2622 SETBUILTIN("bytes", &PyString_Type);
2623 SETBUILTIN("buffer", &PyBuffer_Type);
2624 SETBUILTIN("classmethod", &PyClassMethod_Type);
2625 #ifndef WITHOUT_COMPLEX
2626 SETBUILTIN("complex", &PyComplex_Type);
2627 #endif
2628 SETBUILTIN("dict", &PyDict_Type);
2629 SETBUILTIN("enumerate", &PyEnum_Type);
2630 SETBUILTIN("file", &PyFile_Type);
2631 SETBUILTIN("float", &PyFloat_Type);
2632 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2633 SETBUILTIN("property", &PyProperty_Type);
2634 SETBUILTIN("int", &PyInt_Type);
2635 SETBUILTIN("list", &PyList_Type);
2636 SETBUILTIN("long", &PyLong_Type);
2637 SETBUILTIN("object", &PyBaseObject_Type);
2638 SETBUILTIN("reversed", &PyReversed_Type);
2639 SETBUILTIN("set", &PySet_Type);
2640 SETBUILTIN("slice", &PySlice_Type);
2641 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2642 SETBUILTIN("str", &PyString_Type);
2643 SETBUILTIN("super", &PySuper_Type);
2644 SETBUILTIN("tuple", &PyTuple_Type);
2645 SETBUILTIN("type", &PyType_Type);
2646 SETBUILTIN("xrange", &PyRange_Type);
2647 #ifdef Py_USING_UNICODE
2648 SETBUILTIN("unicode", &PyUnicode_Type);
2649 #endif
2650 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2651 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2652 Py_XDECREF(debug);
2653 return NULL;
2655 Py_XDECREF(debug);
2657 return mod;
2658 #undef ADD_TO_ALL
2659 #undef SETBUILTIN
2662 /* Helper for filter(): filter a tuple through a function */
2664 static PyObject *
2665 filtertuple(PyObject *func, PyObject *tuple)
2667 PyObject *result;
2668 Py_ssize_t i, j;
2669 Py_ssize_t len = PyTuple_Size(tuple);
2671 if (len == 0) {
2672 if (PyTuple_CheckExact(tuple))
2673 Py_INCREF(tuple);
2674 else
2675 tuple = PyTuple_New(0);
2676 return tuple;
2679 if ((result = PyTuple_New(len)) == NULL)
2680 return NULL;
2682 for (i = j = 0; i < len; ++i) {
2683 PyObject *item, *good;
2684 int ok;
2686 if (tuple->ob_type->tp_as_sequence &&
2687 tuple->ob_type->tp_as_sequence->sq_item) {
2688 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2689 if (item == NULL)
2690 goto Fail_1;
2691 } else {
2692 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2693 goto Fail_1;
2695 if (func == Py_None) {
2696 Py_INCREF(item);
2697 good = item;
2699 else {
2700 PyObject *arg = PyTuple_Pack(1, item);
2701 if (arg == NULL) {
2702 Py_DECREF(item);
2703 goto Fail_1;
2705 good = PyEval_CallObject(func, arg);
2706 Py_DECREF(arg);
2707 if (good == NULL) {
2708 Py_DECREF(item);
2709 goto Fail_1;
2712 ok = PyObject_IsTrue(good);
2713 Py_DECREF(good);
2714 if (ok) {
2715 if (PyTuple_SetItem(result, j++, item) < 0)
2716 goto Fail_1;
2718 else
2719 Py_DECREF(item);
2722 if (_PyTuple_Resize(&result, j) < 0)
2723 return NULL;
2725 return result;
2727 Fail_1:
2728 Py_DECREF(result);
2729 return NULL;
2733 /* Helper for filter(): filter a string through a function */
2735 static PyObject *
2736 filterstring(PyObject *func, PyObject *strobj)
2738 PyObject *result;
2739 Py_ssize_t i, j;
2740 Py_ssize_t len = PyString_Size(strobj);
2741 Py_ssize_t outlen = len;
2743 if (func == Py_None) {
2744 /* If it's a real string we can return the original,
2745 * as no character is ever false and __getitem__
2746 * does return this character. If it's a subclass
2747 * we must go through the __getitem__ loop */
2748 if (PyString_CheckExact(strobj)) {
2749 Py_INCREF(strobj);
2750 return strobj;
2753 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2754 return NULL;
2756 for (i = j = 0; i < len; ++i) {
2757 PyObject *item;
2758 int ok;
2760 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2761 if (item == NULL)
2762 goto Fail_1;
2763 if (func==Py_None) {
2764 ok = 1;
2765 } else {
2766 PyObject *arg, *good;
2767 arg = PyTuple_Pack(1, item);
2768 if (arg == NULL) {
2769 Py_DECREF(item);
2770 goto Fail_1;
2772 good = PyEval_CallObject(func, arg);
2773 Py_DECREF(arg);
2774 if (good == NULL) {
2775 Py_DECREF(item);
2776 goto Fail_1;
2778 ok = PyObject_IsTrue(good);
2779 Py_DECREF(good);
2781 if (ok) {
2782 Py_ssize_t reslen;
2783 if (!PyString_Check(item)) {
2784 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2785 " __getitem__ returned different type");
2786 Py_DECREF(item);
2787 goto Fail_1;
2789 reslen = PyString_GET_SIZE(item);
2790 if (reslen == 1) {
2791 PyString_AS_STRING(result)[j++] =
2792 PyString_AS_STRING(item)[0];
2793 } else {
2794 /* do we need more space? */
2795 Py_ssize_t need = j;
2797 /* calculate space requirements while checking for overflow */
2798 if (need > PY_SSIZE_T_MAX - reslen) {
2799 Py_DECREF(item);
2800 goto Fail_1;
2803 need += reslen;
2805 if (need > PY_SSIZE_T_MAX - len) {
2806 Py_DECREF(item);
2807 goto Fail_1;
2810 need += len;
2812 if (need <= i) {
2813 Py_DECREF(item);
2814 goto Fail_1;
2817 need = need - i - 1;
2819 assert(need >= 0);
2820 assert(outlen >= 0);
2822 if (need > outlen) {
2823 /* overallocate, to avoid reallocations */
2824 if (outlen > PY_SSIZE_T_MAX / 2) {
2825 Py_DECREF(item);
2826 return NULL;
2829 if (need<2*outlen) {
2830 need = 2*outlen;
2832 if (_PyString_Resize(&result, need)) {
2833 Py_DECREF(item);
2834 return NULL;
2836 outlen = need;
2838 memcpy(
2839 PyString_AS_STRING(result) + j,
2840 PyString_AS_STRING(item),
2841 reslen
2843 j += reslen;
2846 Py_DECREF(item);
2849 if (j < outlen)
2850 _PyString_Resize(&result, j);
2852 return result;
2854 Fail_1:
2855 Py_DECREF(result);
2856 return NULL;
2859 #ifdef Py_USING_UNICODE
2860 /* Helper for filter(): filter a Unicode object through a function */
2862 static PyObject *
2863 filterunicode(PyObject *func, PyObject *strobj)
2865 PyObject *result;
2866 register Py_ssize_t i, j;
2867 Py_ssize_t len = PyUnicode_GetSize(strobj);
2868 Py_ssize_t outlen = len;
2870 if (func == Py_None) {
2871 /* If it's a real string we can return the original,
2872 * as no character is ever false and __getitem__
2873 * does return this character. If it's a subclass
2874 * we must go through the __getitem__ loop */
2875 if (PyUnicode_CheckExact(strobj)) {
2876 Py_INCREF(strobj);
2877 return strobj;
2880 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2881 return NULL;
2883 for (i = j = 0; i < len; ++i) {
2884 PyObject *item, *arg, *good;
2885 int ok;
2887 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2888 if (item == NULL)
2889 goto Fail_1;
2890 if (func == Py_None) {
2891 ok = 1;
2892 } else {
2893 arg = PyTuple_Pack(1, item);
2894 if (arg == NULL) {
2895 Py_DECREF(item);
2896 goto Fail_1;
2898 good = PyEval_CallObject(func, arg);
2899 Py_DECREF(arg);
2900 if (good == NULL) {
2901 Py_DECREF(item);
2902 goto Fail_1;
2904 ok = PyObject_IsTrue(good);
2905 Py_DECREF(good);
2907 if (ok) {
2908 Py_ssize_t reslen;
2909 if (!PyUnicode_Check(item)) {
2910 PyErr_SetString(PyExc_TypeError,
2911 "can't filter unicode to unicode:"
2912 " __getitem__ returned different type");
2913 Py_DECREF(item);
2914 goto Fail_1;
2916 reslen = PyUnicode_GET_SIZE(item);
2917 if (reslen == 1)
2918 PyUnicode_AS_UNICODE(result)[j++] =
2919 PyUnicode_AS_UNICODE(item)[0];
2920 else {
2921 /* do we need more space? */
2922 Py_ssize_t need = j + reslen + len - i - 1;
2924 /* check that didnt overflow */
2925 if ((j > PY_SSIZE_T_MAX - reslen) ||
2926 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
2927 ((j + reslen + len) < i) ||
2928 ((j + reslen + len - i) <= 0)) {
2929 Py_DECREF(item);
2930 return NULL;
2933 assert(need >= 0);
2934 assert(outlen >= 0);
2936 if (need > outlen) {
2937 /* overallocate,
2938 to avoid reallocations */
2939 if (need < 2 * outlen) {
2940 if (outlen > PY_SSIZE_T_MAX / 2) {
2941 Py_DECREF(item);
2942 return NULL;
2943 } else {
2944 need = 2 * outlen;
2948 if (PyUnicode_Resize(
2949 &result, need) < 0) {
2950 Py_DECREF(item);
2951 goto Fail_1;
2953 outlen = need;
2955 memcpy(PyUnicode_AS_UNICODE(result) + j,
2956 PyUnicode_AS_UNICODE(item),
2957 reslen*sizeof(Py_UNICODE));
2958 j += reslen;
2961 Py_DECREF(item);
2964 if (j < outlen)
2965 PyUnicode_Resize(&result, j);
2967 return result;
2969 Fail_1:
2970 Py_DECREF(result);
2971 return NULL;
2973 #endif