issue1597011: Fix for bz2 module corner-case error due to error checking bug.
[python.git] / Python / bltinmodule.c
blobef3eac8f955f3d003dc08eeb92f357c4a110035a
1 /* Built-in functions */
3 #include "Python.h"
5 #include "node.h"
6 #include "code.h"
7 #include "eval.h"
9 #include <ctype.h>
11 #ifdef RISCOS
12 #include "unixstuff.h"
13 #endif
15 /* The default encoding used by the platform file system APIs
16 Can remain NULL for all platforms that don't have such a concept
18 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
19 const char *Py_FileSystemDefaultEncoding = "mbcs";
20 #elif defined(__APPLE__)
21 const char *Py_FileSystemDefaultEncoding = "utf-8";
22 #else
23 const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
24 #endif
26 /* Forward */
27 static PyObject *filterstring(PyObject *, PyObject *);
28 #ifdef Py_USING_UNICODE
29 static PyObject *filterunicode(PyObject *, PyObject *);
30 #endif
31 static PyObject *filtertuple (PyObject *, PyObject *);
33 static PyObject *
34 builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
36 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
37 "level", 0};
38 char *name;
39 PyObject *globals = NULL;
40 PyObject *locals = NULL;
41 PyObject *fromlist = NULL;
42 int level = -1;
44 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
45 kwlist, &name, &globals, &locals, &fromlist, &level))
46 return NULL;
47 return PyImport_ImportModuleLevel(name, globals, locals,
48 fromlist, level);
51 PyDoc_STRVAR(import_doc,
52 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
53 \n\
54 Import a module. The globals are only used to determine the context;\n\
55 they are not modified. The locals are currently unused. The fromlist\n\
56 should be a list of names to emulate ``from name import ...'', or an\n\
57 empty list to emulate ``import name''.\n\
58 When importing a module from a package, note that __import__('A.B', ...)\n\
59 returns package A when fromlist is empty, but its submodule B when\n\
60 fromlist is not empty. Level is used to determine whether to perform \n\
61 absolute or relative imports. -1 is the original strategy of attempting\n\
62 both absolute and relative imports, 0 is absolute, a positive number\n\
63 is the number of parent directories to search relative to the current module.");
66 static PyObject *
67 builtin_abs(PyObject *self, PyObject *v)
69 return PyNumber_Absolute(v);
72 PyDoc_STRVAR(abs_doc,
73 "abs(number) -> number\n\
74 \n\
75 Return the absolute value of the argument.");
77 static PyObject *
78 builtin_all(PyObject *self, PyObject *v)
80 PyObject *it, *item;
82 it = PyObject_GetIter(v);
83 if (it == NULL)
84 return NULL;
86 while ((item = PyIter_Next(it)) != NULL) {
87 int cmp = PyObject_IsTrue(item);
88 Py_DECREF(item);
89 if (cmp < 0) {
90 Py_DECREF(it);
91 return NULL;
93 if (cmp == 0) {
94 Py_DECREF(it);
95 Py_RETURN_FALSE;
98 Py_DECREF(it);
99 if (PyErr_Occurred())
100 return NULL;
101 Py_RETURN_TRUE;
104 PyDoc_STRVAR(all_doc,
105 "all(iterable) -> bool\n\
107 Return True if bool(x) is True for all values x in the iterable.");
109 static PyObject *
110 builtin_any(PyObject *self, PyObject *v)
112 PyObject *it, *item;
114 it = PyObject_GetIter(v);
115 if (it == NULL)
116 return NULL;
118 while ((item = PyIter_Next(it)) != NULL) {
119 int cmp = PyObject_IsTrue(item);
120 Py_DECREF(item);
121 if (cmp < 0) {
122 Py_DECREF(it);
123 return NULL;
125 if (cmp == 1) {
126 Py_DECREF(it);
127 Py_RETURN_TRUE;
130 Py_DECREF(it);
131 if (PyErr_Occurred())
132 return NULL;
133 Py_RETURN_FALSE;
136 PyDoc_STRVAR(any_doc,
137 "any(iterable) -> bool\n\
139 Return True if bool(x) is True for any x in the iterable.");
141 static PyObject *
142 builtin_apply(PyObject *self, PyObject *args)
144 PyObject *func, *alist = NULL, *kwdict = NULL;
145 PyObject *t = NULL, *retval = NULL;
147 if (Py_Py3kWarningFlag &&
148 PyErr_Warn(PyExc_DeprecationWarning,
149 "apply() not supported in 3.x") < 0)
150 return NULL;
152 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
153 return NULL;
154 if (alist != NULL) {
155 if (!PyTuple_Check(alist)) {
156 if (!PySequence_Check(alist)) {
157 PyErr_Format(PyExc_TypeError,
158 "apply() arg 2 expected sequence, found %s",
159 alist->ob_type->tp_name);
160 return NULL;
162 t = PySequence_Tuple(alist);
163 if (t == NULL)
164 return NULL;
165 alist = t;
168 if (kwdict != NULL && !PyDict_Check(kwdict)) {
169 PyErr_Format(PyExc_TypeError,
170 "apply() arg 3 expected dictionary, found %s",
171 kwdict->ob_type->tp_name);
172 goto finally;
174 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
175 finally:
176 Py_XDECREF(t);
177 return retval;
180 PyDoc_STRVAR(apply_doc,
181 "apply(object[, args[, kwargs]]) -> value\n\
183 Call a callable object with positional arguments taken from the tuple args,\n\
184 and keyword arguments taken from the optional dictionary kwargs.\n\
185 Note that classes are callable, as are instances with a __call__() method.\n\
187 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
188 function(*args, **keywords).");
191 static PyObject *
192 builtin_callable(PyObject *self, PyObject *v)
194 if (Py_Py3kWarningFlag &&
195 PyErr_Warn(PyExc_DeprecationWarning,
196 "callable() not supported in 3.x") < 0)
197 return NULL;
198 return PyBool_FromLong((long)PyCallable_Check(v));
201 PyDoc_STRVAR(callable_doc,
202 "callable(object) -> bool\n\
204 Return whether the object is callable (i.e., some kind of function).\n\
205 Note that classes are callable, as are instances with a __call__() method.");
208 static PyObject *
209 builtin_filter(PyObject *self, PyObject *args)
211 PyObject *func, *seq, *result, *it, *arg;
212 Py_ssize_t len; /* guess for result list size */
213 register Py_ssize_t j;
215 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
216 return NULL;
218 /* Strings and tuples return a result of the same type. */
219 if (PyString_Check(seq))
220 return filterstring(func, seq);
221 #ifdef Py_USING_UNICODE
222 if (PyUnicode_Check(seq))
223 return filterunicode(func, seq);
224 #endif
225 if (PyTuple_Check(seq))
226 return filtertuple(func, seq);
228 /* Pre-allocate argument list tuple. */
229 arg = PyTuple_New(1);
230 if (arg == NULL)
231 return NULL;
233 /* Get iterator. */
234 it = PyObject_GetIter(seq);
235 if (it == NULL)
236 goto Fail_arg;
238 /* Guess a result list size. */
239 len = _PyObject_LengthHint(seq);
240 if (len < 0) {
241 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
242 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
243 goto Fail_it;
245 PyErr_Clear();
246 len = 8; /* arbitrary */
249 /* Get a result list. */
250 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
251 /* Eww - can modify the list in-place. */
252 Py_INCREF(seq);
253 result = seq;
255 else {
256 result = PyList_New(len);
257 if (result == NULL)
258 goto Fail_it;
261 /* Build the result list. */
262 j = 0;
263 for (;;) {
264 PyObject *item;
265 int ok;
267 item = PyIter_Next(it);
268 if (item == NULL) {
269 if (PyErr_Occurred())
270 goto Fail_result_it;
271 break;
274 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
275 ok = PyObject_IsTrue(item);
277 else {
278 PyObject *good;
279 PyTuple_SET_ITEM(arg, 0, item);
280 good = PyObject_Call(func, arg, NULL);
281 PyTuple_SET_ITEM(arg, 0, NULL);
282 if (good == NULL) {
283 Py_DECREF(item);
284 goto Fail_result_it;
286 ok = PyObject_IsTrue(good);
287 Py_DECREF(good);
289 if (ok) {
290 if (j < len)
291 PyList_SET_ITEM(result, j, item);
292 else {
293 int status = PyList_Append(result, item);
294 Py_DECREF(item);
295 if (status < 0)
296 goto Fail_result_it;
298 ++j;
300 else
301 Py_DECREF(item);
305 /* Cut back result list if len is too big. */
306 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
307 goto Fail_result_it;
309 Py_DECREF(it);
310 Py_DECREF(arg);
311 return result;
313 Fail_result_it:
314 Py_DECREF(result);
315 Fail_it:
316 Py_DECREF(it);
317 Fail_arg:
318 Py_DECREF(arg);
319 return NULL;
322 PyDoc_STRVAR(filter_doc,
323 "filter(function or None, sequence) -> list, tuple, or string\n"
324 "\n"
325 "Return those items of sequence for which function(item) is true. If\n"
326 "function is None, return the items that are true. If sequence is a tuple\n"
327 "or string, return the same type, else return a list.");
329 static PyObject *
330 builtin_chr(PyObject *self, PyObject *args)
332 long x;
333 char s[1];
335 if (!PyArg_ParseTuple(args, "l:chr", &x))
336 return NULL;
337 if (x < 0 || x >= 256) {
338 PyErr_SetString(PyExc_ValueError,
339 "chr() arg not in range(256)");
340 return NULL;
342 s[0] = (char)x;
343 return PyString_FromStringAndSize(s, 1);
346 PyDoc_STRVAR(chr_doc,
347 "chr(i) -> character\n\
349 Return a string of one character with ordinal i; 0 <= i < 256.");
352 #ifdef Py_USING_UNICODE
353 static PyObject *
354 builtin_unichr(PyObject *self, PyObject *args)
356 long x;
358 if (!PyArg_ParseTuple(args, "l:unichr", &x))
359 return NULL;
361 return PyUnicode_FromOrdinal(x);
364 PyDoc_STRVAR(unichr_doc,
365 "unichr(i) -> Unicode character\n\
367 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
368 #endif
371 static PyObject *
372 builtin_cmp(PyObject *self, PyObject *args)
374 PyObject *a, *b;
375 int c;
377 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
378 return NULL;
379 if (PyObject_Cmp(a, b, &c) < 0)
380 return NULL;
381 return PyInt_FromLong((long)c);
384 PyDoc_STRVAR(cmp_doc,
385 "cmp(x, y) -> integer\n\
387 Return negative if x<y, zero if x==y, positive if x>y.");
390 static PyObject *
391 builtin_coerce(PyObject *self, PyObject *args)
393 PyObject *v, *w;
394 PyObject *res;
396 if (Py_Py3kWarningFlag &&
397 PyErr_Warn(PyExc_DeprecationWarning,
398 "coerce() not supported in 3.x") < 0)
399 return NULL;
401 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
402 return NULL;
403 if (PyNumber_Coerce(&v, &w) < 0)
404 return NULL;
405 res = PyTuple_Pack(2, v, w);
406 Py_DECREF(v);
407 Py_DECREF(w);
408 return res;
411 PyDoc_STRVAR(coerce_doc,
412 "coerce(x, y) -> (x1, y1)\n\
414 Return a tuple consisting of the two numeric arguments converted to\n\
415 a common type, using the same rules as used by arithmetic operations.\n\
416 If coercion is not possible, raise TypeError.");
418 static PyObject *
419 builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
421 char *str;
422 char *filename;
423 char *startstr;
424 int start;
425 int dont_inherit = 0;
426 int supplied_flags = 0;
427 PyCompilerFlags cf;
428 PyObject *result = NULL, *cmd, *tmp = NULL;
429 Py_ssize_t length;
430 static char *kwlist[] = {"source", "filename", "mode", "flags",
431 "dont_inherit", NULL};
433 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
434 kwlist, &cmd, &filename, &startstr,
435 &supplied_flags, &dont_inherit))
436 return NULL;
438 cf.cf_flags = supplied_flags;
440 #ifdef Py_USING_UNICODE
441 if (PyUnicode_Check(cmd)) {
442 tmp = PyUnicode_AsUTF8String(cmd);
443 if (tmp == NULL)
444 return NULL;
445 cmd = tmp;
446 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
448 #endif
449 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
450 return NULL;
451 if ((size_t)length != strlen(str)) {
452 PyErr_SetString(PyExc_TypeError,
453 "compile() expected string without null bytes");
454 goto cleanup;
457 if (strcmp(startstr, "exec") == 0)
458 start = Py_file_input;
459 else if (strcmp(startstr, "eval") == 0)
460 start = Py_eval_input;
461 else if (strcmp(startstr, "single") == 0)
462 start = Py_single_input;
463 else {
464 PyErr_SetString(PyExc_ValueError,
465 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
466 goto cleanup;
469 if (supplied_flags &
470 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
472 PyErr_SetString(PyExc_ValueError,
473 "compile(): unrecognised flags");
474 goto cleanup;
476 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
478 if (!dont_inherit) {
479 PyEval_MergeCompilerFlags(&cf);
481 result = Py_CompileStringFlags(str, filename, start, &cf);
482 cleanup:
483 Py_XDECREF(tmp);
484 return result;
487 PyDoc_STRVAR(compile_doc,
488 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
490 Compile the source string (a Python module, statement or expression)\n\
491 into a code object that can be executed by the exec statement or eval().\n\
492 The filename will be used for run-time error messages.\n\
493 The mode must be 'exec' to compile a module, 'single' to compile a\n\
494 single (interactive) statement, or 'eval' to compile an expression.\n\
495 The flags argument, if present, controls which future statements influence\n\
496 the compilation of the code.\n\
497 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
498 the effects of any future statements in effect in the code calling\n\
499 compile; if absent or zero these statements do influence the compilation,\n\
500 in addition to any features explicitly specified.");
502 static PyObject *
503 builtin_dir(PyObject *self, PyObject *args)
505 PyObject *arg = NULL;
507 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
508 return NULL;
509 return PyObject_Dir(arg);
512 PyDoc_STRVAR(dir_doc,
513 "dir([object]) -> list of strings\n"
514 "\n"
515 "If called without an argument, return the names in the current scope.\n"
516 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
517 "of the given object, and of attributes reachable from it.\n"
518 "If the object supplies a method named __dir__, it will be used; otherwise\n"
519 "the default dir() logic is used and returns:\n"
520 " for a module object: the module's attributes.\n"
521 " for a class object: its attributes, and recursively the attributes\n"
522 " of its bases.\n"
523 " for any other object: its attributes, its class's attributes, and\n"
524 " recursively the attributes of its class's base classes.");
526 static PyObject *
527 builtin_divmod(PyObject *self, PyObject *args)
529 PyObject *v, *w;
531 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
532 return NULL;
533 return PyNumber_Divmod(v, w);
536 PyDoc_STRVAR(divmod_doc,
537 "divmod(x, y) -> (div, mod)\n\
539 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
542 static PyObject *
543 builtin_eval(PyObject *self, PyObject *args)
545 PyObject *cmd, *result, *tmp = NULL;
546 PyObject *globals = Py_None, *locals = Py_None;
547 char *str;
548 PyCompilerFlags cf;
550 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
551 return NULL;
552 if (locals != Py_None && !PyMapping_Check(locals)) {
553 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
554 return NULL;
556 if (globals != Py_None && !PyDict_Check(globals)) {
557 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
558 "globals must be a real dict; try eval(expr, {}, mapping)"
559 : "globals must be a dict");
560 return NULL;
562 if (globals == Py_None) {
563 globals = PyEval_GetGlobals();
564 if (locals == Py_None)
565 locals = PyEval_GetLocals();
567 else if (locals == Py_None)
568 locals = globals;
570 if (globals == NULL || locals == NULL) {
571 PyErr_SetString(PyExc_TypeError,
572 "eval must be given globals and locals "
573 "when called without a frame");
574 return NULL;
577 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
578 if (PyDict_SetItemString(globals, "__builtins__",
579 PyEval_GetBuiltins()) != 0)
580 return NULL;
583 if (PyCode_Check(cmd)) {
584 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
585 PyErr_SetString(PyExc_TypeError,
586 "code object passed to eval() may not contain free variables");
587 return NULL;
589 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
592 if (!PyString_Check(cmd) &&
593 !PyUnicode_Check(cmd)) {
594 PyErr_SetString(PyExc_TypeError,
595 "eval() arg 1 must be a string or code object");
596 return NULL;
598 cf.cf_flags = 0;
600 #ifdef Py_USING_UNICODE
601 if (PyUnicode_Check(cmd)) {
602 tmp = PyUnicode_AsUTF8String(cmd);
603 if (tmp == NULL)
604 return NULL;
605 cmd = tmp;
606 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
608 #endif
609 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
610 Py_XDECREF(tmp);
611 return NULL;
613 while (*str == ' ' || *str == '\t')
614 str++;
616 (void)PyEval_MergeCompilerFlags(&cf);
617 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
618 Py_XDECREF(tmp);
619 return result;
622 PyDoc_STRVAR(eval_doc,
623 "eval(source[, globals[, locals]]) -> value\n\
625 Evaluate the source in the context of globals and locals.\n\
626 The source may be a string representing a Python expression\n\
627 or a code object as returned by compile().\n\
628 The globals must be a dictionary and locals can be any mapping,\n\
629 defaulting to the current globals and locals.\n\
630 If only globals is given, locals defaults to it.\n");
633 static PyObject *
634 builtin_execfile(PyObject *self, PyObject *args)
636 char *filename;
637 PyObject *globals = Py_None, *locals = Py_None;
638 PyObject *res;
639 FILE* fp = NULL;
640 PyCompilerFlags cf;
641 int exists;
643 if (Py_Py3kWarningFlag &&
644 PyErr_Warn(PyExc_DeprecationWarning,
645 "execfile() not supported in 3.x") < 0)
646 return NULL;
648 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
649 &filename,
650 &PyDict_Type, &globals,
651 &locals))
652 return NULL;
653 if (locals != Py_None && !PyMapping_Check(locals)) {
654 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
655 return NULL;
657 if (globals == Py_None) {
658 globals = PyEval_GetGlobals();
659 if (locals == Py_None)
660 locals = PyEval_GetLocals();
662 else if (locals == Py_None)
663 locals = globals;
664 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
665 if (PyDict_SetItemString(globals, "__builtins__",
666 PyEval_GetBuiltins()) != 0)
667 return NULL;
670 exists = 0;
671 /* Test for existence or directory. */
672 #if defined(PLAN9)
674 Dir *d;
676 if ((d = dirstat(filename))!=nil) {
677 if(d->mode & DMDIR)
678 werrstr("is a directory");
679 else
680 exists = 1;
681 free(d);
684 #elif defined(RISCOS)
685 if (object_exists(filename)) {
686 if (isdir(filename))
687 errno = EISDIR;
688 else
689 exists = 1;
691 #else /* standard Posix */
693 struct stat s;
694 if (stat(filename, &s) == 0) {
695 if (S_ISDIR(s.st_mode))
696 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
697 errno = EOS2ERR;
698 # else
699 errno = EISDIR;
700 # endif
701 else
702 exists = 1;
705 #endif
707 if (exists) {
708 Py_BEGIN_ALLOW_THREADS
709 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
710 Py_END_ALLOW_THREADS
712 if (fp == NULL) {
713 exists = 0;
717 if (!exists) {
718 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
719 return NULL;
721 cf.cf_flags = 0;
722 if (PyEval_MergeCompilerFlags(&cf))
723 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
724 locals, 1, &cf);
725 else
726 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
727 locals, 1);
728 return res;
731 PyDoc_STRVAR(execfile_doc,
732 "execfile(filename[, globals[, locals]])\n\
734 Read and execute a Python script from a file.\n\
735 The globals and locals are dictionaries, defaulting to the current\n\
736 globals and locals. If only globals is given, locals defaults to it.");
739 static PyObject *
740 builtin_getattr(PyObject *self, PyObject *args)
742 PyObject *v, *result, *dflt = NULL;
743 PyObject *name;
745 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
746 return NULL;
747 #ifdef Py_USING_UNICODE
748 if (PyUnicode_Check(name)) {
749 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
750 if (name == NULL)
751 return NULL;
753 #endif
755 if (!PyString_Check(name)) {
756 PyErr_SetString(PyExc_TypeError,
757 "getattr(): attribute name must be string");
758 return NULL;
760 result = PyObject_GetAttr(v, name);
761 if (result == NULL && dflt != NULL &&
762 PyErr_ExceptionMatches(PyExc_AttributeError))
764 PyErr_Clear();
765 Py_INCREF(dflt);
766 result = dflt;
768 return result;
771 PyDoc_STRVAR(getattr_doc,
772 "getattr(object, name[, default]) -> value\n\
774 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
775 When a default argument is given, it is returned when the attribute doesn't\n\
776 exist; without it, an exception is raised in that case.");
779 static PyObject *
780 builtin_globals(PyObject *self)
782 PyObject *d;
784 d = PyEval_GetGlobals();
785 Py_XINCREF(d);
786 return d;
789 PyDoc_STRVAR(globals_doc,
790 "globals() -> dictionary\n\
792 Return the dictionary containing the current scope's global variables.");
795 static PyObject *
796 builtin_hasattr(PyObject *self, PyObject *args)
798 PyObject *v;
799 PyObject *name;
801 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
802 return NULL;
803 #ifdef Py_USING_UNICODE
804 if (PyUnicode_Check(name)) {
805 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
806 if (name == NULL)
807 return NULL;
809 #endif
811 if (!PyString_Check(name)) {
812 PyErr_SetString(PyExc_TypeError,
813 "hasattr(): attribute name must be string");
814 return NULL;
816 v = PyObject_GetAttr(v, name);
817 if (v == NULL) {
818 PyErr_Clear();
819 Py_INCREF(Py_False);
820 return Py_False;
822 Py_DECREF(v);
823 Py_INCREF(Py_True);
824 return Py_True;
827 PyDoc_STRVAR(hasattr_doc,
828 "hasattr(object, name) -> bool\n\
830 Return whether the object has an attribute with the given name.\n\
831 (This is done by calling getattr(object, name) and catching exceptions.)");
834 static PyObject *
835 builtin_id(PyObject *self, PyObject *v)
837 return PyLong_FromVoidPtr(v);
840 PyDoc_STRVAR(id_doc,
841 "id(object) -> integer\n\
843 Return the identity of an object. This is guaranteed to be unique among\n\
844 simultaneously existing objects. (Hint: it's the object's memory address.)");
847 static PyObject *
848 builtin_map(PyObject *self, PyObject *args)
850 typedef struct {
851 PyObject *it; /* the iterator object */
852 int saw_StopIteration; /* bool: did the iterator end? */
853 } sequence;
855 PyObject *func, *result;
856 sequence *seqs = NULL, *sqp;
857 Py_ssize_t n, len;
858 register int i, j;
860 n = PyTuple_Size(args);
861 if (n < 2) {
862 PyErr_SetString(PyExc_TypeError,
863 "map() requires at least two args");
864 return NULL;
867 func = PyTuple_GetItem(args, 0);
868 n--;
870 if (func == Py_None && n == 1) {
871 /* map(None, S) is the same as list(S). */
872 return PySequence_List(PyTuple_GetItem(args, 1));
875 /* Get space for sequence descriptors. Must NULL out the iterator
876 * pointers so that jumping to Fail_2 later doesn't see trash.
878 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
879 PyErr_NoMemory();
880 return NULL;
882 for (i = 0; i < n; ++i) {
883 seqs[i].it = (PyObject*)NULL;
884 seqs[i].saw_StopIteration = 0;
887 /* Do a first pass to obtain iterators for the arguments, and set len
888 * to the largest of their lengths.
890 len = 0;
891 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
892 PyObject *curseq;
893 Py_ssize_t curlen;
895 /* Get iterator. */
896 curseq = PyTuple_GetItem(args, i+1);
897 sqp->it = PyObject_GetIter(curseq);
898 if (sqp->it == NULL) {
899 static char errmsg[] =
900 "argument %d to map() must support iteration";
901 char errbuf[sizeof(errmsg) + 25];
902 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
903 PyErr_SetString(PyExc_TypeError, errbuf);
904 goto Fail_2;
907 /* Update len. */
908 curlen = _PyObject_LengthHint(curseq);
909 if (curlen < 0) {
910 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
911 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
912 goto Fail_2;
914 PyErr_Clear();
915 curlen = 8; /* arbitrary */
917 if (curlen > len)
918 len = curlen;
921 /* Get space for the result list. */
922 if ((result = (PyObject *) PyList_New(len)) == NULL)
923 goto Fail_2;
925 /* Iterate over the sequences until all have stopped. */
926 for (i = 0; ; ++i) {
927 PyObject *alist, *item=NULL, *value;
928 int numactive = 0;
930 if (func == Py_None && n == 1)
931 alist = NULL;
932 else if ((alist = PyTuple_New(n)) == NULL)
933 goto Fail_1;
935 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
936 if (sqp->saw_StopIteration) {
937 Py_INCREF(Py_None);
938 item = Py_None;
940 else {
941 item = PyIter_Next(sqp->it);
942 if (item)
943 ++numactive;
944 else {
945 if (PyErr_Occurred()) {
946 Py_XDECREF(alist);
947 goto Fail_1;
949 Py_INCREF(Py_None);
950 item = Py_None;
951 sqp->saw_StopIteration = 1;
954 if (alist)
955 PyTuple_SET_ITEM(alist, j, item);
956 else
957 break;
960 if (!alist)
961 alist = item;
963 if (numactive == 0) {
964 Py_DECREF(alist);
965 break;
968 if (func == Py_None)
969 value = alist;
970 else {
971 value = PyEval_CallObject(func, alist);
972 Py_DECREF(alist);
973 if (value == NULL)
974 goto Fail_1;
976 if (i >= len) {
977 int status = PyList_Append(result, value);
978 Py_DECREF(value);
979 if (status < 0)
980 goto Fail_1;
982 else if (PyList_SetItem(result, i, value) < 0)
983 goto Fail_1;
986 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
987 goto Fail_1;
989 goto Succeed;
991 Fail_1:
992 Py_DECREF(result);
993 Fail_2:
994 result = NULL;
995 Succeed:
996 assert(seqs);
997 for (i = 0; i < n; ++i)
998 Py_XDECREF(seqs[i].it);
999 PyMem_DEL(seqs);
1000 return result;
1003 PyDoc_STRVAR(map_doc,
1004 "map(function, sequence[, sequence, ...]) -> list\n\
1006 Return a list of the results of applying the function to the items of\n\
1007 the argument sequence(s). If more than one sequence is given, the\n\
1008 function is called with an argument list consisting of the corresponding\n\
1009 item of each sequence, substituting None for missing values when not all\n\
1010 sequences have the same length. If the function is None, return a list of\n\
1011 the items of the sequence (or a list of tuples if more than one sequence).");
1014 static PyObject *
1015 builtin_setattr(PyObject *self, PyObject *args)
1017 PyObject *v;
1018 PyObject *name;
1019 PyObject *value;
1021 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1022 return NULL;
1023 if (PyObject_SetAttr(v, name, value) != 0)
1024 return NULL;
1025 Py_INCREF(Py_None);
1026 return Py_None;
1029 PyDoc_STRVAR(setattr_doc,
1030 "setattr(object, name, value)\n\
1032 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1033 ``x.y = v''.");
1036 static PyObject *
1037 builtin_delattr(PyObject *self, PyObject *args)
1039 PyObject *v;
1040 PyObject *name;
1042 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1043 return NULL;
1044 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1045 return NULL;
1046 Py_INCREF(Py_None);
1047 return Py_None;
1050 PyDoc_STRVAR(delattr_doc,
1051 "delattr(object, name)\n\
1053 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1054 ``del x.y''.");
1057 static PyObject *
1058 builtin_hash(PyObject *self, PyObject *v)
1060 long x;
1062 x = PyObject_Hash(v);
1063 if (x == -1)
1064 return NULL;
1065 return PyInt_FromLong(x);
1068 PyDoc_STRVAR(hash_doc,
1069 "hash(object) -> integer\n\
1071 Return a hash value for the object. Two objects with the same value have\n\
1072 the same hash value. The reverse is not necessarily true, but likely.");
1075 static PyObject *
1076 builtin_hex(PyObject *self, PyObject *v)
1078 PyNumberMethods *nb;
1079 PyObject *res;
1081 if ((nb = v->ob_type->tp_as_number) == NULL ||
1082 nb->nb_hex == NULL) {
1083 PyErr_SetString(PyExc_TypeError,
1084 "hex() argument can't be converted to hex");
1085 return NULL;
1087 res = (*nb->nb_hex)(v);
1088 if (res && !PyString_Check(res)) {
1089 PyErr_Format(PyExc_TypeError,
1090 "__hex__ returned non-string (type %.200s)",
1091 res->ob_type->tp_name);
1092 Py_DECREF(res);
1093 return NULL;
1095 return res;
1098 PyDoc_STRVAR(hex_doc,
1099 "hex(number) -> string\n\
1101 Return the hexadecimal representation of an integer or long integer.");
1104 static PyObject *builtin_raw_input(PyObject *, PyObject *);
1106 static PyObject *
1107 builtin_input(PyObject *self, PyObject *args)
1109 PyObject *line;
1110 char *str;
1111 PyObject *res;
1112 PyObject *globals, *locals;
1113 PyCompilerFlags cf;
1115 line = builtin_raw_input(self, args);
1116 if (line == NULL)
1117 return line;
1118 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1119 return NULL;
1120 while (*str == ' ' || *str == '\t')
1121 str++;
1122 globals = PyEval_GetGlobals();
1123 locals = PyEval_GetLocals();
1124 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1125 if (PyDict_SetItemString(globals, "__builtins__",
1126 PyEval_GetBuiltins()) != 0)
1127 return NULL;
1129 cf.cf_flags = 0;
1130 PyEval_MergeCompilerFlags(&cf);
1131 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1132 Py_DECREF(line);
1133 return res;
1136 PyDoc_STRVAR(input_doc,
1137 "input([prompt]) -> value\n\
1139 Equivalent to eval(raw_input(prompt)).");
1142 static PyObject *
1143 builtin_intern(PyObject *self, PyObject *args)
1145 PyObject *s;
1146 if (!PyArg_ParseTuple(args, "S:intern", &s))
1147 return NULL;
1148 if (!PyString_CheckExact(s)) {
1149 PyErr_SetString(PyExc_TypeError,
1150 "can't intern subclass of string");
1151 return NULL;
1153 Py_INCREF(s);
1154 PyString_InternInPlace(&s);
1155 return s;
1158 PyDoc_STRVAR(intern_doc,
1159 "intern(string) -> string\n\
1161 ``Intern'' the given string. This enters the string in the (global)\n\
1162 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1163 Return the string itself or the previously interned string object with the\n\
1164 same value.");
1167 static PyObject *
1168 builtin_iter(PyObject *self, PyObject *args)
1170 PyObject *v, *w = NULL;
1172 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1173 return NULL;
1174 if (w == NULL)
1175 return PyObject_GetIter(v);
1176 if (!PyCallable_Check(v)) {
1177 PyErr_SetString(PyExc_TypeError,
1178 "iter(v, w): v must be callable");
1179 return NULL;
1181 return PyCallIter_New(v, w);
1184 PyDoc_STRVAR(iter_doc,
1185 "iter(collection) -> iterator\n\
1186 iter(callable, sentinel) -> iterator\n\
1188 Get an iterator from an object. In the first form, the argument must\n\
1189 supply its own iterator, or be a sequence.\n\
1190 In the second form, the callable is called until it returns the sentinel.");
1193 static PyObject *
1194 builtin_len(PyObject *self, PyObject *v)
1196 Py_ssize_t res;
1198 res = PyObject_Size(v);
1199 if (res < 0 && PyErr_Occurred())
1200 return NULL;
1201 return PyInt_FromSsize_t(res);
1204 PyDoc_STRVAR(len_doc,
1205 "len(object) -> integer\n\
1207 Return the number of items of a sequence or mapping.");
1210 static PyObject *
1211 builtin_locals(PyObject *self)
1213 PyObject *d;
1215 d = PyEval_GetLocals();
1216 Py_XINCREF(d);
1217 return d;
1220 PyDoc_STRVAR(locals_doc,
1221 "locals() -> dictionary\n\
1223 Update and return a dictionary containing the current scope's local variables.");
1226 static PyObject *
1227 min_max(PyObject *args, PyObject *kwds, int op)
1229 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1230 const char *name = op == Py_LT ? "min" : "max";
1232 if (PyTuple_Size(args) > 1)
1233 v = args;
1234 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1235 return NULL;
1237 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1238 keyfunc = PyDict_GetItemString(kwds, "key");
1239 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1240 PyErr_Format(PyExc_TypeError,
1241 "%s() got an unexpected keyword argument", name);
1242 return NULL;
1246 it = PyObject_GetIter(v);
1247 if (it == NULL)
1248 return NULL;
1250 maxitem = NULL; /* the result */
1251 maxval = NULL; /* the value associated with the result */
1252 while (( item = PyIter_Next(it) )) {
1253 /* get the value from the key function */
1254 if (keyfunc != NULL) {
1255 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1256 if (val == NULL)
1257 goto Fail_it_item;
1259 /* no key function; the value is the item */
1260 else {
1261 val = item;
1262 Py_INCREF(val);
1265 /* maximum value and item are unset; set them */
1266 if (maxval == NULL) {
1267 maxitem = item;
1268 maxval = val;
1270 /* maximum value and item are set; update them as necessary */
1271 else {
1272 int cmp = PyObject_RichCompareBool(val, maxval, op);
1273 if (cmp < 0)
1274 goto Fail_it_item_and_val;
1275 else if (cmp > 0) {
1276 Py_DECREF(maxval);
1277 Py_DECREF(maxitem);
1278 maxval = val;
1279 maxitem = item;
1281 else {
1282 Py_DECREF(item);
1283 Py_DECREF(val);
1287 if (PyErr_Occurred())
1288 goto Fail_it;
1289 if (maxval == NULL) {
1290 PyErr_Format(PyExc_ValueError,
1291 "%s() arg is an empty sequence", name);
1292 assert(maxitem == NULL);
1294 else
1295 Py_DECREF(maxval);
1296 Py_DECREF(it);
1297 return maxitem;
1299 Fail_it_item_and_val:
1300 Py_DECREF(val);
1301 Fail_it_item:
1302 Py_DECREF(item);
1303 Fail_it:
1304 Py_XDECREF(maxval);
1305 Py_XDECREF(maxitem);
1306 Py_DECREF(it);
1307 return NULL;
1310 static PyObject *
1311 builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1313 return min_max(args, kwds, Py_LT);
1316 PyDoc_STRVAR(min_doc,
1317 "min(iterable[, key=func]) -> value\n\
1318 min(a, b, c, ...[, key=func]) -> value\n\
1320 With a single iterable argument, return its smallest item.\n\
1321 With two or more arguments, return the smallest argument.");
1324 static PyObject *
1325 builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1327 return min_max(args, kwds, Py_GT);
1330 PyDoc_STRVAR(max_doc,
1331 "max(iterable[, key=func]) -> value\n\
1332 max(a, b, c, ...[, key=func]) -> value\n\
1334 With a single iterable argument, return its largest item.\n\
1335 With two or more arguments, return the largest argument.");
1338 static PyObject *
1339 builtin_oct(PyObject *self, PyObject *v)
1341 PyNumberMethods *nb;
1342 PyObject *res;
1344 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1345 nb->nb_oct == NULL) {
1346 PyErr_SetString(PyExc_TypeError,
1347 "oct() argument can't be converted to oct");
1348 return NULL;
1350 res = (*nb->nb_oct)(v);
1351 if (res && !PyString_Check(res)) {
1352 PyErr_Format(PyExc_TypeError,
1353 "__oct__ returned non-string (type %.200s)",
1354 res->ob_type->tp_name);
1355 Py_DECREF(res);
1356 return NULL;
1358 return res;
1361 PyDoc_STRVAR(oct_doc,
1362 "oct(number) -> string\n\
1364 Return the octal representation of an integer or long integer.");
1367 static PyObject *
1368 builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1370 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
1373 PyDoc_STRVAR(open_doc,
1374 "open(name[, mode[, buffering]]) -> file object\n\
1376 Open a file using the file() type, returns a file object.");
1379 static PyObject *
1380 builtin_ord(PyObject *self, PyObject* obj)
1382 long ord;
1383 Py_ssize_t size;
1385 if (PyString_Check(obj)) {
1386 size = PyString_GET_SIZE(obj);
1387 if (size == 1) {
1388 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1389 return PyInt_FromLong(ord);
1391 #ifdef Py_USING_UNICODE
1392 } else if (PyUnicode_Check(obj)) {
1393 size = PyUnicode_GET_SIZE(obj);
1394 if (size == 1) {
1395 ord = (long)*PyUnicode_AS_UNICODE(obj);
1396 return PyInt_FromLong(ord);
1398 #endif
1399 } else {
1400 PyErr_Format(PyExc_TypeError,
1401 "ord() expected string of length 1, but " \
1402 "%.200s found", obj->ob_type->tp_name);
1403 return NULL;
1406 PyErr_Format(PyExc_TypeError,
1407 "ord() expected a character, "
1408 "but string of length %zd found",
1409 size);
1410 return NULL;
1413 PyDoc_STRVAR(ord_doc,
1414 "ord(c) -> integer\n\
1416 Return the integer ordinal of a one-character string.");
1419 static PyObject *
1420 builtin_pow(PyObject *self, PyObject *args)
1422 PyObject *v, *w, *z = Py_None;
1424 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1425 return NULL;
1426 return PyNumber_Power(v, w, z);
1429 PyDoc_STRVAR(pow_doc,
1430 "pow(x, y[, z]) -> number\n\
1432 With two arguments, equivalent to x**y. With three arguments,\n\
1433 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1437 /* Return number of items in range (lo, hi, step), when arguments are
1438 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1439 * & only if the true value is too large to fit in a signed long.
1440 * Arguments MUST return 1 with either PyInt_Check() or
1441 * PyLong_Check(). Return -1 when there is an error.
1443 static long
1444 get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1446 /* -------------------------------------------------------------
1447 Algorithm is equal to that of get_len_of_range(), but it operates
1448 on PyObjects (which are assumed to be PyLong or PyInt objects).
1449 ---------------------------------------------------------------*/
1450 long n;
1451 PyObject *diff = NULL;
1452 PyObject *one = NULL;
1453 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1454 /* holds sub-expression evaluations */
1456 /* if (lo >= hi), return length of 0. */
1457 if (PyObject_Compare(lo, hi) >= 0)
1458 return 0;
1460 if ((one = PyLong_FromLong(1L)) == NULL)
1461 goto Fail;
1463 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1464 goto Fail;
1466 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1467 goto Fail;
1469 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1470 goto Fail;
1472 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1473 goto Fail;
1475 n = PyLong_AsLong(tmp3);
1476 if (PyErr_Occurred()) { /* Check for Overflow */
1477 PyErr_Clear();
1478 goto Fail;
1481 Py_DECREF(tmp3);
1482 Py_DECREF(tmp2);
1483 Py_DECREF(diff);
1484 Py_DECREF(tmp1);
1485 Py_DECREF(one);
1486 return n;
1488 Fail:
1489 Py_XDECREF(tmp3);
1490 Py_XDECREF(tmp2);
1491 Py_XDECREF(diff);
1492 Py_XDECREF(tmp1);
1493 Py_XDECREF(one);
1494 return -1;
1497 /* An extension of builtin_range() that handles the case when PyLong
1498 * arguments are given. */
1499 static PyObject *
1500 handle_range_longs(PyObject *self, PyObject *args)
1502 PyObject *ilow;
1503 PyObject *ihigh = NULL;
1504 PyObject *istep = NULL;
1506 PyObject *curnum = NULL;
1507 PyObject *v = NULL;
1508 long bign;
1509 int i, n;
1510 int cmp_result;
1512 PyObject *zero = PyLong_FromLong(0);
1514 if (zero == NULL)
1515 return NULL;
1517 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1518 Py_DECREF(zero);
1519 return NULL;
1522 /* Figure out which way we were called, supply defaults, and be
1523 * sure to incref everything so that the decrefs at the end
1524 * are correct.
1526 assert(ilow != NULL);
1527 if (ihigh == NULL) {
1528 /* only 1 arg -- it's the upper limit */
1529 ihigh = ilow;
1530 ilow = NULL;
1532 assert(ihigh != NULL);
1533 Py_INCREF(ihigh);
1535 /* ihigh correct now; do ilow */
1536 if (ilow == NULL)
1537 ilow = zero;
1538 Py_INCREF(ilow);
1540 /* ilow and ihigh correct now; do istep */
1541 if (istep == NULL) {
1542 istep = PyLong_FromLong(1L);
1543 if (istep == NULL)
1544 goto Fail;
1546 else {
1547 Py_INCREF(istep);
1550 if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
1551 PyErr_Format(PyExc_TypeError,
1552 "range() integer start argument expected, got %s.",
1553 ilow->ob_type->tp_name);
1554 goto Fail;
1557 if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
1558 PyErr_Format(PyExc_TypeError,
1559 "range() integer end argument expected, got %s.",
1560 ihigh->ob_type->tp_name);
1561 goto Fail;
1564 if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
1565 PyErr_Format(PyExc_TypeError,
1566 "range() integer step argument expected, got %s.",
1567 istep->ob_type->tp_name);
1568 goto Fail;
1571 if (PyObject_Cmp(istep, zero, &cmp_result) == -1)
1572 goto Fail;
1573 if (cmp_result == 0) {
1574 PyErr_SetString(PyExc_ValueError,
1575 "range() step argument must not be zero");
1576 goto Fail;
1579 if (cmp_result > 0)
1580 bign = get_len_of_range_longs(ilow, ihigh, istep);
1581 else {
1582 PyObject *neg_istep = PyNumber_Negative(istep);
1583 if (neg_istep == NULL)
1584 goto Fail;
1585 bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
1586 Py_DECREF(neg_istep);
1589 n = (int)bign;
1590 if (bign < 0 || (long)n != bign) {
1591 PyErr_SetString(PyExc_OverflowError,
1592 "range() result has too many items");
1593 goto Fail;
1596 v = PyList_New(n);
1597 if (v == NULL)
1598 goto Fail;
1600 curnum = ilow;
1601 Py_INCREF(curnum);
1603 for (i = 0; i < n; i++) {
1604 PyObject *w = PyNumber_Long(curnum);
1605 PyObject *tmp_num;
1606 if (w == NULL)
1607 goto Fail;
1609 PyList_SET_ITEM(v, i, w);
1611 tmp_num = PyNumber_Add(curnum, istep);
1612 if (tmp_num == NULL)
1613 goto Fail;
1615 Py_DECREF(curnum);
1616 curnum = tmp_num;
1618 Py_DECREF(ilow);
1619 Py_DECREF(ihigh);
1620 Py_DECREF(istep);
1621 Py_DECREF(zero);
1622 Py_DECREF(curnum);
1623 return v;
1625 Fail:
1626 Py_DECREF(ilow);
1627 Py_DECREF(ihigh);
1628 Py_XDECREF(istep);
1629 Py_DECREF(zero);
1630 Py_XDECREF(curnum);
1631 Py_XDECREF(v);
1632 return NULL;
1635 /* Return number of items in range/xrange (lo, hi, step). step > 0
1636 * required. Return a value < 0 if & only if the true value is too
1637 * large to fit in a signed long.
1639 static long
1640 get_len_of_range(long lo, long hi, long step)
1642 /* -------------------------------------------------------------
1643 If lo >= hi, the range is empty.
1644 Else if n values are in the range, the last one is
1645 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1646 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1647 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1648 the RHS is non-negative and so truncation is the same as the
1649 floor. Letting M be the largest positive long, the worst case
1650 for the RHS numerator is hi=M, lo=-M-1, and then
1651 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1652 precision to compute the RHS exactly.
1653 ---------------------------------------------------------------*/
1654 long n = 0;
1655 if (lo < hi) {
1656 unsigned long uhi = (unsigned long)hi;
1657 unsigned long ulo = (unsigned long)lo;
1658 unsigned long diff = uhi - ulo - 1;
1659 n = (long)(diff / (unsigned long)step + 1);
1661 return n;
1664 static PyObject *
1665 builtin_range(PyObject *self, PyObject *args)
1667 long ilow = 0, ihigh = 0, istep = 1;
1668 long bign;
1669 int i, n;
1671 PyObject *v;
1673 if (PyTuple_Size(args) <= 1) {
1674 if (!PyArg_ParseTuple(args,
1675 "l;range() requires 1-3 int arguments",
1676 &ihigh)) {
1677 PyErr_Clear();
1678 return handle_range_longs(self, args);
1681 else {
1682 if (!PyArg_ParseTuple(args,
1683 "ll|l;range() requires 1-3 int arguments",
1684 &ilow, &ihigh, &istep)) {
1685 PyErr_Clear();
1686 return handle_range_longs(self, args);
1689 if (istep == 0) {
1690 PyErr_SetString(PyExc_ValueError,
1691 "range() step argument must not be zero");
1692 return NULL;
1694 if (istep > 0)
1695 bign = get_len_of_range(ilow, ihigh, istep);
1696 else
1697 bign = get_len_of_range(ihigh, ilow, -istep);
1698 n = (int)bign;
1699 if (bign < 0 || (long)n != bign) {
1700 PyErr_SetString(PyExc_OverflowError,
1701 "range() result has too many items");
1702 return NULL;
1704 v = PyList_New(n);
1705 if (v == NULL)
1706 return NULL;
1707 for (i = 0; i < n; i++) {
1708 PyObject *w = PyInt_FromLong(ilow);
1709 if (w == NULL) {
1710 Py_DECREF(v);
1711 return NULL;
1713 PyList_SET_ITEM(v, i, w);
1714 ilow += istep;
1716 return v;
1719 PyDoc_STRVAR(range_doc,
1720 "range([start,] stop[, step]) -> list of integers\n\
1722 Return a list containing an arithmetic progression of integers.\n\
1723 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1724 When step is given, it specifies the increment (or decrement).\n\
1725 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1726 These are exactly the valid indices for a list of 4 elements.");
1729 static PyObject *
1730 builtin_raw_input(PyObject *self, PyObject *args)
1732 PyObject *v = NULL;
1733 PyObject *fin = PySys_GetObject("stdin");
1734 PyObject *fout = PySys_GetObject("stdout");
1736 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
1737 return NULL;
1739 if (fin == NULL) {
1740 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
1741 return NULL;
1743 if (fout == NULL) {
1744 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
1745 return NULL;
1747 if (PyFile_SoftSpace(fout, 0)) {
1748 if (PyFile_WriteString(" ", fout) != 0)
1749 return NULL;
1751 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
1752 && isatty(fileno(PyFile_AsFile(fin)))
1753 && isatty(fileno(PyFile_AsFile(fout)))) {
1754 PyObject *po;
1755 char *prompt;
1756 char *s;
1757 PyObject *result;
1758 if (v != NULL) {
1759 po = PyObject_Str(v);
1760 if (po == NULL)
1761 return NULL;
1762 prompt = PyString_AsString(po);
1763 if (prompt == NULL)
1764 return NULL;
1766 else {
1767 po = NULL;
1768 prompt = "";
1770 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
1771 prompt);
1772 Py_XDECREF(po);
1773 if (s == NULL) {
1774 if (!PyErr_Occurred())
1775 PyErr_SetNone(PyExc_KeyboardInterrupt);
1776 return NULL;
1778 if (*s == '\0') {
1779 PyErr_SetNone(PyExc_EOFError);
1780 result = NULL;
1782 else { /* strip trailing '\n' */
1783 size_t len = strlen(s);
1784 if (len > PY_SSIZE_T_MAX) {
1785 PyErr_SetString(PyExc_OverflowError,
1786 "[raw_]input: input too long");
1787 result = NULL;
1789 else {
1790 result = PyString_FromStringAndSize(s, len-1);
1793 PyMem_FREE(s);
1794 return result;
1796 if (v != NULL) {
1797 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
1798 return NULL;
1800 return PyFile_GetLine(fin, -1);
1803 PyDoc_STRVAR(raw_input_doc,
1804 "raw_input([prompt]) -> string\n\
1806 Read a string from standard input. The trailing newline is stripped.\n\
1807 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1808 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1809 is printed without a trailing newline before reading.");
1812 static PyObject *
1813 builtin_reduce(PyObject *self, PyObject *args)
1815 PyObject *seq, *func, *result = NULL, *it;
1817 if (Py_Py3kWarningFlag &&
1818 PyErr_Warn(PyExc_DeprecationWarning,
1819 "reduce() not supported in 3.x") < 0)
1820 return NULL;
1822 if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
1823 return NULL;
1824 if (result != NULL)
1825 Py_INCREF(result);
1827 it = PyObject_GetIter(seq);
1828 if (it == NULL) {
1829 PyErr_SetString(PyExc_TypeError,
1830 "reduce() arg 2 must support iteration");
1831 Py_XDECREF(result);
1832 return NULL;
1835 if ((args = PyTuple_New(2)) == NULL)
1836 goto Fail;
1838 for (;;) {
1839 PyObject *op2;
1841 if (args->ob_refcnt > 1) {
1842 Py_DECREF(args);
1843 if ((args = PyTuple_New(2)) == NULL)
1844 goto Fail;
1847 op2 = PyIter_Next(it);
1848 if (op2 == NULL) {
1849 if (PyErr_Occurred())
1850 goto Fail;
1851 break;
1854 if (result == NULL)
1855 result = op2;
1856 else {
1857 PyTuple_SetItem(args, 0, result);
1858 PyTuple_SetItem(args, 1, op2);
1859 if ((result = PyEval_CallObject(func, args)) == NULL)
1860 goto Fail;
1864 Py_DECREF(args);
1866 if (result == NULL)
1867 PyErr_SetString(PyExc_TypeError,
1868 "reduce() of empty sequence with no initial value");
1870 Py_DECREF(it);
1871 return result;
1873 Fail:
1874 Py_XDECREF(args);
1875 Py_XDECREF(result);
1876 Py_DECREF(it);
1877 return NULL;
1880 PyDoc_STRVAR(reduce_doc,
1881 "reduce(function, sequence[, initial]) -> value\n\
1883 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1884 from left to right, so as to reduce the sequence to a single value.\n\
1885 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1886 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1887 of the sequence in the calculation, and serves as a default when the\n\
1888 sequence is empty.");
1891 static PyObject *
1892 builtin_reload(PyObject *self, PyObject *v)
1894 if (Py_Py3kWarningFlag &&
1895 PyErr_Warn(PyExc_DeprecationWarning,
1896 "reload() not supported in 3.x") < 0)
1897 return NULL;
1899 return PyImport_ReloadModule(v);
1902 PyDoc_STRVAR(reload_doc,
1903 "reload(module) -> module\n\
1905 Reload the module. The module must have been successfully imported before.");
1908 static PyObject *
1909 builtin_repr(PyObject *self, PyObject *v)
1911 return PyObject_Repr(v);
1914 PyDoc_STRVAR(repr_doc,
1915 "repr(object) -> string\n\
1917 Return the canonical string representation of the object.\n\
1918 For most object types, eval(repr(object)) == object.");
1921 static PyObject *
1922 builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
1924 double number;
1925 double f;
1926 int ndigits = 0;
1927 int i;
1928 static char *kwlist[] = {"number", "ndigits", 0};
1930 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|i:round",
1931 kwlist, &number, &ndigits))
1932 return NULL;
1933 f = 1.0;
1934 i = abs(ndigits);
1935 while (--i >= 0)
1936 f = f*10.0;
1937 if (ndigits < 0)
1938 number /= f;
1939 else
1940 number *= f;
1941 if (number >= 0.0)
1942 number = floor(number + 0.5);
1943 else
1944 number = ceil(number - 0.5);
1945 if (ndigits < 0)
1946 number *= f;
1947 else
1948 number /= f;
1949 return PyFloat_FromDouble(number);
1952 PyDoc_STRVAR(round_doc,
1953 "round(number[, ndigits]) -> floating point number\n\
1955 Round a number to a given precision in decimal digits (default 0 digits).\n\
1956 This always returns a floating point number. Precision may be negative.");
1958 static PyObject *
1959 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1961 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1962 PyObject *callable;
1963 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
1964 int reverse;
1966 /* args 1-4 should match listsort in Objects/listobject.c */
1967 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1968 kwlist, &seq, &compare, &keyfunc, &reverse))
1969 return NULL;
1971 newlist = PySequence_List(seq);
1972 if (newlist == NULL)
1973 return NULL;
1975 callable = PyObject_GetAttrString(newlist, "sort");
1976 if (callable == NULL) {
1977 Py_DECREF(newlist);
1978 return NULL;
1981 newargs = PyTuple_GetSlice(args, 1, 4);
1982 if (newargs == NULL) {
1983 Py_DECREF(newlist);
1984 Py_DECREF(callable);
1985 return NULL;
1988 v = PyObject_Call(callable, newargs, kwds);
1989 Py_DECREF(newargs);
1990 Py_DECREF(callable);
1991 if (v == NULL) {
1992 Py_DECREF(newlist);
1993 return NULL;
1995 Py_DECREF(v);
1996 return newlist;
1999 PyDoc_STRVAR(sorted_doc,
2000 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2002 static PyObject *
2003 builtin_vars(PyObject *self, PyObject *args)
2005 PyObject *v = NULL;
2006 PyObject *d;
2008 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2009 return NULL;
2010 if (v == NULL) {
2011 d = PyEval_GetLocals();
2012 if (d == NULL) {
2013 if (!PyErr_Occurred())
2014 PyErr_SetString(PyExc_SystemError,
2015 "vars(): no locals!?");
2017 else
2018 Py_INCREF(d);
2020 else {
2021 d = PyObject_GetAttrString(v, "__dict__");
2022 if (d == NULL) {
2023 PyErr_SetString(PyExc_TypeError,
2024 "vars() argument must have __dict__ attribute");
2025 return NULL;
2028 return d;
2031 PyDoc_STRVAR(vars_doc,
2032 "vars([object]) -> dictionary\n\
2034 Without arguments, equivalent to locals().\n\
2035 With an argument, equivalent to object.__dict__.");
2038 static PyObject*
2039 builtin_sum(PyObject *self, PyObject *args)
2041 PyObject *seq;
2042 PyObject *result = NULL;
2043 PyObject *temp, *item, *iter;
2045 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2046 return NULL;
2048 iter = PyObject_GetIter(seq);
2049 if (iter == NULL)
2050 return NULL;
2052 if (result == NULL) {
2053 result = PyInt_FromLong(0);
2054 if (result == NULL) {
2055 Py_DECREF(iter);
2056 return NULL;
2058 } else {
2059 /* reject string values for 'start' parameter */
2060 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2061 PyErr_SetString(PyExc_TypeError,
2062 "sum() can't sum strings [use ''.join(seq) instead]");
2063 Py_DECREF(iter);
2064 return NULL;
2066 Py_INCREF(result);
2069 for(;;) {
2070 item = PyIter_Next(iter);
2071 if (item == NULL) {
2072 /* error, or end-of-sequence */
2073 if (PyErr_Occurred()) {
2074 Py_DECREF(result);
2075 result = NULL;
2077 break;
2079 temp = PyNumber_Add(result, item);
2080 Py_DECREF(result);
2081 Py_DECREF(item);
2082 result = temp;
2083 if (result == NULL)
2084 break;
2086 Py_DECREF(iter);
2087 return result;
2090 PyDoc_STRVAR(sum_doc,
2091 "sum(sequence[, start]) -> value\n\
2093 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2094 of parameter 'start' (which defaults to 0). When the sequence is\n\
2095 empty, returns start.");
2098 static PyObject *
2099 builtin_isinstance(PyObject *self, PyObject *args)
2101 PyObject *inst;
2102 PyObject *cls;
2103 int retval;
2105 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2106 return NULL;
2108 retval = PyObject_IsInstance(inst, cls);
2109 if (retval < 0)
2110 return NULL;
2111 return PyBool_FromLong(retval);
2114 PyDoc_STRVAR(isinstance_doc,
2115 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2117 Return whether an object is an instance of a class or of a subclass thereof.\n\
2118 With a type as second argument, return whether that is the object's type.\n\
2119 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2120 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2123 static PyObject *
2124 builtin_issubclass(PyObject *self, PyObject *args)
2126 PyObject *derived;
2127 PyObject *cls;
2128 int retval;
2130 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2131 return NULL;
2133 retval = PyObject_IsSubclass(derived, cls);
2134 if (retval < 0)
2135 return NULL;
2136 return PyBool_FromLong(retval);
2139 PyDoc_STRVAR(issubclass_doc,
2140 "issubclass(C, B) -> bool\n\
2142 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2143 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2144 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2147 static PyObject*
2148 builtin_zip(PyObject *self, PyObject *args)
2150 PyObject *ret;
2151 const Py_ssize_t itemsize = PySequence_Length(args);
2152 Py_ssize_t i;
2153 PyObject *itlist; /* tuple of iterators */
2154 Py_ssize_t len; /* guess at result length */
2156 if (itemsize == 0)
2157 return PyList_New(0);
2159 /* args must be a tuple */
2160 assert(PyTuple_Check(args));
2162 /* Guess at result length: the shortest of the input lengths.
2163 If some argument refuses to say, we refuse to guess too, lest
2164 an argument like xrange(sys.maxint) lead us astray.*/
2165 len = -1; /* unknown */
2166 for (i = 0; i < itemsize; ++i) {
2167 PyObject *item = PyTuple_GET_ITEM(args, i);
2168 Py_ssize_t thislen = _PyObject_LengthHint(item);
2169 if (thislen < 0) {
2170 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
2171 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
2172 return NULL;
2174 PyErr_Clear();
2175 len = -1;
2176 break;
2178 else if (len < 0 || thislen < len)
2179 len = thislen;
2182 /* allocate result list */
2183 if (len < 0)
2184 len = 10; /* arbitrary */
2185 if ((ret = PyList_New(len)) == NULL)
2186 return NULL;
2188 /* obtain iterators */
2189 itlist = PyTuple_New(itemsize);
2190 if (itlist == NULL)
2191 goto Fail_ret;
2192 for (i = 0; i < itemsize; ++i) {
2193 PyObject *item = PyTuple_GET_ITEM(args, i);
2194 PyObject *it = PyObject_GetIter(item);
2195 if (it == NULL) {
2196 if (PyErr_ExceptionMatches(PyExc_TypeError))
2197 PyErr_Format(PyExc_TypeError,
2198 "zip argument #%zd must support iteration",
2199 i+1);
2200 goto Fail_ret_itlist;
2202 PyTuple_SET_ITEM(itlist, i, it);
2205 /* build result into ret list */
2206 for (i = 0; ; ++i) {
2207 int j;
2208 PyObject *next = PyTuple_New(itemsize);
2209 if (!next)
2210 goto Fail_ret_itlist;
2212 for (j = 0; j < itemsize; j++) {
2213 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2214 PyObject *item = PyIter_Next(it);
2215 if (!item) {
2216 if (PyErr_Occurred()) {
2217 Py_DECREF(ret);
2218 ret = NULL;
2220 Py_DECREF(next);
2221 Py_DECREF(itlist);
2222 goto Done;
2224 PyTuple_SET_ITEM(next, j, item);
2227 if (i < len)
2228 PyList_SET_ITEM(ret, i, next);
2229 else {
2230 int status = PyList_Append(ret, next);
2231 Py_DECREF(next);
2232 ++len;
2233 if (status < 0)
2234 goto Fail_ret_itlist;
2238 Done:
2239 if (ret != NULL && i < len) {
2240 /* The list is too big. */
2241 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2242 return NULL;
2244 return ret;
2246 Fail_ret_itlist:
2247 Py_DECREF(itlist);
2248 Fail_ret:
2249 Py_DECREF(ret);
2250 return NULL;
2254 PyDoc_STRVAR(zip_doc,
2255 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2257 Return a list of tuples, where each tuple contains the i-th element\n\
2258 from each of the argument sequences. The returned list is truncated\n\
2259 in length to the length of the shortest argument sequence.");
2262 static PyMethodDef builtin_methods[] = {
2263 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2264 {"abs", builtin_abs, METH_O, abs_doc},
2265 {"all", builtin_all, METH_O, all_doc},
2266 {"any", builtin_any, METH_O, any_doc},
2267 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2268 {"callable", builtin_callable, METH_O, callable_doc},
2269 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2270 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2271 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2272 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2273 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2274 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2275 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2276 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2277 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2278 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2279 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2280 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2281 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2282 {"hash", builtin_hash, METH_O, hash_doc},
2283 {"hex", builtin_hex, METH_O, hex_doc},
2284 {"id", builtin_id, METH_O, id_doc},
2285 {"input", builtin_input, METH_VARARGS, input_doc},
2286 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2287 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2288 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2289 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2290 {"len", builtin_len, METH_O, len_doc},
2291 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2292 {"map", builtin_map, METH_VARARGS, map_doc},
2293 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2294 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2295 {"oct", builtin_oct, METH_O, oct_doc},
2296 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2297 {"ord", builtin_ord, METH_O, ord_doc},
2298 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2299 {"range", builtin_range, METH_VARARGS, range_doc},
2300 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2301 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2302 {"reload", builtin_reload, METH_O, reload_doc},
2303 {"repr", builtin_repr, METH_O, repr_doc},
2304 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2305 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2306 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2307 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2308 #ifdef Py_USING_UNICODE
2309 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
2310 #endif
2311 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2312 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2313 {NULL, NULL},
2316 PyDoc_STRVAR(builtin_doc,
2317 "Built-in functions, exceptions, and other objects.\n\
2319 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2321 PyObject *
2322 _PyBuiltin_Init(void)
2324 PyObject *mod, *dict, *debug;
2325 mod = Py_InitModule4("__builtin__", builtin_methods,
2326 builtin_doc, (PyObject *)NULL,
2327 PYTHON_API_VERSION);
2328 if (mod == NULL)
2329 return NULL;
2330 dict = PyModule_GetDict(mod);
2332 #ifdef Py_TRACE_REFS
2333 /* __builtin__ exposes a number of statically allocated objects
2334 * that, before this code was added in 2.3, never showed up in
2335 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2336 * result, programs leaking references to None and False (etc)
2337 * couldn't be diagnosed by examining sys.getobjects(0).
2339 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2340 #else
2341 #define ADD_TO_ALL(OBJECT) (void)0
2342 #endif
2344 #define SETBUILTIN(NAME, OBJECT) \
2345 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2346 return NULL; \
2347 ADD_TO_ALL(OBJECT)
2349 SETBUILTIN("None", Py_None);
2350 SETBUILTIN("Ellipsis", Py_Ellipsis);
2351 SETBUILTIN("NotImplemented", Py_NotImplemented);
2352 SETBUILTIN("False", Py_False);
2353 SETBUILTIN("True", Py_True);
2354 SETBUILTIN("basestring", &PyBaseString_Type);
2355 SETBUILTIN("bool", &PyBool_Type);
2356 SETBUILTIN("buffer", &PyBuffer_Type);
2357 SETBUILTIN("classmethod", &PyClassMethod_Type);
2358 #ifndef WITHOUT_COMPLEX
2359 SETBUILTIN("complex", &PyComplex_Type);
2360 #endif
2361 SETBUILTIN("dict", &PyDict_Type);
2362 SETBUILTIN("enumerate", &PyEnum_Type);
2363 SETBUILTIN("file", &PyFile_Type);
2364 SETBUILTIN("float", &PyFloat_Type);
2365 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2366 SETBUILTIN("property", &PyProperty_Type);
2367 SETBUILTIN("int", &PyInt_Type);
2368 SETBUILTIN("list", &PyList_Type);
2369 SETBUILTIN("long", &PyLong_Type);
2370 SETBUILTIN("object", &PyBaseObject_Type);
2371 SETBUILTIN("reversed", &PyReversed_Type);
2372 SETBUILTIN("set", &PySet_Type);
2373 SETBUILTIN("slice", &PySlice_Type);
2374 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2375 SETBUILTIN("str", &PyString_Type);
2376 SETBUILTIN("super", &PySuper_Type);
2377 SETBUILTIN("tuple", &PyTuple_Type);
2378 SETBUILTIN("type", &PyType_Type);
2379 SETBUILTIN("xrange", &PyRange_Type);
2380 #ifdef Py_USING_UNICODE
2381 SETBUILTIN("unicode", &PyUnicode_Type);
2382 #endif
2383 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2384 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2385 Py_XDECREF(debug);
2386 return NULL;
2388 Py_XDECREF(debug);
2390 return mod;
2391 #undef ADD_TO_ALL
2392 #undef SETBUILTIN
2395 /* Helper for filter(): filter a tuple through a function */
2397 static PyObject *
2398 filtertuple(PyObject *func, PyObject *tuple)
2400 PyObject *result;
2401 Py_ssize_t i, j;
2402 Py_ssize_t len = PyTuple_Size(tuple);
2404 if (len == 0) {
2405 if (PyTuple_CheckExact(tuple))
2406 Py_INCREF(tuple);
2407 else
2408 tuple = PyTuple_New(0);
2409 return tuple;
2412 if ((result = PyTuple_New(len)) == NULL)
2413 return NULL;
2415 for (i = j = 0; i < len; ++i) {
2416 PyObject *item, *good;
2417 int ok;
2419 if (tuple->ob_type->tp_as_sequence &&
2420 tuple->ob_type->tp_as_sequence->sq_item) {
2421 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2422 if (item == NULL)
2423 goto Fail_1;
2424 } else {
2425 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2426 goto Fail_1;
2428 if (func == Py_None) {
2429 Py_INCREF(item);
2430 good = item;
2432 else {
2433 PyObject *arg = PyTuple_Pack(1, item);
2434 if (arg == NULL) {
2435 Py_DECREF(item);
2436 goto Fail_1;
2438 good = PyEval_CallObject(func, arg);
2439 Py_DECREF(arg);
2440 if (good == NULL) {
2441 Py_DECREF(item);
2442 goto Fail_1;
2445 ok = PyObject_IsTrue(good);
2446 Py_DECREF(good);
2447 if (ok) {
2448 if (PyTuple_SetItem(result, j++, item) < 0)
2449 goto Fail_1;
2451 else
2452 Py_DECREF(item);
2455 if (_PyTuple_Resize(&result, j) < 0)
2456 return NULL;
2458 return result;
2460 Fail_1:
2461 Py_DECREF(result);
2462 return NULL;
2466 /* Helper for filter(): filter a string through a function */
2468 static PyObject *
2469 filterstring(PyObject *func, PyObject *strobj)
2471 PyObject *result;
2472 Py_ssize_t i, j;
2473 Py_ssize_t len = PyString_Size(strobj);
2474 Py_ssize_t outlen = len;
2476 if (func == Py_None) {
2477 /* If it's a real string we can return the original,
2478 * as no character is ever false and __getitem__
2479 * does return this character. If it's a subclass
2480 * we must go through the __getitem__ loop */
2481 if (PyString_CheckExact(strobj)) {
2482 Py_INCREF(strobj);
2483 return strobj;
2486 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2487 return NULL;
2489 for (i = j = 0; i < len; ++i) {
2490 PyObject *item;
2491 int ok;
2493 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2494 if (item == NULL)
2495 goto Fail_1;
2496 if (func==Py_None) {
2497 ok = 1;
2498 } else {
2499 PyObject *arg, *good;
2500 arg = PyTuple_Pack(1, item);
2501 if (arg == NULL) {
2502 Py_DECREF(item);
2503 goto Fail_1;
2505 good = PyEval_CallObject(func, arg);
2506 Py_DECREF(arg);
2507 if (good == NULL) {
2508 Py_DECREF(item);
2509 goto Fail_1;
2511 ok = PyObject_IsTrue(good);
2512 Py_DECREF(good);
2514 if (ok) {
2515 Py_ssize_t reslen;
2516 if (!PyString_Check(item)) {
2517 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2518 " __getitem__ returned different type");
2519 Py_DECREF(item);
2520 goto Fail_1;
2522 reslen = PyString_GET_SIZE(item);
2523 if (reslen == 1) {
2524 PyString_AS_STRING(result)[j++] =
2525 PyString_AS_STRING(item)[0];
2526 } else {
2527 /* do we need more space? */
2528 Py_ssize_t need = j + reslen + len-i-1;
2529 if (need > outlen) {
2530 /* overallocate, to avoid reallocations */
2531 if (need<2*outlen)
2532 need = 2*outlen;
2533 if (_PyString_Resize(&result, need)) {
2534 Py_DECREF(item);
2535 return NULL;
2537 outlen = need;
2539 memcpy(
2540 PyString_AS_STRING(result) + j,
2541 PyString_AS_STRING(item),
2542 reslen
2544 j += reslen;
2547 Py_DECREF(item);
2550 if (j < outlen)
2551 _PyString_Resize(&result, j);
2553 return result;
2555 Fail_1:
2556 Py_DECREF(result);
2557 return NULL;
2560 #ifdef Py_USING_UNICODE
2561 /* Helper for filter(): filter a Unicode object through a function */
2563 static PyObject *
2564 filterunicode(PyObject *func, PyObject *strobj)
2566 PyObject *result;
2567 register Py_ssize_t i, j;
2568 Py_ssize_t len = PyUnicode_GetSize(strobj);
2569 Py_ssize_t outlen = len;
2571 if (func == Py_None) {
2572 /* If it's a real string we can return the original,
2573 * as no character is ever false and __getitem__
2574 * does return this character. If it's a subclass
2575 * we must go through the __getitem__ loop */
2576 if (PyUnicode_CheckExact(strobj)) {
2577 Py_INCREF(strobj);
2578 return strobj;
2581 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2582 return NULL;
2584 for (i = j = 0; i < len; ++i) {
2585 PyObject *item, *arg, *good;
2586 int ok;
2588 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2589 if (item == NULL)
2590 goto Fail_1;
2591 if (func == Py_None) {
2592 ok = 1;
2593 } else {
2594 arg = PyTuple_Pack(1, item);
2595 if (arg == NULL) {
2596 Py_DECREF(item);
2597 goto Fail_1;
2599 good = PyEval_CallObject(func, arg);
2600 Py_DECREF(arg);
2601 if (good == NULL) {
2602 Py_DECREF(item);
2603 goto Fail_1;
2605 ok = PyObject_IsTrue(good);
2606 Py_DECREF(good);
2608 if (ok) {
2609 Py_ssize_t reslen;
2610 if (!PyUnicode_Check(item)) {
2611 PyErr_SetString(PyExc_TypeError,
2612 "can't filter unicode to unicode:"
2613 " __getitem__ returned different type");
2614 Py_DECREF(item);
2615 goto Fail_1;
2617 reslen = PyUnicode_GET_SIZE(item);
2618 if (reslen == 1)
2619 PyUnicode_AS_UNICODE(result)[j++] =
2620 PyUnicode_AS_UNICODE(item)[0];
2621 else {
2622 /* do we need more space? */
2623 Py_ssize_t need = j + reslen + len - i - 1;
2624 if (need > outlen) {
2625 /* overallocate,
2626 to avoid reallocations */
2627 if (need < 2 * outlen)
2628 need = 2 * outlen;
2629 if (PyUnicode_Resize(
2630 &result, need) < 0) {
2631 Py_DECREF(item);
2632 goto Fail_1;
2634 outlen = need;
2636 memcpy(PyUnicode_AS_UNICODE(result) + j,
2637 PyUnicode_AS_UNICODE(item),
2638 reslen*sizeof(Py_UNICODE));
2639 j += reslen;
2642 Py_DECREF(item);
2645 if (j < outlen)
2646 PyUnicode_Resize(&result, j);
2648 return result;
2650 Fail_1:
2651 Py_DECREF(result);
2652 return NULL;
2654 #endif