Fixes (accepts patch) issue1339 - http://bugs.python.org/issue1339
[python.git] / Python / bltinmodule.c
blob3ebd29df9abd4c1903e16fafebbdc809febc7bd1
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;
81 PyObject *(*iternext)(PyObject *);
82 int cmp;
84 it = PyObject_GetIter(v);
85 if (it == NULL)
86 return NULL;
87 iternext = *Py_TYPE(it)->tp_iternext;
89 for (;;) {
90 item = iternext(it);
91 if (item == NULL)
92 break;
93 cmp = PyObject_IsTrue(item);
94 Py_DECREF(item);
95 if (cmp < 0) {
96 Py_DECREF(it);
97 return NULL;
99 if (cmp == 0) {
100 Py_DECREF(it);
101 Py_RETURN_FALSE;
104 Py_DECREF(it);
105 if (PyErr_Occurred()) {
106 if (PyErr_ExceptionMatches(PyExc_StopIteration))
107 PyErr_Clear();
108 else
109 return NULL;
111 Py_RETURN_TRUE;
114 PyDoc_STRVAR(all_doc,
115 "all(iterable) -> bool\n\
117 Return True if bool(x) is True for all values x in the iterable.");
119 static PyObject *
120 builtin_any(PyObject *self, PyObject *v)
122 PyObject *it, *item;
123 PyObject *(*iternext)(PyObject *);
124 int cmp;
126 it = PyObject_GetIter(v);
127 if (it == NULL)
128 return NULL;
129 iternext = *Py_TYPE(it)->tp_iternext;
131 for (;;) {
132 item = iternext(it);
133 if (item == NULL)
134 break;
135 cmp = PyObject_IsTrue(item);
136 Py_DECREF(item);
137 if (cmp < 0) {
138 Py_DECREF(it);
139 return NULL;
141 if (cmp == 1) {
142 Py_DECREF(it);
143 Py_RETURN_TRUE;
146 Py_DECREF(it);
147 if (PyErr_Occurred()) {
148 if (PyErr_ExceptionMatches(PyExc_StopIteration))
149 PyErr_Clear();
150 else
151 return NULL;
153 Py_RETURN_FALSE;
156 PyDoc_STRVAR(any_doc,
157 "any(iterable) -> bool\n\
159 Return True if bool(x) is True for any x in the iterable.");
161 static PyObject *
162 builtin_apply(PyObject *self, PyObject *args)
164 PyObject *func, *alist = NULL, *kwdict = NULL;
165 PyObject *t = NULL, *retval = NULL;
167 if (Py_Py3kWarningFlag &&
168 PyErr_Warn(PyExc_DeprecationWarning,
169 "apply() not supported in 3.x") < 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_callable(PyObject *self, PyObject *v)
214 if (Py_Py3kWarningFlag &&
215 PyErr_Warn(PyExc_DeprecationWarning,
216 "callable() not supported in 3.x") < 0)
217 return NULL;
218 return PyBool_FromLong((long)PyCallable_Check(v));
221 PyDoc_STRVAR(callable_doc,
222 "callable(object) -> bool\n\
224 Return whether the object is callable (i.e., some kind of function).\n\
225 Note that classes are callable, as are instances with a __call__() method.");
228 static PyObject *
229 builtin_filter(PyObject *self, PyObject *args)
231 PyObject *func, *seq, *result, *it, *arg;
232 Py_ssize_t len; /* guess for result list size */
233 register Py_ssize_t j;
235 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
236 return NULL;
238 /* Strings and tuples return a result of the same type. */
239 if (PyString_Check(seq))
240 return filterstring(func, seq);
241 #ifdef Py_USING_UNICODE
242 if (PyUnicode_Check(seq))
243 return filterunicode(func, seq);
244 #endif
245 if (PyTuple_Check(seq))
246 return filtertuple(func, seq);
248 /* Pre-allocate argument list tuple. */
249 arg = PyTuple_New(1);
250 if (arg == NULL)
251 return NULL;
253 /* Get iterator. */
254 it = PyObject_GetIter(seq);
255 if (it == NULL)
256 goto Fail_arg;
258 /* Guess a result list size. */
259 len = _PyObject_LengthHint(seq, 8);
261 /* Get a result list. */
262 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
263 /* Eww - can modify the list in-place. */
264 Py_INCREF(seq);
265 result = seq;
267 else {
268 result = PyList_New(len);
269 if (result == NULL)
270 goto Fail_it;
273 /* Build the result list. */
274 j = 0;
275 for (;;) {
276 PyObject *item;
277 int ok;
279 item = PyIter_Next(it);
280 if (item == NULL) {
281 if (PyErr_Occurred())
282 goto Fail_result_it;
283 break;
286 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
287 ok = PyObject_IsTrue(item);
289 else {
290 PyObject *good;
291 PyTuple_SET_ITEM(arg, 0, item);
292 good = PyObject_Call(func, arg, NULL);
293 PyTuple_SET_ITEM(arg, 0, NULL);
294 if (good == NULL) {
295 Py_DECREF(item);
296 goto Fail_result_it;
298 ok = PyObject_IsTrue(good);
299 Py_DECREF(good);
301 if (ok) {
302 if (j < len)
303 PyList_SET_ITEM(result, j, item);
304 else {
305 int status = PyList_Append(result, item);
306 Py_DECREF(item);
307 if (status < 0)
308 goto Fail_result_it;
310 ++j;
312 else
313 Py_DECREF(item);
317 /* Cut back result list if len is too big. */
318 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
319 goto Fail_result_it;
321 Py_DECREF(it);
322 Py_DECREF(arg);
323 return result;
325 Fail_result_it:
326 Py_DECREF(result);
327 Fail_it:
328 Py_DECREF(it);
329 Fail_arg:
330 Py_DECREF(arg);
331 return NULL;
334 PyDoc_STRVAR(filter_doc,
335 "filter(function or None, sequence) -> list, tuple, or string\n"
336 "\n"
337 "Return those items of sequence for which function(item) is true. If\n"
338 "function is None, return the items that are true. If sequence is a tuple\n"
339 "or string, return the same type, else return a list.");
341 static PyObject *
342 builtin_chr(PyObject *self, PyObject *args)
344 long x;
345 char s[1];
347 if (!PyArg_ParseTuple(args, "l:chr", &x))
348 return NULL;
349 if (x < 0 || x >= 256) {
350 PyErr_SetString(PyExc_ValueError,
351 "chr() arg not in range(256)");
352 return NULL;
354 s[0] = (char)x;
355 return PyString_FromStringAndSize(s, 1);
358 PyDoc_STRVAR(chr_doc,
359 "chr(i) -> character\n\
361 Return a string of one character with ordinal i; 0 <= i < 256.");
364 #ifdef Py_USING_UNICODE
365 static PyObject *
366 builtin_unichr(PyObject *self, PyObject *args)
368 long x;
370 if (!PyArg_ParseTuple(args, "l:unichr", &x))
371 return NULL;
373 return PyUnicode_FromOrdinal(x);
376 PyDoc_STRVAR(unichr_doc,
377 "unichr(i) -> Unicode character\n\
379 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
380 #endif
383 static PyObject *
384 builtin_cmp(PyObject *self, PyObject *args)
386 PyObject *a, *b;
387 int c;
389 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
390 return NULL;
391 if (PyObject_Cmp(a, b, &c) < 0)
392 return NULL;
393 return PyInt_FromLong((long)c);
396 PyDoc_STRVAR(cmp_doc,
397 "cmp(x, y) -> integer\n\
399 Return negative if x<y, zero if x==y, positive if x>y.");
402 static PyObject *
403 builtin_coerce(PyObject *self, PyObject *args)
405 PyObject *v, *w;
406 PyObject *res;
408 if (Py_Py3kWarningFlag &&
409 PyErr_Warn(PyExc_DeprecationWarning,
410 "coerce() not supported in 3.x") < 0)
411 return NULL;
413 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
414 return NULL;
415 if (PyNumber_Coerce(&v, &w) < 0)
416 return NULL;
417 res = PyTuple_Pack(2, v, w);
418 Py_DECREF(v);
419 Py_DECREF(w);
420 return res;
423 PyDoc_STRVAR(coerce_doc,
424 "coerce(x, y) -> (x1, y1)\n\
426 Return a tuple consisting of the two numeric arguments converted to\n\
427 a common type, using the same rules as used by arithmetic operations.\n\
428 If coercion is not possible, raise TypeError.");
430 static PyObject *
431 builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
433 char *str;
434 char *filename;
435 char *startstr;
436 int start;
437 int dont_inherit = 0;
438 int supplied_flags = 0;
439 PyCompilerFlags cf;
440 PyObject *result = NULL, *cmd, *tmp = NULL;
441 Py_ssize_t length;
442 static char *kwlist[] = {"source", "filename", "mode", "flags",
443 "dont_inherit", NULL};
445 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
446 kwlist, &cmd, &filename, &startstr,
447 &supplied_flags, &dont_inherit))
448 return NULL;
450 cf.cf_flags = supplied_flags;
452 #ifdef Py_USING_UNICODE
453 if (PyUnicode_Check(cmd)) {
454 tmp = PyUnicode_AsUTF8String(cmd);
455 if (tmp == NULL)
456 return NULL;
457 cmd = tmp;
458 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
460 #endif
461 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
462 return NULL;
463 if ((size_t)length != strlen(str)) {
464 PyErr_SetString(PyExc_TypeError,
465 "compile() expected string without null bytes");
466 goto cleanup;
469 if (strcmp(startstr, "exec") == 0)
470 start = Py_file_input;
471 else if (strcmp(startstr, "eval") == 0)
472 start = Py_eval_input;
473 else if (strcmp(startstr, "single") == 0)
474 start = Py_single_input;
475 else {
476 PyErr_SetString(PyExc_ValueError,
477 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
478 goto cleanup;
481 if (supplied_flags &
482 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
484 PyErr_SetString(PyExc_ValueError,
485 "compile(): unrecognised flags");
486 goto cleanup;
488 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
490 if (!dont_inherit) {
491 PyEval_MergeCompilerFlags(&cf);
493 result = Py_CompileStringFlags(str, filename, start, &cf);
494 cleanup:
495 Py_XDECREF(tmp);
496 return result;
499 PyDoc_STRVAR(compile_doc,
500 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
502 Compile the source string (a Python module, statement or expression)\n\
503 into a code object that can be executed by the exec statement or eval().\n\
504 The filename will be used for run-time error messages.\n\
505 The mode must be 'exec' to compile a module, 'single' to compile a\n\
506 single (interactive) statement, or 'eval' to compile an expression.\n\
507 The flags argument, if present, controls which future statements influence\n\
508 the compilation of the code.\n\
509 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
510 the effects of any future statements in effect in the code calling\n\
511 compile; if absent or zero these statements do influence the compilation,\n\
512 in addition to any features explicitly specified.");
514 static PyObject *
515 builtin_dir(PyObject *self, PyObject *args)
517 PyObject *arg = NULL;
519 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
520 return NULL;
521 return PyObject_Dir(arg);
524 PyDoc_STRVAR(dir_doc,
525 "dir([object]) -> list of strings\n"
526 "\n"
527 "If called without an argument, return the names in the current scope.\n"
528 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
529 "of the given object, and of attributes reachable from it.\n"
530 "If the object supplies a method named __dir__, it will be used; otherwise\n"
531 "the default dir() logic is used and returns:\n"
532 " for a module object: the module's attributes.\n"
533 " for a class object: its attributes, and recursively the attributes\n"
534 " of its bases.\n"
535 " for any other object: its attributes, its class's attributes, and\n"
536 " recursively the attributes of its class's base classes.");
538 static PyObject *
539 builtin_divmod(PyObject *self, PyObject *args)
541 PyObject *v, *w;
543 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
544 return NULL;
545 return PyNumber_Divmod(v, w);
548 PyDoc_STRVAR(divmod_doc,
549 "divmod(x, y) -> (div, mod)\n\
551 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
554 static PyObject *
555 builtin_eval(PyObject *self, PyObject *args)
557 PyObject *cmd, *result, *tmp = NULL;
558 PyObject *globals = Py_None, *locals = Py_None;
559 char *str;
560 PyCompilerFlags cf;
562 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
563 return NULL;
564 if (locals != Py_None && !PyMapping_Check(locals)) {
565 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
566 return NULL;
568 if (globals != Py_None && !PyDict_Check(globals)) {
569 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
570 "globals must be a real dict; try eval(expr, {}, mapping)"
571 : "globals must be a dict");
572 return NULL;
574 if (globals == Py_None) {
575 globals = PyEval_GetGlobals();
576 if (locals == Py_None)
577 locals = PyEval_GetLocals();
579 else if (locals == Py_None)
580 locals = globals;
582 if (globals == NULL || locals == NULL) {
583 PyErr_SetString(PyExc_TypeError,
584 "eval must be given globals and locals "
585 "when called without a frame");
586 return NULL;
589 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
590 if (PyDict_SetItemString(globals, "__builtins__",
591 PyEval_GetBuiltins()) != 0)
592 return NULL;
595 if (PyCode_Check(cmd)) {
596 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
597 PyErr_SetString(PyExc_TypeError,
598 "code object passed to eval() may not contain free variables");
599 return NULL;
601 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
604 if (!PyString_Check(cmd) &&
605 !PyUnicode_Check(cmd)) {
606 PyErr_SetString(PyExc_TypeError,
607 "eval() arg 1 must be a string or code object");
608 return NULL;
610 cf.cf_flags = 0;
612 #ifdef Py_USING_UNICODE
613 if (PyUnicode_Check(cmd)) {
614 tmp = PyUnicode_AsUTF8String(cmd);
615 if (tmp == NULL)
616 return NULL;
617 cmd = tmp;
618 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
620 #endif
621 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
622 Py_XDECREF(tmp);
623 return NULL;
625 while (*str == ' ' || *str == '\t')
626 str++;
628 (void)PyEval_MergeCompilerFlags(&cf);
629 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
630 Py_XDECREF(tmp);
631 return result;
634 PyDoc_STRVAR(eval_doc,
635 "eval(source[, globals[, locals]]) -> value\n\
637 Evaluate the source in the context of globals and locals.\n\
638 The source may be a string representing a Python expression\n\
639 or a code object as returned by compile().\n\
640 The globals must be a dictionary and locals can be any mapping,\n\
641 defaulting to the current globals and locals.\n\
642 If only globals is given, locals defaults to it.\n");
645 static PyObject *
646 builtin_execfile(PyObject *self, PyObject *args)
648 char *filename;
649 PyObject *globals = Py_None, *locals = Py_None;
650 PyObject *res;
651 FILE* fp = NULL;
652 PyCompilerFlags cf;
653 int exists;
655 if (Py_Py3kWarningFlag &&
656 PyErr_Warn(PyExc_DeprecationWarning,
657 "execfile() not supported in 3.x") < 0)
658 return NULL;
660 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
661 &filename,
662 &PyDict_Type, &globals,
663 &locals))
664 return NULL;
665 if (locals != Py_None && !PyMapping_Check(locals)) {
666 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
667 return NULL;
669 if (globals == Py_None) {
670 globals = PyEval_GetGlobals();
671 if (locals == Py_None)
672 locals = PyEval_GetLocals();
674 else if (locals == Py_None)
675 locals = globals;
676 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
677 if (PyDict_SetItemString(globals, "__builtins__",
678 PyEval_GetBuiltins()) != 0)
679 return NULL;
682 exists = 0;
683 /* Test for existence or directory. */
684 #if defined(PLAN9)
686 Dir *d;
688 if ((d = dirstat(filename))!=nil) {
689 if(d->mode & DMDIR)
690 werrstr("is a directory");
691 else
692 exists = 1;
693 free(d);
696 #elif defined(RISCOS)
697 if (object_exists(filename)) {
698 if (isdir(filename))
699 errno = EISDIR;
700 else
701 exists = 1;
703 #else /* standard Posix */
705 struct stat s;
706 if (stat(filename, &s) == 0) {
707 if (S_ISDIR(s.st_mode))
708 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
709 errno = EOS2ERR;
710 # else
711 errno = EISDIR;
712 # endif
713 else
714 exists = 1;
717 #endif
719 if (exists) {
720 Py_BEGIN_ALLOW_THREADS
721 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
722 Py_END_ALLOW_THREADS
724 if (fp == NULL) {
725 exists = 0;
729 if (!exists) {
730 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
731 return NULL;
733 cf.cf_flags = 0;
734 if (PyEval_MergeCompilerFlags(&cf))
735 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
736 locals, 1, &cf);
737 else
738 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
739 locals, 1);
740 return res;
743 PyDoc_STRVAR(execfile_doc,
744 "execfile(filename[, globals[, locals]])\n\
746 Read and execute a Python script from a file.\n\
747 The globals and locals are dictionaries, defaulting to the current\n\
748 globals and locals. If only globals is given, locals defaults to it.");
751 static PyObject *
752 builtin_getattr(PyObject *self, PyObject *args)
754 PyObject *v, *result, *dflt = NULL;
755 PyObject *name;
757 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
758 return NULL;
759 #ifdef Py_USING_UNICODE
760 if (PyUnicode_Check(name)) {
761 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
762 if (name == NULL)
763 return NULL;
765 #endif
767 if (!PyString_Check(name)) {
768 PyErr_SetString(PyExc_TypeError,
769 "getattr(): attribute name must be string");
770 return NULL;
772 result = PyObject_GetAttr(v, name);
773 if (result == NULL && dflt != NULL &&
774 PyErr_ExceptionMatches(PyExc_AttributeError))
776 PyErr_Clear();
777 Py_INCREF(dflt);
778 result = dflt;
780 return result;
783 PyDoc_STRVAR(getattr_doc,
784 "getattr(object, name[, default]) -> value\n\
786 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
787 When a default argument is given, it is returned when the attribute doesn't\n\
788 exist; without it, an exception is raised in that case.");
791 static PyObject *
792 builtin_globals(PyObject *self)
794 PyObject *d;
796 d = PyEval_GetGlobals();
797 Py_XINCREF(d);
798 return d;
801 PyDoc_STRVAR(globals_doc,
802 "globals() -> dictionary\n\
804 Return the dictionary containing the current scope's global variables.");
807 static PyObject *
808 builtin_hasattr(PyObject *self, PyObject *args)
810 PyObject *v;
811 PyObject *name;
813 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
814 return NULL;
815 #ifdef Py_USING_UNICODE
816 if (PyUnicode_Check(name)) {
817 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
818 if (name == NULL)
819 return NULL;
821 #endif
823 if (!PyString_Check(name)) {
824 PyErr_SetString(PyExc_TypeError,
825 "hasattr(): attribute name must be string");
826 return NULL;
828 v = PyObject_GetAttr(v, name);
829 if (v == NULL) {
830 PyErr_Clear();
831 Py_INCREF(Py_False);
832 return Py_False;
834 Py_DECREF(v);
835 Py_INCREF(Py_True);
836 return Py_True;
839 PyDoc_STRVAR(hasattr_doc,
840 "hasattr(object, name) -> bool\n\
842 Return whether the object has an attribute with the given name.\n\
843 (This is done by calling getattr(object, name) and catching exceptions.)");
846 static PyObject *
847 builtin_id(PyObject *self, PyObject *v)
849 return PyLong_FromVoidPtr(v);
852 PyDoc_STRVAR(id_doc,
853 "id(object) -> integer\n\
855 Return the identity of an object. This is guaranteed to be unique among\n\
856 simultaneously existing objects. (Hint: it's the object's memory address.)");
859 static PyObject *
860 builtin_map(PyObject *self, PyObject *args)
862 typedef struct {
863 PyObject *it; /* the iterator object */
864 int saw_StopIteration; /* bool: did the iterator end? */
865 } sequence;
867 PyObject *func, *result;
868 sequence *seqs = NULL, *sqp;
869 Py_ssize_t n, len;
870 register int i, j;
872 n = PyTuple_Size(args);
873 if (n < 2) {
874 PyErr_SetString(PyExc_TypeError,
875 "map() requires at least two args");
876 return NULL;
879 func = PyTuple_GetItem(args, 0);
880 n--;
882 if (func == Py_None && n == 1) {
883 /* map(None, S) is the same as list(S). */
884 return PySequence_List(PyTuple_GetItem(args, 1));
887 /* Get space for sequence descriptors. Must NULL out the iterator
888 * pointers so that jumping to Fail_2 later doesn't see trash.
890 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
891 PyErr_NoMemory();
892 return NULL;
894 for (i = 0; i < n; ++i) {
895 seqs[i].it = (PyObject*)NULL;
896 seqs[i].saw_StopIteration = 0;
899 /* Do a first pass to obtain iterators for the arguments, and set len
900 * to the largest of their lengths.
902 len = 0;
903 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
904 PyObject *curseq;
905 Py_ssize_t curlen;
907 /* Get iterator. */
908 curseq = PyTuple_GetItem(args, i+1);
909 sqp->it = PyObject_GetIter(curseq);
910 if (sqp->it == NULL) {
911 static char errmsg[] =
912 "argument %d to map() must support iteration";
913 char errbuf[sizeof(errmsg) + 25];
914 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
915 PyErr_SetString(PyExc_TypeError, errbuf);
916 goto Fail_2;
919 /* Update len. */
920 curlen = _PyObject_LengthHint(curseq, 8);
921 if (curlen > len)
922 len = curlen;
925 /* Get space for the result list. */
926 if ((result = (PyObject *) PyList_New(len)) == NULL)
927 goto Fail_2;
929 /* Iterate over the sequences until all have stopped. */
930 for (i = 0; ; ++i) {
931 PyObject *alist, *item=NULL, *value;
932 int numactive = 0;
934 if (func == Py_None && n == 1)
935 alist = NULL;
936 else if ((alist = PyTuple_New(n)) == NULL)
937 goto Fail_1;
939 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
940 if (sqp->saw_StopIteration) {
941 Py_INCREF(Py_None);
942 item = Py_None;
944 else {
945 item = PyIter_Next(sqp->it);
946 if (item)
947 ++numactive;
948 else {
949 if (PyErr_Occurred()) {
950 Py_XDECREF(alist);
951 goto Fail_1;
953 Py_INCREF(Py_None);
954 item = Py_None;
955 sqp->saw_StopIteration = 1;
958 if (alist)
959 PyTuple_SET_ITEM(alist, j, item);
960 else
961 break;
964 if (!alist)
965 alist = item;
967 if (numactive == 0) {
968 Py_DECREF(alist);
969 break;
972 if (func == Py_None)
973 value = alist;
974 else {
975 value = PyEval_CallObject(func, alist);
976 Py_DECREF(alist);
977 if (value == NULL)
978 goto Fail_1;
980 if (i >= len) {
981 int status = PyList_Append(result, value);
982 Py_DECREF(value);
983 if (status < 0)
984 goto Fail_1;
986 else if (PyList_SetItem(result, i, value) < 0)
987 goto Fail_1;
990 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
991 goto Fail_1;
993 goto Succeed;
995 Fail_1:
996 Py_DECREF(result);
997 Fail_2:
998 result = NULL;
999 Succeed:
1000 assert(seqs);
1001 for (i = 0; i < n; ++i)
1002 Py_XDECREF(seqs[i].it);
1003 PyMem_DEL(seqs);
1004 return result;
1007 PyDoc_STRVAR(map_doc,
1008 "map(function, sequence[, sequence, ...]) -> list\n\
1010 Return a list of the results of applying the function to the items of\n\
1011 the argument sequence(s). If more than one sequence is given, the\n\
1012 function is called with an argument list consisting of the corresponding\n\
1013 item of each sequence, substituting None for missing values when not all\n\
1014 sequences have the same length. If the function is None, return a list of\n\
1015 the items of the sequence (or a list of tuples if more than one sequence).");
1018 static PyObject *
1019 builtin_setattr(PyObject *self, PyObject *args)
1021 PyObject *v;
1022 PyObject *name;
1023 PyObject *value;
1025 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1026 return NULL;
1027 if (PyObject_SetAttr(v, name, value) != 0)
1028 return NULL;
1029 Py_INCREF(Py_None);
1030 return Py_None;
1033 PyDoc_STRVAR(setattr_doc,
1034 "setattr(object, name, value)\n\
1036 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1037 ``x.y = v''.");
1040 static PyObject *
1041 builtin_delattr(PyObject *self, PyObject *args)
1043 PyObject *v;
1044 PyObject *name;
1046 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1047 return NULL;
1048 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1049 return NULL;
1050 Py_INCREF(Py_None);
1051 return Py_None;
1054 PyDoc_STRVAR(delattr_doc,
1055 "delattr(object, name)\n\
1057 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1058 ``del x.y''.");
1061 static PyObject *
1062 builtin_hash(PyObject *self, PyObject *v)
1064 long x;
1066 x = PyObject_Hash(v);
1067 if (x == -1)
1068 return NULL;
1069 return PyInt_FromLong(x);
1072 PyDoc_STRVAR(hash_doc,
1073 "hash(object) -> integer\n\
1075 Return a hash value for the object. Two objects with the same value have\n\
1076 the same hash value. The reverse is not necessarily true, but likely.");
1079 static PyObject *
1080 builtin_hex(PyObject *self, PyObject *v)
1082 PyNumberMethods *nb;
1083 PyObject *res;
1085 if ((nb = v->ob_type->tp_as_number) == NULL ||
1086 nb->nb_hex == NULL) {
1087 PyErr_SetString(PyExc_TypeError,
1088 "hex() argument can't be converted to hex");
1089 return NULL;
1091 res = (*nb->nb_hex)(v);
1092 if (res && !PyString_Check(res)) {
1093 PyErr_Format(PyExc_TypeError,
1094 "__hex__ returned non-string (type %.200s)",
1095 res->ob_type->tp_name);
1096 Py_DECREF(res);
1097 return NULL;
1099 return res;
1102 PyDoc_STRVAR(hex_doc,
1103 "hex(number) -> string\n\
1105 Return the hexadecimal representation of an integer or long integer.");
1108 static PyObject *builtin_raw_input(PyObject *, PyObject *);
1110 static PyObject *
1111 builtin_input(PyObject *self, PyObject *args)
1113 PyObject *line;
1114 char *str;
1115 PyObject *res;
1116 PyObject *globals, *locals;
1117 PyCompilerFlags cf;
1119 line = builtin_raw_input(self, args);
1120 if (line == NULL)
1121 return line;
1122 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1123 return NULL;
1124 while (*str == ' ' || *str == '\t')
1125 str++;
1126 globals = PyEval_GetGlobals();
1127 locals = PyEval_GetLocals();
1128 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1129 if (PyDict_SetItemString(globals, "__builtins__",
1130 PyEval_GetBuiltins()) != 0)
1131 return NULL;
1133 cf.cf_flags = 0;
1134 PyEval_MergeCompilerFlags(&cf);
1135 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1136 Py_DECREF(line);
1137 return res;
1140 PyDoc_STRVAR(input_doc,
1141 "input([prompt]) -> value\n\
1143 Equivalent to eval(raw_input(prompt)).");
1146 static PyObject *
1147 builtin_intern(PyObject *self, PyObject *args)
1149 PyObject *s;
1150 if (!PyArg_ParseTuple(args, "S:intern", &s))
1151 return NULL;
1152 if (!PyString_CheckExact(s)) {
1153 PyErr_SetString(PyExc_TypeError,
1154 "can't intern subclass of string");
1155 return NULL;
1157 Py_INCREF(s);
1158 PyString_InternInPlace(&s);
1159 return s;
1162 PyDoc_STRVAR(intern_doc,
1163 "intern(string) -> string\n\
1165 ``Intern'' the given string. This enters the string in the (global)\n\
1166 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1167 Return the string itself or the previously interned string object with the\n\
1168 same value.");
1171 static PyObject *
1172 builtin_iter(PyObject *self, PyObject *args)
1174 PyObject *v, *w = NULL;
1176 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1177 return NULL;
1178 if (w == NULL)
1179 return PyObject_GetIter(v);
1180 if (!PyCallable_Check(v)) {
1181 PyErr_SetString(PyExc_TypeError,
1182 "iter(v, w): v must be callable");
1183 return NULL;
1185 return PyCallIter_New(v, w);
1188 PyDoc_STRVAR(iter_doc,
1189 "iter(collection) -> iterator\n\
1190 iter(callable, sentinel) -> iterator\n\
1192 Get an iterator from an object. In the first form, the argument must\n\
1193 supply its own iterator, or be a sequence.\n\
1194 In the second form, the callable is called until it returns the sentinel.");
1197 static PyObject *
1198 builtin_len(PyObject *self, PyObject *v)
1200 Py_ssize_t res;
1202 res = PyObject_Size(v);
1203 if (res < 0 && PyErr_Occurred())
1204 return NULL;
1205 return PyInt_FromSsize_t(res);
1208 PyDoc_STRVAR(len_doc,
1209 "len(object) -> integer\n\
1211 Return the number of items of a sequence or mapping.");
1214 static PyObject *
1215 builtin_locals(PyObject *self)
1217 PyObject *d;
1219 d = PyEval_GetLocals();
1220 Py_XINCREF(d);
1221 return d;
1224 PyDoc_STRVAR(locals_doc,
1225 "locals() -> dictionary\n\
1227 Update and return a dictionary containing the current scope's local variables.");
1230 static PyObject *
1231 min_max(PyObject *args, PyObject *kwds, int op)
1233 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1234 const char *name = op == Py_LT ? "min" : "max";
1236 if (PyTuple_Size(args) > 1)
1237 v = args;
1238 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1239 return NULL;
1241 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1242 keyfunc = PyDict_GetItemString(kwds, "key");
1243 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1244 PyErr_Format(PyExc_TypeError,
1245 "%s() got an unexpected keyword argument", name);
1246 return NULL;
1250 it = PyObject_GetIter(v);
1251 if (it == NULL)
1252 return NULL;
1254 maxitem = NULL; /* the result */
1255 maxval = NULL; /* the value associated with the result */
1256 while (( item = PyIter_Next(it) )) {
1257 /* get the value from the key function */
1258 if (keyfunc != NULL) {
1259 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1260 if (val == NULL)
1261 goto Fail_it_item;
1263 /* no key function; the value is the item */
1264 else {
1265 val = item;
1266 Py_INCREF(val);
1269 /* maximum value and item are unset; set them */
1270 if (maxval == NULL) {
1271 maxitem = item;
1272 maxval = val;
1274 /* maximum value and item are set; update them as necessary */
1275 else {
1276 int cmp = PyObject_RichCompareBool(val, maxval, op);
1277 if (cmp < 0)
1278 goto Fail_it_item_and_val;
1279 else if (cmp > 0) {
1280 Py_DECREF(maxval);
1281 Py_DECREF(maxitem);
1282 maxval = val;
1283 maxitem = item;
1285 else {
1286 Py_DECREF(item);
1287 Py_DECREF(val);
1291 if (PyErr_Occurred())
1292 goto Fail_it;
1293 if (maxval == NULL) {
1294 PyErr_Format(PyExc_ValueError,
1295 "%s() arg is an empty sequence", name);
1296 assert(maxitem == NULL);
1298 else
1299 Py_DECREF(maxval);
1300 Py_DECREF(it);
1301 return maxitem;
1303 Fail_it_item_and_val:
1304 Py_DECREF(val);
1305 Fail_it_item:
1306 Py_DECREF(item);
1307 Fail_it:
1308 Py_XDECREF(maxval);
1309 Py_XDECREF(maxitem);
1310 Py_DECREF(it);
1311 return NULL;
1314 static PyObject *
1315 builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1317 return min_max(args, kwds, Py_LT);
1320 PyDoc_STRVAR(min_doc,
1321 "min(iterable[, key=func]) -> value\n\
1322 min(a, b, c, ...[, key=func]) -> value\n\
1324 With a single iterable argument, return its smallest item.\n\
1325 With two or more arguments, return the smallest argument.");
1328 static PyObject *
1329 builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1331 return min_max(args, kwds, Py_GT);
1334 PyDoc_STRVAR(max_doc,
1335 "max(iterable[, key=func]) -> value\n\
1336 max(a, b, c, ...[, key=func]) -> value\n\
1338 With a single iterable argument, return its largest item.\n\
1339 With two or more arguments, return the largest argument.");
1342 static PyObject *
1343 builtin_oct(PyObject *self, PyObject *v)
1345 PyNumberMethods *nb;
1346 PyObject *res;
1348 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1349 nb->nb_oct == NULL) {
1350 PyErr_SetString(PyExc_TypeError,
1351 "oct() argument can't be converted to oct");
1352 return NULL;
1354 res = (*nb->nb_oct)(v);
1355 if (res && !PyString_Check(res)) {
1356 PyErr_Format(PyExc_TypeError,
1357 "__oct__ returned non-string (type %.200s)",
1358 res->ob_type->tp_name);
1359 Py_DECREF(res);
1360 return NULL;
1362 return res;
1365 PyDoc_STRVAR(oct_doc,
1366 "oct(number) -> string\n\
1368 Return the octal representation of an integer or long integer.");
1371 static PyObject *
1372 builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1374 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
1377 PyDoc_STRVAR(open_doc,
1378 "open(name[, mode[, buffering]]) -> file object\n\
1380 Open a file using the file() type, returns a file object. This is the\n\
1381 preferred way to open a file.");
1384 static PyObject *
1385 builtin_ord(PyObject *self, PyObject* obj)
1387 long ord;
1388 Py_ssize_t size;
1390 if (PyString_Check(obj)) {
1391 size = PyString_GET_SIZE(obj);
1392 if (size == 1) {
1393 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1394 return PyInt_FromLong(ord);
1396 #ifdef Py_USING_UNICODE
1397 } else if (PyUnicode_Check(obj)) {
1398 size = PyUnicode_GET_SIZE(obj);
1399 if (size == 1) {
1400 ord = (long)*PyUnicode_AS_UNICODE(obj);
1401 return PyInt_FromLong(ord);
1403 #endif
1404 } else {
1405 PyErr_Format(PyExc_TypeError,
1406 "ord() expected string of length 1, but " \
1407 "%.200s found", obj->ob_type->tp_name);
1408 return NULL;
1411 PyErr_Format(PyExc_TypeError,
1412 "ord() expected a character, "
1413 "but string of length %zd found",
1414 size);
1415 return NULL;
1418 PyDoc_STRVAR(ord_doc,
1419 "ord(c) -> integer\n\
1421 Return the integer ordinal of a one-character string.");
1424 static PyObject *
1425 builtin_pow(PyObject *self, PyObject *args)
1427 PyObject *v, *w, *z = Py_None;
1429 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1430 return NULL;
1431 return PyNumber_Power(v, w, z);
1434 PyDoc_STRVAR(pow_doc,
1435 "pow(x, y[, z]) -> number\n\
1437 With two arguments, equivalent to x**y. With three arguments,\n\
1438 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1442 /* Return number of items in range (lo, hi, step), when arguments are
1443 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1444 * & only if the true value is too large to fit in a signed long.
1445 * Arguments MUST return 1 with either PyInt_Check() or
1446 * PyLong_Check(). Return -1 when there is an error.
1448 static long
1449 get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1451 /* -------------------------------------------------------------
1452 Algorithm is equal to that of get_len_of_range(), but it operates
1453 on PyObjects (which are assumed to be PyLong or PyInt objects).
1454 ---------------------------------------------------------------*/
1455 long n;
1456 PyObject *diff = NULL;
1457 PyObject *one = NULL;
1458 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1459 /* holds sub-expression evaluations */
1461 /* if (lo >= hi), return length of 0. */
1462 if (PyObject_Compare(lo, hi) >= 0)
1463 return 0;
1465 if ((one = PyLong_FromLong(1L)) == NULL)
1466 goto Fail;
1468 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1469 goto Fail;
1471 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1472 goto Fail;
1474 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1475 goto Fail;
1477 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1478 goto Fail;
1480 n = PyLong_AsLong(tmp3);
1481 if (PyErr_Occurred()) { /* Check for Overflow */
1482 PyErr_Clear();
1483 goto Fail;
1486 Py_DECREF(tmp3);
1487 Py_DECREF(tmp2);
1488 Py_DECREF(diff);
1489 Py_DECREF(tmp1);
1490 Py_DECREF(one);
1491 return n;
1493 Fail:
1494 Py_XDECREF(tmp3);
1495 Py_XDECREF(tmp2);
1496 Py_XDECREF(diff);
1497 Py_XDECREF(tmp1);
1498 Py_XDECREF(one);
1499 return -1;
1502 /* An extension of builtin_range() that handles the case when PyLong
1503 * arguments are given. */
1504 static PyObject *
1505 handle_range_longs(PyObject *self, PyObject *args)
1507 PyObject *ilow;
1508 PyObject *ihigh = NULL;
1509 PyObject *istep = NULL;
1511 PyObject *curnum = NULL;
1512 PyObject *v = NULL;
1513 long bign;
1514 int i, n;
1515 int cmp_result;
1517 PyObject *zero = PyLong_FromLong(0);
1519 if (zero == NULL)
1520 return NULL;
1522 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1523 Py_DECREF(zero);
1524 return NULL;
1527 /* Figure out which way we were called, supply defaults, and be
1528 * sure to incref everything so that the decrefs at the end
1529 * are correct.
1531 assert(ilow != NULL);
1532 if (ihigh == NULL) {
1533 /* only 1 arg -- it's the upper limit */
1534 ihigh = ilow;
1535 ilow = NULL;
1537 assert(ihigh != NULL);
1538 Py_INCREF(ihigh);
1540 /* ihigh correct now; do ilow */
1541 if (ilow == NULL)
1542 ilow = zero;
1543 Py_INCREF(ilow);
1545 /* ilow and ihigh correct now; do istep */
1546 if (istep == NULL) {
1547 istep = PyLong_FromLong(1L);
1548 if (istep == NULL)
1549 goto Fail;
1551 else {
1552 Py_INCREF(istep);
1555 if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
1556 PyErr_Format(PyExc_TypeError,
1557 "range() integer start argument expected, got %s.",
1558 ilow->ob_type->tp_name);
1559 goto Fail;
1562 if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
1563 PyErr_Format(PyExc_TypeError,
1564 "range() integer end argument expected, got %s.",
1565 ihigh->ob_type->tp_name);
1566 goto Fail;
1569 if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
1570 PyErr_Format(PyExc_TypeError,
1571 "range() integer step argument expected, got %s.",
1572 istep->ob_type->tp_name);
1573 goto Fail;
1576 if (PyObject_Cmp(istep, zero, &cmp_result) == -1)
1577 goto Fail;
1578 if (cmp_result == 0) {
1579 PyErr_SetString(PyExc_ValueError,
1580 "range() step argument must not be zero");
1581 goto Fail;
1584 if (cmp_result > 0)
1585 bign = get_len_of_range_longs(ilow, ihigh, istep);
1586 else {
1587 PyObject *neg_istep = PyNumber_Negative(istep);
1588 if (neg_istep == NULL)
1589 goto Fail;
1590 bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
1591 Py_DECREF(neg_istep);
1594 n = (int)bign;
1595 if (bign < 0 || (long)n != bign) {
1596 PyErr_SetString(PyExc_OverflowError,
1597 "range() result has too many items");
1598 goto Fail;
1601 v = PyList_New(n);
1602 if (v == NULL)
1603 goto Fail;
1605 curnum = ilow;
1606 Py_INCREF(curnum);
1608 for (i = 0; i < n; i++) {
1609 PyObject *w = PyNumber_Long(curnum);
1610 PyObject *tmp_num;
1611 if (w == NULL)
1612 goto Fail;
1614 PyList_SET_ITEM(v, i, w);
1616 tmp_num = PyNumber_Add(curnum, istep);
1617 if (tmp_num == NULL)
1618 goto Fail;
1620 Py_DECREF(curnum);
1621 curnum = tmp_num;
1623 Py_DECREF(ilow);
1624 Py_DECREF(ihigh);
1625 Py_DECREF(istep);
1626 Py_DECREF(zero);
1627 Py_DECREF(curnum);
1628 return v;
1630 Fail:
1631 Py_DECREF(ilow);
1632 Py_DECREF(ihigh);
1633 Py_XDECREF(istep);
1634 Py_DECREF(zero);
1635 Py_XDECREF(curnum);
1636 Py_XDECREF(v);
1637 return NULL;
1640 /* Return number of items in range/xrange (lo, hi, step). step > 0
1641 * required. Return a value < 0 if & only if the true value is too
1642 * large to fit in a signed long.
1644 static long
1645 get_len_of_range(long lo, long hi, long step)
1647 /* -------------------------------------------------------------
1648 If lo >= hi, the range is empty.
1649 Else if n values are in the range, the last one is
1650 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1651 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1652 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1653 the RHS is non-negative and so truncation is the same as the
1654 floor. Letting M be the largest positive long, the worst case
1655 for the RHS numerator is hi=M, lo=-M-1, and then
1656 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1657 precision to compute the RHS exactly.
1658 ---------------------------------------------------------------*/
1659 long n = 0;
1660 if (lo < hi) {
1661 unsigned long uhi = (unsigned long)hi;
1662 unsigned long ulo = (unsigned long)lo;
1663 unsigned long diff = uhi - ulo - 1;
1664 n = (long)(diff / (unsigned long)step + 1);
1666 return n;
1669 static PyObject *
1670 builtin_range(PyObject *self, PyObject *args)
1672 long ilow = 0, ihigh = 0, istep = 1;
1673 long bign;
1674 int i, n;
1676 PyObject *v;
1678 if (PyTuple_Size(args) <= 1) {
1679 if (!PyArg_ParseTuple(args,
1680 "l;range() requires 1-3 int arguments",
1681 &ihigh)) {
1682 PyErr_Clear();
1683 return handle_range_longs(self, args);
1686 else {
1687 if (!PyArg_ParseTuple(args,
1688 "ll|l;range() requires 1-3 int arguments",
1689 &ilow, &ihigh, &istep)) {
1690 PyErr_Clear();
1691 return handle_range_longs(self, args);
1694 if (istep == 0) {
1695 PyErr_SetString(PyExc_ValueError,
1696 "range() step argument must not be zero");
1697 return NULL;
1699 if (istep > 0)
1700 bign = get_len_of_range(ilow, ihigh, istep);
1701 else
1702 bign = get_len_of_range(ihigh, ilow, -istep);
1703 n = (int)bign;
1704 if (bign < 0 || (long)n != bign) {
1705 PyErr_SetString(PyExc_OverflowError,
1706 "range() result has too many items");
1707 return NULL;
1709 v = PyList_New(n);
1710 if (v == NULL)
1711 return NULL;
1712 for (i = 0; i < n; i++) {
1713 PyObject *w = PyInt_FromLong(ilow);
1714 if (w == NULL) {
1715 Py_DECREF(v);
1716 return NULL;
1718 PyList_SET_ITEM(v, i, w);
1719 ilow += istep;
1721 return v;
1724 PyDoc_STRVAR(range_doc,
1725 "range([start,] stop[, step]) -> list of integers\n\
1727 Return a list containing an arithmetic progression of integers.\n\
1728 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1729 When step is given, it specifies the increment (or decrement).\n\
1730 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1731 These are exactly the valid indices for a list of 4 elements.");
1734 static PyObject *
1735 builtin_raw_input(PyObject *self, PyObject *args)
1737 PyObject *v = NULL;
1738 PyObject *fin = PySys_GetObject("stdin");
1739 PyObject *fout = PySys_GetObject("stdout");
1741 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
1742 return NULL;
1744 if (fin == NULL) {
1745 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
1746 return NULL;
1748 if (fout == NULL) {
1749 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
1750 return NULL;
1752 if (PyFile_SoftSpace(fout, 0)) {
1753 if (PyFile_WriteString(" ", fout) != 0)
1754 return NULL;
1756 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
1757 && isatty(fileno(PyFile_AsFile(fin)))
1758 && isatty(fileno(PyFile_AsFile(fout)))) {
1759 PyObject *po;
1760 char *prompt;
1761 char *s;
1762 PyObject *result;
1763 if (v != NULL) {
1764 po = PyObject_Str(v);
1765 if (po == NULL)
1766 return NULL;
1767 prompt = PyString_AsString(po);
1768 if (prompt == NULL)
1769 return NULL;
1771 else {
1772 po = NULL;
1773 prompt = "";
1775 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
1776 prompt);
1777 Py_XDECREF(po);
1778 if (s == NULL) {
1779 if (!PyErr_Occurred())
1780 PyErr_SetNone(PyExc_KeyboardInterrupt);
1781 return NULL;
1783 if (*s == '\0') {
1784 PyErr_SetNone(PyExc_EOFError);
1785 result = NULL;
1787 else { /* strip trailing '\n' */
1788 size_t len = strlen(s);
1789 if (len > PY_SSIZE_T_MAX) {
1790 PyErr_SetString(PyExc_OverflowError,
1791 "[raw_]input: input too long");
1792 result = NULL;
1794 else {
1795 result = PyString_FromStringAndSize(s, len-1);
1798 PyMem_FREE(s);
1799 return result;
1801 if (v != NULL) {
1802 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
1803 return NULL;
1805 return PyFile_GetLine(fin, -1);
1808 PyDoc_STRVAR(raw_input_doc,
1809 "raw_input([prompt]) -> string\n\
1811 Read a string from standard input. The trailing newline is stripped.\n\
1812 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1813 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1814 is printed without a trailing newline before reading.");
1817 static PyObject *
1818 builtin_reduce(PyObject *self, PyObject *args)
1820 PyObject *seq, *func, *result = NULL, *it;
1822 if (Py_Py3kWarningFlag &&
1823 PyErr_Warn(PyExc_DeprecationWarning,
1824 "reduce() not supported in 3.x") < 0)
1825 return NULL;
1827 if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
1828 return NULL;
1829 if (result != NULL)
1830 Py_INCREF(result);
1832 it = PyObject_GetIter(seq);
1833 if (it == NULL) {
1834 PyErr_SetString(PyExc_TypeError,
1835 "reduce() arg 2 must support iteration");
1836 Py_XDECREF(result);
1837 return NULL;
1840 if ((args = PyTuple_New(2)) == NULL)
1841 goto Fail;
1843 for (;;) {
1844 PyObject *op2;
1846 if (args->ob_refcnt > 1) {
1847 Py_DECREF(args);
1848 if ((args = PyTuple_New(2)) == NULL)
1849 goto Fail;
1852 op2 = PyIter_Next(it);
1853 if (op2 == NULL) {
1854 if (PyErr_Occurred())
1855 goto Fail;
1856 break;
1859 if (result == NULL)
1860 result = op2;
1861 else {
1862 PyTuple_SetItem(args, 0, result);
1863 PyTuple_SetItem(args, 1, op2);
1864 if ((result = PyEval_CallObject(func, args)) == NULL)
1865 goto Fail;
1869 Py_DECREF(args);
1871 if (result == NULL)
1872 PyErr_SetString(PyExc_TypeError,
1873 "reduce() of empty sequence with no initial value");
1875 Py_DECREF(it);
1876 return result;
1878 Fail:
1879 Py_XDECREF(args);
1880 Py_XDECREF(result);
1881 Py_DECREF(it);
1882 return NULL;
1885 PyDoc_STRVAR(reduce_doc,
1886 "reduce(function, sequence[, initial]) -> value\n\
1888 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1889 from left to right, so as to reduce the sequence to a single value.\n\
1890 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1891 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1892 of the sequence in the calculation, and serves as a default when the\n\
1893 sequence is empty.");
1896 static PyObject *
1897 builtin_reload(PyObject *self, PyObject *v)
1899 if (Py_Py3kWarningFlag &&
1900 PyErr_Warn(PyExc_DeprecationWarning,
1901 "reload() not supported in 3.x") < 0)
1902 return NULL;
1904 return PyImport_ReloadModule(v);
1907 PyDoc_STRVAR(reload_doc,
1908 "reload(module) -> module\n\
1910 Reload the module. The module must have been successfully imported before.");
1913 static PyObject *
1914 builtin_repr(PyObject *self, PyObject *v)
1916 return PyObject_Repr(v);
1919 PyDoc_STRVAR(repr_doc,
1920 "repr(object) -> string\n\
1922 Return the canonical string representation of the object.\n\
1923 For most object types, eval(repr(object)) == object.");
1926 static PyObject *
1927 builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
1929 double number;
1930 double f;
1931 int ndigits = 0;
1932 int i;
1933 static char *kwlist[] = {"number", "ndigits", 0};
1935 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|i:round",
1936 kwlist, &number, &ndigits))
1937 return NULL;
1938 f = 1.0;
1939 i = abs(ndigits);
1940 while (--i >= 0)
1941 f = f*10.0;
1942 if (ndigits < 0)
1943 number /= f;
1944 else
1945 number *= f;
1946 if (number >= 0.0)
1947 number = floor(number + 0.5);
1948 else
1949 number = ceil(number - 0.5);
1950 if (ndigits < 0)
1951 number *= f;
1952 else
1953 number /= f;
1954 return PyFloat_FromDouble(number);
1957 PyDoc_STRVAR(round_doc,
1958 "round(number[, ndigits]) -> floating point number\n\
1960 Round a number to a given precision in decimal digits (default 0 digits).\n\
1961 This always returns a floating point number. Precision may be negative.");
1963 static PyObject *
1964 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1966 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1967 PyObject *callable;
1968 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
1969 int reverse;
1971 /* args 1-4 should match listsort in Objects/listobject.c */
1972 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1973 kwlist, &seq, &compare, &keyfunc, &reverse))
1974 return NULL;
1976 newlist = PySequence_List(seq);
1977 if (newlist == NULL)
1978 return NULL;
1980 callable = PyObject_GetAttrString(newlist, "sort");
1981 if (callable == NULL) {
1982 Py_DECREF(newlist);
1983 return NULL;
1986 newargs = PyTuple_GetSlice(args, 1, 4);
1987 if (newargs == NULL) {
1988 Py_DECREF(newlist);
1989 Py_DECREF(callable);
1990 return NULL;
1993 v = PyObject_Call(callable, newargs, kwds);
1994 Py_DECREF(newargs);
1995 Py_DECREF(callable);
1996 if (v == NULL) {
1997 Py_DECREF(newlist);
1998 return NULL;
2000 Py_DECREF(v);
2001 return newlist;
2004 PyDoc_STRVAR(sorted_doc,
2005 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2007 static PyObject *
2008 builtin_vars(PyObject *self, PyObject *args)
2010 PyObject *v = NULL;
2011 PyObject *d;
2013 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2014 return NULL;
2015 if (v == NULL) {
2016 d = PyEval_GetLocals();
2017 if (d == NULL) {
2018 if (!PyErr_Occurred())
2019 PyErr_SetString(PyExc_SystemError,
2020 "vars(): no locals!?");
2022 else
2023 Py_INCREF(d);
2025 else {
2026 d = PyObject_GetAttrString(v, "__dict__");
2027 if (d == NULL) {
2028 PyErr_SetString(PyExc_TypeError,
2029 "vars() argument must have __dict__ attribute");
2030 return NULL;
2033 return d;
2036 PyDoc_STRVAR(vars_doc,
2037 "vars([object]) -> dictionary\n\
2039 Without arguments, equivalent to locals().\n\
2040 With an argument, equivalent to object.__dict__.");
2042 static PyObject *
2043 builtin_trunc(PyObject *self, PyObject *number)
2045 /* XXX: The py3k branch gets better errors for this by using
2046 _PyType_Lookup(), but since float's mro isn't set in py2.6,
2047 we just use PyObject_CallMethod here. */
2048 return PyObject_CallMethod(number, "__trunc__", "");
2051 PyDoc_STRVAR(trunc_doc,
2052 "trunc(Real) -> Integral\n\
2054 returns the integral closest to x between 0 and x.");
2057 static PyObject*
2058 builtin_sum(PyObject *self, PyObject *args)
2060 PyObject *seq;
2061 PyObject *result = NULL;
2062 PyObject *temp, *item, *iter;
2064 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2065 return NULL;
2067 iter = PyObject_GetIter(seq);
2068 if (iter == NULL)
2069 return NULL;
2071 if (result == NULL) {
2072 result = PyInt_FromLong(0);
2073 if (result == NULL) {
2074 Py_DECREF(iter);
2075 return NULL;
2077 } else {
2078 /* reject string values for 'start' parameter */
2079 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2080 PyErr_SetString(PyExc_TypeError,
2081 "sum() can't sum strings [use ''.join(seq) instead]");
2082 Py_DECREF(iter);
2083 return NULL;
2085 Py_INCREF(result);
2088 #ifndef SLOW_SUM
2089 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2090 Assumes all inputs are the same type. If the assumption fails, default
2091 to the more general routine.
2093 if (PyInt_CheckExact(result)) {
2094 long i_result = PyInt_AS_LONG(result);
2095 Py_DECREF(result);
2096 result = NULL;
2097 while(result == NULL) {
2098 item = PyIter_Next(iter);
2099 if (item == NULL) {
2100 Py_DECREF(iter);
2101 if (PyErr_Occurred())
2102 return NULL;
2103 return PyInt_FromLong(i_result);
2105 if (PyInt_CheckExact(item)) {
2106 long b = PyInt_AS_LONG(item);
2107 long x = i_result + b;
2108 if ((x^i_result) >= 0 || (x^b) >= 0) {
2109 i_result = x;
2110 Py_DECREF(item);
2111 continue;
2114 /* Either overflowed or is not an int. Restore real objects and process normally */
2115 result = PyInt_FromLong(i_result);
2116 temp = PyNumber_Add(result, item);
2117 Py_DECREF(result);
2118 Py_DECREF(item);
2119 result = temp;
2120 if (result == NULL) {
2121 Py_DECREF(iter);
2122 return NULL;
2127 if (PyFloat_CheckExact(result)) {
2128 double f_result = PyFloat_AS_DOUBLE(result);
2129 Py_DECREF(result);
2130 result = NULL;
2131 while(result == NULL) {
2132 item = PyIter_Next(iter);
2133 if (item == NULL) {
2134 Py_DECREF(iter);
2135 if (PyErr_Occurred())
2136 return NULL;
2137 return PyFloat_FromDouble(f_result);
2139 if (PyFloat_CheckExact(item)) {
2140 PyFPE_START_PROTECT("add", return 0)
2141 f_result += PyFloat_AS_DOUBLE(item);
2142 PyFPE_END_PROTECT(f_result)
2143 Py_DECREF(item);
2144 continue;
2146 if (PyInt_CheckExact(item)) {
2147 PyFPE_START_PROTECT("add", return 0)
2148 f_result += (double)PyInt_AS_LONG(item);
2149 PyFPE_END_PROTECT(f_result)
2150 Py_DECREF(item);
2151 continue;
2153 result = PyFloat_FromDouble(f_result);
2154 temp = PyNumber_Add(result, item);
2155 Py_DECREF(result);
2156 Py_DECREF(item);
2157 result = temp;
2158 if (result == NULL) {
2159 Py_DECREF(iter);
2160 return NULL;
2164 #endif
2166 for(;;) {
2167 item = PyIter_Next(iter);
2168 if (item == NULL) {
2169 /* error, or end-of-sequence */
2170 if (PyErr_Occurred()) {
2171 Py_DECREF(result);
2172 result = NULL;
2174 break;
2176 temp = PyNumber_Add(result, item);
2177 Py_DECREF(result);
2178 Py_DECREF(item);
2179 result = temp;
2180 if (result == NULL)
2181 break;
2183 Py_DECREF(iter);
2184 return result;
2187 PyDoc_STRVAR(sum_doc,
2188 "sum(sequence[, start]) -> value\n\
2190 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2191 of parameter 'start' (which defaults to 0). When the sequence is\n\
2192 empty, returns start.");
2195 static PyObject *
2196 builtin_isinstance(PyObject *self, PyObject *args)
2198 PyObject *inst;
2199 PyObject *cls;
2200 int retval;
2202 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2203 return NULL;
2205 retval = PyObject_IsInstance(inst, cls);
2206 if (retval < 0)
2207 return NULL;
2208 return PyBool_FromLong(retval);
2211 PyDoc_STRVAR(isinstance_doc,
2212 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2214 Return whether an object is an instance of a class or of a subclass thereof.\n\
2215 With a type as second argument, return whether that is the object's type.\n\
2216 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2217 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2220 static PyObject *
2221 builtin_issubclass(PyObject *self, PyObject *args)
2223 PyObject *derived;
2224 PyObject *cls;
2225 int retval;
2227 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2228 return NULL;
2230 retval = PyObject_IsSubclass(derived, cls);
2231 if (retval < 0)
2232 return NULL;
2233 return PyBool_FromLong(retval);
2236 PyDoc_STRVAR(issubclass_doc,
2237 "issubclass(C, B) -> bool\n\
2239 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2240 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2241 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2244 static PyObject*
2245 builtin_zip(PyObject *self, PyObject *args)
2247 PyObject *ret;
2248 const Py_ssize_t itemsize = PySequence_Length(args);
2249 Py_ssize_t i;
2250 PyObject *itlist; /* tuple of iterators */
2251 Py_ssize_t len; /* guess at result length */
2253 if (itemsize == 0)
2254 return PyList_New(0);
2256 /* args must be a tuple */
2257 assert(PyTuple_Check(args));
2259 /* Guess at result length: the shortest of the input lengths.
2260 If some argument refuses to say, we refuse to guess too, lest
2261 an argument like xrange(sys.maxint) lead us astray.*/
2262 len = -1; /* unknown */
2263 for (i = 0; i < itemsize; ++i) {
2264 PyObject *item = PyTuple_GET_ITEM(args, i);
2265 Py_ssize_t thislen = _PyObject_LengthHint(item, -1);
2266 if (thislen < 0) {
2267 len = -1;
2268 break;
2270 else if (len < 0 || thislen < len)
2271 len = thislen;
2274 /* allocate result list */
2275 if (len < 0)
2276 len = 10; /* arbitrary */
2277 if ((ret = PyList_New(len)) == NULL)
2278 return NULL;
2280 /* obtain iterators */
2281 itlist = PyTuple_New(itemsize);
2282 if (itlist == NULL)
2283 goto Fail_ret;
2284 for (i = 0; i < itemsize; ++i) {
2285 PyObject *item = PyTuple_GET_ITEM(args, i);
2286 PyObject *it = PyObject_GetIter(item);
2287 if (it == NULL) {
2288 if (PyErr_ExceptionMatches(PyExc_TypeError))
2289 PyErr_Format(PyExc_TypeError,
2290 "zip argument #%zd must support iteration",
2291 i+1);
2292 goto Fail_ret_itlist;
2294 PyTuple_SET_ITEM(itlist, i, it);
2297 /* build result into ret list */
2298 for (i = 0; ; ++i) {
2299 int j;
2300 PyObject *next = PyTuple_New(itemsize);
2301 if (!next)
2302 goto Fail_ret_itlist;
2304 for (j = 0; j < itemsize; j++) {
2305 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2306 PyObject *item = PyIter_Next(it);
2307 if (!item) {
2308 if (PyErr_Occurred()) {
2309 Py_DECREF(ret);
2310 ret = NULL;
2312 Py_DECREF(next);
2313 Py_DECREF(itlist);
2314 goto Done;
2316 PyTuple_SET_ITEM(next, j, item);
2319 if (i < len)
2320 PyList_SET_ITEM(ret, i, next);
2321 else {
2322 int status = PyList_Append(ret, next);
2323 Py_DECREF(next);
2324 ++len;
2325 if (status < 0)
2326 goto Fail_ret_itlist;
2330 Done:
2331 if (ret != NULL && i < len) {
2332 /* The list is too big. */
2333 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2334 return NULL;
2336 return ret;
2338 Fail_ret_itlist:
2339 Py_DECREF(itlist);
2340 Fail_ret:
2341 Py_DECREF(ret);
2342 return NULL;
2346 PyDoc_STRVAR(zip_doc,
2347 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2349 Return a list of tuples, where each tuple contains the i-th element\n\
2350 from each of the argument sequences. The returned list is truncated\n\
2351 in length to the length of the shortest argument sequence.");
2354 static PyMethodDef builtin_methods[] = {
2355 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2356 {"abs", builtin_abs, METH_O, abs_doc},
2357 {"all", builtin_all, METH_O, all_doc},
2358 {"any", builtin_any, METH_O, any_doc},
2359 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2360 {"callable", builtin_callable, METH_O, callable_doc},
2361 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2362 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2363 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2364 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2365 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2366 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2367 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2368 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2369 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2370 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2371 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2372 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2373 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2374 {"hash", builtin_hash, METH_O, hash_doc},
2375 {"hex", builtin_hex, METH_O, hex_doc},
2376 {"id", builtin_id, METH_O, id_doc},
2377 {"input", builtin_input, METH_VARARGS, input_doc},
2378 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2379 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2380 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2381 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2382 {"len", builtin_len, METH_O, len_doc},
2383 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2384 {"map", builtin_map, METH_VARARGS, map_doc},
2385 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2386 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2387 {"oct", builtin_oct, METH_O, oct_doc},
2388 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2389 {"ord", builtin_ord, METH_O, ord_doc},
2390 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2391 {"range", builtin_range, METH_VARARGS, range_doc},
2392 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2393 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2394 {"reload", builtin_reload, METH_O, reload_doc},
2395 {"repr", builtin_repr, METH_O, repr_doc},
2396 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2397 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2398 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2399 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2400 #ifdef Py_USING_UNICODE
2401 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
2402 #endif
2403 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2404 {"trunc", builtin_trunc, METH_O, trunc_doc},
2405 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2406 {NULL, NULL},
2409 PyDoc_STRVAR(builtin_doc,
2410 "Built-in functions, exceptions, and other objects.\n\
2412 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2414 PyObject *
2415 _PyBuiltin_Init(void)
2417 PyObject *mod, *dict, *debug;
2418 mod = Py_InitModule4("__builtin__", builtin_methods,
2419 builtin_doc, (PyObject *)NULL,
2420 PYTHON_API_VERSION);
2421 if (mod == NULL)
2422 return NULL;
2423 dict = PyModule_GetDict(mod);
2425 #ifdef Py_TRACE_REFS
2426 /* __builtin__ exposes a number of statically allocated objects
2427 * that, before this code was added in 2.3, never showed up in
2428 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2429 * result, programs leaking references to None and False (etc)
2430 * couldn't be diagnosed by examining sys.getobjects(0).
2432 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2433 #else
2434 #define ADD_TO_ALL(OBJECT) (void)0
2435 #endif
2437 #define SETBUILTIN(NAME, OBJECT) \
2438 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2439 return NULL; \
2440 ADD_TO_ALL(OBJECT)
2442 SETBUILTIN("None", Py_None);
2443 SETBUILTIN("Ellipsis", Py_Ellipsis);
2444 SETBUILTIN("NotImplemented", Py_NotImplemented);
2445 SETBUILTIN("False", Py_False);
2446 SETBUILTIN("True", Py_True);
2447 SETBUILTIN("basestring", &PyBaseString_Type);
2448 SETBUILTIN("bool", &PyBool_Type);
2449 SETBUILTIN("buffer", &PyBuffer_Type);
2450 SETBUILTIN("classmethod", &PyClassMethod_Type);
2451 #ifndef WITHOUT_COMPLEX
2452 SETBUILTIN("complex", &PyComplex_Type);
2453 #endif
2454 SETBUILTIN("dict", &PyDict_Type);
2455 SETBUILTIN("enumerate", &PyEnum_Type);
2456 SETBUILTIN("file", &PyFile_Type);
2457 SETBUILTIN("float", &PyFloat_Type);
2458 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2459 SETBUILTIN("property", &PyProperty_Type);
2460 SETBUILTIN("int", &PyInt_Type);
2461 SETBUILTIN("list", &PyList_Type);
2462 SETBUILTIN("long", &PyLong_Type);
2463 SETBUILTIN("object", &PyBaseObject_Type);
2464 SETBUILTIN("reversed", &PyReversed_Type);
2465 SETBUILTIN("set", &PySet_Type);
2466 SETBUILTIN("slice", &PySlice_Type);
2467 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2468 SETBUILTIN("str", &PyString_Type);
2469 SETBUILTIN("super", &PySuper_Type);
2470 SETBUILTIN("tuple", &PyTuple_Type);
2471 SETBUILTIN("type", &PyType_Type);
2472 SETBUILTIN("xrange", &PyRange_Type);
2473 #ifdef Py_USING_UNICODE
2474 SETBUILTIN("unicode", &PyUnicode_Type);
2475 #endif
2476 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2477 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2478 Py_XDECREF(debug);
2479 return NULL;
2481 Py_XDECREF(debug);
2483 return mod;
2484 #undef ADD_TO_ALL
2485 #undef SETBUILTIN
2488 /* Helper for filter(): filter a tuple through a function */
2490 static PyObject *
2491 filtertuple(PyObject *func, PyObject *tuple)
2493 PyObject *result;
2494 Py_ssize_t i, j;
2495 Py_ssize_t len = PyTuple_Size(tuple);
2497 if (len == 0) {
2498 if (PyTuple_CheckExact(tuple))
2499 Py_INCREF(tuple);
2500 else
2501 tuple = PyTuple_New(0);
2502 return tuple;
2505 if ((result = PyTuple_New(len)) == NULL)
2506 return NULL;
2508 for (i = j = 0; i < len; ++i) {
2509 PyObject *item, *good;
2510 int ok;
2512 if (tuple->ob_type->tp_as_sequence &&
2513 tuple->ob_type->tp_as_sequence->sq_item) {
2514 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2515 if (item == NULL)
2516 goto Fail_1;
2517 } else {
2518 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2519 goto Fail_1;
2521 if (func == Py_None) {
2522 Py_INCREF(item);
2523 good = item;
2525 else {
2526 PyObject *arg = PyTuple_Pack(1, item);
2527 if (arg == NULL) {
2528 Py_DECREF(item);
2529 goto Fail_1;
2531 good = PyEval_CallObject(func, arg);
2532 Py_DECREF(arg);
2533 if (good == NULL) {
2534 Py_DECREF(item);
2535 goto Fail_1;
2538 ok = PyObject_IsTrue(good);
2539 Py_DECREF(good);
2540 if (ok) {
2541 if (PyTuple_SetItem(result, j++, item) < 0)
2542 goto Fail_1;
2544 else
2545 Py_DECREF(item);
2548 if (_PyTuple_Resize(&result, j) < 0)
2549 return NULL;
2551 return result;
2553 Fail_1:
2554 Py_DECREF(result);
2555 return NULL;
2559 /* Helper for filter(): filter a string through a function */
2561 static PyObject *
2562 filterstring(PyObject *func, PyObject *strobj)
2564 PyObject *result;
2565 Py_ssize_t i, j;
2566 Py_ssize_t len = PyString_Size(strobj);
2567 Py_ssize_t outlen = len;
2569 if (func == Py_None) {
2570 /* If it's a real string we can return the original,
2571 * as no character is ever false and __getitem__
2572 * does return this character. If it's a subclass
2573 * we must go through the __getitem__ loop */
2574 if (PyString_CheckExact(strobj)) {
2575 Py_INCREF(strobj);
2576 return strobj;
2579 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2580 return NULL;
2582 for (i = j = 0; i < len; ++i) {
2583 PyObject *item;
2584 int ok;
2586 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2587 if (item == NULL)
2588 goto Fail_1;
2589 if (func==Py_None) {
2590 ok = 1;
2591 } else {
2592 PyObject *arg, *good;
2593 arg = PyTuple_Pack(1, item);
2594 if (arg == NULL) {
2595 Py_DECREF(item);
2596 goto Fail_1;
2598 good = PyEval_CallObject(func, arg);
2599 Py_DECREF(arg);
2600 if (good == NULL) {
2601 Py_DECREF(item);
2602 goto Fail_1;
2604 ok = PyObject_IsTrue(good);
2605 Py_DECREF(good);
2607 if (ok) {
2608 Py_ssize_t reslen;
2609 if (!PyString_Check(item)) {
2610 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2611 " __getitem__ returned different type");
2612 Py_DECREF(item);
2613 goto Fail_1;
2615 reslen = PyString_GET_SIZE(item);
2616 if (reslen == 1) {
2617 PyString_AS_STRING(result)[j++] =
2618 PyString_AS_STRING(item)[0];
2619 } else {
2620 /* do we need more space? */
2621 Py_ssize_t need = j + reslen + len-i-1;
2622 if (need > outlen) {
2623 /* overallocate, to avoid reallocations */
2624 if (need<2*outlen)
2625 need = 2*outlen;
2626 if (_PyString_Resize(&result, need)) {
2627 Py_DECREF(item);
2628 return NULL;
2630 outlen = need;
2632 memcpy(
2633 PyString_AS_STRING(result) + j,
2634 PyString_AS_STRING(item),
2635 reslen
2637 j += reslen;
2640 Py_DECREF(item);
2643 if (j < outlen)
2644 _PyString_Resize(&result, j);
2646 return result;
2648 Fail_1:
2649 Py_DECREF(result);
2650 return NULL;
2653 #ifdef Py_USING_UNICODE
2654 /* Helper for filter(): filter a Unicode object through a function */
2656 static PyObject *
2657 filterunicode(PyObject *func, PyObject *strobj)
2659 PyObject *result;
2660 register Py_ssize_t i, j;
2661 Py_ssize_t len = PyUnicode_GetSize(strobj);
2662 Py_ssize_t outlen = len;
2664 if (func == Py_None) {
2665 /* If it's a real string we can return the original,
2666 * as no character is ever false and __getitem__
2667 * does return this character. If it's a subclass
2668 * we must go through the __getitem__ loop */
2669 if (PyUnicode_CheckExact(strobj)) {
2670 Py_INCREF(strobj);
2671 return strobj;
2674 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2675 return NULL;
2677 for (i = j = 0; i < len; ++i) {
2678 PyObject *item, *arg, *good;
2679 int ok;
2681 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2682 if (item == NULL)
2683 goto Fail_1;
2684 if (func == Py_None) {
2685 ok = 1;
2686 } else {
2687 arg = PyTuple_Pack(1, item);
2688 if (arg == NULL) {
2689 Py_DECREF(item);
2690 goto Fail_1;
2692 good = PyEval_CallObject(func, arg);
2693 Py_DECREF(arg);
2694 if (good == NULL) {
2695 Py_DECREF(item);
2696 goto Fail_1;
2698 ok = PyObject_IsTrue(good);
2699 Py_DECREF(good);
2701 if (ok) {
2702 Py_ssize_t reslen;
2703 if (!PyUnicode_Check(item)) {
2704 PyErr_SetString(PyExc_TypeError,
2705 "can't filter unicode to unicode:"
2706 " __getitem__ returned different type");
2707 Py_DECREF(item);
2708 goto Fail_1;
2710 reslen = PyUnicode_GET_SIZE(item);
2711 if (reslen == 1)
2712 PyUnicode_AS_UNICODE(result)[j++] =
2713 PyUnicode_AS_UNICODE(item)[0];
2714 else {
2715 /* do we need more space? */
2716 Py_ssize_t need = j + reslen + len - i - 1;
2717 if (need > outlen) {
2718 /* overallocate,
2719 to avoid reallocations */
2720 if (need < 2 * outlen)
2721 need = 2 * outlen;
2722 if (PyUnicode_Resize(
2723 &result, need) < 0) {
2724 Py_DECREF(item);
2725 goto Fail_1;
2727 outlen = need;
2729 memcpy(PyUnicode_AS_UNICODE(result) + j,
2730 PyUnicode_AS_UNICODE(item),
2731 reslen*sizeof(Py_UNICODE));
2732 j += reslen;
2735 Py_DECREF(item);
2738 if (j < outlen)
2739 PyUnicode_Resize(&result, j);
2741 return result;
2743 Fail_1:
2744 Py_DECREF(result);
2745 return NULL;
2747 #endif