Patch by Jeremy Katz (SF #1609407)
[python.git] / Python / bltinmodule.c
blobf6c4ebbf2f8eb84d6d09e3ca87b8a7fc00a80699
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 (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
148 return NULL;
149 if (alist != NULL) {
150 if (!PyTuple_Check(alist)) {
151 if (!PySequence_Check(alist)) {
152 PyErr_Format(PyExc_TypeError,
153 "apply() arg 2 expected sequence, found %s",
154 alist->ob_type->tp_name);
155 return NULL;
157 t = PySequence_Tuple(alist);
158 if (t == NULL)
159 return NULL;
160 alist = t;
163 if (kwdict != NULL && !PyDict_Check(kwdict)) {
164 PyErr_Format(PyExc_TypeError,
165 "apply() arg 3 expected dictionary, found %s",
166 kwdict->ob_type->tp_name);
167 goto finally;
169 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
170 finally:
171 Py_XDECREF(t);
172 return retval;
175 PyDoc_STRVAR(apply_doc,
176 "apply(object[, args[, kwargs]]) -> value\n\
178 Call a callable object with positional arguments taken from the tuple args,\n\
179 and keyword arguments taken from the optional dictionary kwargs.\n\
180 Note that classes are callable, as are instances with a __call__() method.\n\
182 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
183 function(*args, **keywords).");
186 static PyObject *
187 builtin_callable(PyObject *self, PyObject *v)
189 return PyBool_FromLong((long)PyCallable_Check(v));
192 PyDoc_STRVAR(callable_doc,
193 "callable(object) -> bool\n\
195 Return whether the object is callable (i.e., some kind of function).\n\
196 Note that classes are callable, as are instances with a __call__() method.");
199 static PyObject *
200 builtin_filter(PyObject *self, PyObject *args)
202 PyObject *func, *seq, *result, *it, *arg;
203 Py_ssize_t len; /* guess for result list size */
204 register Py_ssize_t j;
206 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
207 return NULL;
209 /* Strings and tuples return a result of the same type. */
210 if (PyString_Check(seq))
211 return filterstring(func, seq);
212 #ifdef Py_USING_UNICODE
213 if (PyUnicode_Check(seq))
214 return filterunicode(func, seq);
215 #endif
216 if (PyTuple_Check(seq))
217 return filtertuple(func, seq);
219 /* Pre-allocate argument list tuple. */
220 arg = PyTuple_New(1);
221 if (arg == NULL)
222 return NULL;
224 /* Get iterator. */
225 it = PyObject_GetIter(seq);
226 if (it == NULL)
227 goto Fail_arg;
229 /* Guess a result list size. */
230 len = _PyObject_LengthHint(seq);
231 if (len < 0) {
232 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
233 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
234 goto Fail_it;
236 PyErr_Clear();
237 len = 8; /* arbitrary */
240 /* Get a result list. */
241 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
242 /* Eww - can modify the list in-place. */
243 Py_INCREF(seq);
244 result = seq;
246 else {
247 result = PyList_New(len);
248 if (result == NULL)
249 goto Fail_it;
252 /* Build the result list. */
253 j = 0;
254 for (;;) {
255 PyObject *item;
256 int ok;
258 item = PyIter_Next(it);
259 if (item == NULL) {
260 if (PyErr_Occurred())
261 goto Fail_result_it;
262 break;
265 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
266 ok = PyObject_IsTrue(item);
268 else {
269 PyObject *good;
270 PyTuple_SET_ITEM(arg, 0, item);
271 good = PyObject_Call(func, arg, NULL);
272 PyTuple_SET_ITEM(arg, 0, NULL);
273 if (good == NULL) {
274 Py_DECREF(item);
275 goto Fail_result_it;
277 ok = PyObject_IsTrue(good);
278 Py_DECREF(good);
280 if (ok) {
281 if (j < len)
282 PyList_SET_ITEM(result, j, item);
283 else {
284 int status = PyList_Append(result, item);
285 Py_DECREF(item);
286 if (status < 0)
287 goto Fail_result_it;
289 ++j;
291 else
292 Py_DECREF(item);
296 /* Cut back result list if len is too big. */
297 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
298 goto Fail_result_it;
300 Py_DECREF(it);
301 Py_DECREF(arg);
302 return result;
304 Fail_result_it:
305 Py_DECREF(result);
306 Fail_it:
307 Py_DECREF(it);
308 Fail_arg:
309 Py_DECREF(arg);
310 return NULL;
313 PyDoc_STRVAR(filter_doc,
314 "filter(function or None, sequence) -> list, tuple, or string\n"
315 "\n"
316 "Return those items of sequence for which function(item) is true. If\n"
317 "function is None, return the items that are true. If sequence is a tuple\n"
318 "or string, return the same type, else return a list.");
320 static PyObject *
321 builtin_chr(PyObject *self, PyObject *args)
323 long x;
324 char s[1];
326 if (!PyArg_ParseTuple(args, "l:chr", &x))
327 return NULL;
328 if (x < 0 || x >= 256) {
329 PyErr_SetString(PyExc_ValueError,
330 "chr() arg not in range(256)");
331 return NULL;
333 s[0] = (char)x;
334 return PyString_FromStringAndSize(s, 1);
337 PyDoc_STRVAR(chr_doc,
338 "chr(i) -> character\n\
340 Return a string of one character with ordinal i; 0 <= i < 256.");
343 #ifdef Py_USING_UNICODE
344 static PyObject *
345 builtin_unichr(PyObject *self, PyObject *args)
347 long x;
349 if (!PyArg_ParseTuple(args, "l:unichr", &x))
350 return NULL;
352 return PyUnicode_FromOrdinal(x);
355 PyDoc_STRVAR(unichr_doc,
356 "unichr(i) -> Unicode character\n\
358 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
359 #endif
362 static PyObject *
363 builtin_cmp(PyObject *self, PyObject *args)
365 PyObject *a, *b;
366 int c;
368 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
369 return NULL;
370 if (PyObject_Cmp(a, b, &c) < 0)
371 return NULL;
372 return PyInt_FromLong((long)c);
375 PyDoc_STRVAR(cmp_doc,
376 "cmp(x, y) -> integer\n\
378 Return negative if x<y, zero if x==y, positive if x>y.");
381 static PyObject *
382 builtin_coerce(PyObject *self, PyObject *args)
384 PyObject *v, *w;
385 PyObject *res;
387 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
388 return NULL;
389 if (PyNumber_Coerce(&v, &w) < 0)
390 return NULL;
391 res = PyTuple_Pack(2, v, w);
392 Py_DECREF(v);
393 Py_DECREF(w);
394 return res;
397 PyDoc_STRVAR(coerce_doc,
398 "coerce(x, y) -> (x1, y1)\n\
400 Return a tuple consisting of the two numeric arguments converted to\n\
401 a common type, using the same rules as used by arithmetic operations.\n\
402 If coercion is not possible, raise TypeError.");
404 static PyObject *
405 builtin_compile(PyObject *self, PyObject *args)
407 char *str;
408 char *filename;
409 char *startstr;
410 int start;
411 int dont_inherit = 0;
412 int supplied_flags = 0;
413 PyCompilerFlags cf;
414 PyObject *result = NULL, *cmd, *tmp = NULL;
415 Py_ssize_t length;
417 if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename,
418 &startstr, &supplied_flags, &dont_inherit))
419 return NULL;
421 cf.cf_flags = supplied_flags;
423 #ifdef Py_USING_UNICODE
424 if (PyUnicode_Check(cmd)) {
425 tmp = PyUnicode_AsUTF8String(cmd);
426 if (tmp == NULL)
427 return NULL;
428 cmd = tmp;
429 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
431 #endif
432 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
433 return NULL;
434 if ((size_t)length != strlen(str)) {
435 PyErr_SetString(PyExc_TypeError,
436 "compile() expected string without null bytes");
437 goto cleanup;
440 if (strcmp(startstr, "exec") == 0)
441 start = Py_file_input;
442 else if (strcmp(startstr, "eval") == 0)
443 start = Py_eval_input;
444 else if (strcmp(startstr, "single") == 0)
445 start = Py_single_input;
446 else {
447 PyErr_SetString(PyExc_ValueError,
448 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
449 goto cleanup;
452 if (supplied_flags &
453 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
455 PyErr_SetString(PyExc_ValueError,
456 "compile(): unrecognised flags");
457 goto cleanup;
459 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
461 if (!dont_inherit) {
462 PyEval_MergeCompilerFlags(&cf);
464 result = Py_CompileStringFlags(str, filename, start, &cf);
465 cleanup:
466 Py_XDECREF(tmp);
467 return result;
470 PyDoc_STRVAR(compile_doc,
471 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
473 Compile the source string (a Python module, statement or expression)\n\
474 into a code object that can be executed by the exec statement or eval().\n\
475 The filename will be used for run-time error messages.\n\
476 The mode must be 'exec' to compile a module, 'single' to compile a\n\
477 single (interactive) statement, or 'eval' to compile an expression.\n\
478 The flags argument, if present, controls which future statements influence\n\
479 the compilation of the code.\n\
480 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
481 the effects of any future statements in effect in the code calling\n\
482 compile; if absent or zero these statements do influence the compilation,\n\
483 in addition to any features explicitly specified.");
485 static PyObject *
486 builtin_dir(PyObject *self, PyObject *args)
488 PyObject *arg = NULL;
490 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
491 return NULL;
492 return PyObject_Dir(arg);
495 PyDoc_STRVAR(dir_doc,
496 "dir([object]) -> list of strings\n"
497 "\n"
498 "Return an alphabetized list of names comprising (some of) the attributes\n"
499 "of the given object, and of attributes reachable from it:\n"
500 "\n"
501 "No argument: the names in the current scope.\n"
502 "Module object: the module attributes.\n"
503 "Type or class object: its attributes, and recursively the attributes of\n"
504 " its bases.\n"
505 "Otherwise: its attributes, its class's attributes, and recursively the\n"
506 " attributes of its class's base classes.");
508 static PyObject *
509 builtin_divmod(PyObject *self, PyObject *args)
511 PyObject *v, *w;
513 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
514 return NULL;
515 return PyNumber_Divmod(v, w);
518 PyDoc_STRVAR(divmod_doc,
519 "divmod(x, y) -> (div, mod)\n\
521 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
524 static PyObject *
525 builtin_eval(PyObject *self, PyObject *args)
527 PyObject *cmd, *result, *tmp = NULL;
528 PyObject *globals = Py_None, *locals = Py_None;
529 char *str;
530 PyCompilerFlags cf;
532 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
533 return NULL;
534 if (locals != Py_None && !PyMapping_Check(locals)) {
535 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
536 return NULL;
538 if (globals != Py_None && !PyDict_Check(globals)) {
539 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
540 "globals must be a real dict; try eval(expr, {}, mapping)"
541 : "globals must be a dict");
542 return NULL;
544 if (globals == Py_None) {
545 globals = PyEval_GetGlobals();
546 if (locals == Py_None)
547 locals = PyEval_GetLocals();
549 else if (locals == Py_None)
550 locals = globals;
552 if (globals == NULL || locals == NULL) {
553 PyErr_SetString(PyExc_TypeError,
554 "eval must be given globals and locals "
555 "when called without a frame");
556 return NULL;
559 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
560 if (PyDict_SetItemString(globals, "__builtins__",
561 PyEval_GetBuiltins()) != 0)
562 return NULL;
565 if (PyCode_Check(cmd)) {
566 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
567 PyErr_SetString(PyExc_TypeError,
568 "code object passed to eval() may not contain free variables");
569 return NULL;
571 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
574 if (!PyString_Check(cmd) &&
575 !PyUnicode_Check(cmd)) {
576 PyErr_SetString(PyExc_TypeError,
577 "eval() arg 1 must be a string or code object");
578 return NULL;
580 cf.cf_flags = 0;
582 #ifdef Py_USING_UNICODE
583 if (PyUnicode_Check(cmd)) {
584 tmp = PyUnicode_AsUTF8String(cmd);
585 if (tmp == NULL)
586 return NULL;
587 cmd = tmp;
588 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
590 #endif
591 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
592 Py_XDECREF(tmp);
593 return NULL;
595 while (*str == ' ' || *str == '\t')
596 str++;
598 (void)PyEval_MergeCompilerFlags(&cf);
599 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
600 Py_XDECREF(tmp);
601 return result;
604 PyDoc_STRVAR(eval_doc,
605 "eval(source[, globals[, locals]]) -> value\n\
607 Evaluate the source in the context of globals and locals.\n\
608 The source may be a string representing a Python expression\n\
609 or a code object as returned by compile().\n\
610 The globals must be a dictionary and locals can be any mapping,\n\
611 defaulting to the current globals and locals.\n\
612 If only globals is given, locals defaults to it.\n");
615 static PyObject *
616 builtin_execfile(PyObject *self, PyObject *args)
618 char *filename;
619 PyObject *globals = Py_None, *locals = Py_None;
620 PyObject *res;
621 FILE* fp = NULL;
622 PyCompilerFlags cf;
623 int exists;
625 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
626 &filename,
627 &PyDict_Type, &globals,
628 &locals))
629 return NULL;
630 if (locals != Py_None && !PyMapping_Check(locals)) {
631 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
632 return NULL;
634 if (globals == Py_None) {
635 globals = PyEval_GetGlobals();
636 if (locals == Py_None)
637 locals = PyEval_GetLocals();
639 else if (locals == Py_None)
640 locals = globals;
641 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
642 if (PyDict_SetItemString(globals, "__builtins__",
643 PyEval_GetBuiltins()) != 0)
644 return NULL;
647 exists = 0;
648 /* Test for existence or directory. */
649 #if defined(PLAN9)
651 Dir *d;
653 if ((d = dirstat(filename))!=nil) {
654 if(d->mode & DMDIR)
655 werrstr("is a directory");
656 else
657 exists = 1;
658 free(d);
661 #elif defined(RISCOS)
662 if (object_exists(filename)) {
663 if (isdir(filename))
664 errno = EISDIR;
665 else
666 exists = 1;
668 #else /* standard Posix */
670 struct stat s;
671 if (stat(filename, &s) == 0) {
672 if (S_ISDIR(s.st_mode))
673 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
674 errno = EOS2ERR;
675 # else
676 errno = EISDIR;
677 # endif
678 else
679 exists = 1;
682 #endif
684 if (exists) {
685 Py_BEGIN_ALLOW_THREADS
686 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
687 Py_END_ALLOW_THREADS
689 if (fp == NULL) {
690 exists = 0;
694 if (!exists) {
695 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
696 return NULL;
698 cf.cf_flags = 0;
699 if (PyEval_MergeCompilerFlags(&cf))
700 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
701 locals, 1, &cf);
702 else
703 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
704 locals, 1);
705 return res;
708 PyDoc_STRVAR(execfile_doc,
709 "execfile(filename[, globals[, locals]])\n\
711 Read and execute a Python script from a file.\n\
712 The globals and locals are dictionaries, defaulting to the current\n\
713 globals and locals. If only globals is given, locals defaults to it.");
716 static PyObject *
717 builtin_getattr(PyObject *self, PyObject *args)
719 PyObject *v, *result, *dflt = NULL;
720 PyObject *name;
722 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
723 return NULL;
724 #ifdef Py_USING_UNICODE
725 if (PyUnicode_Check(name)) {
726 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
727 if (name == NULL)
728 return NULL;
730 #endif
732 if (!PyString_Check(name)) {
733 PyErr_SetString(PyExc_TypeError,
734 "getattr(): attribute name must be string");
735 return NULL;
737 result = PyObject_GetAttr(v, name);
738 if (result == NULL && dflt != NULL &&
739 PyErr_ExceptionMatches(PyExc_AttributeError))
741 PyErr_Clear();
742 Py_INCREF(dflt);
743 result = dflt;
745 return result;
748 PyDoc_STRVAR(getattr_doc,
749 "getattr(object, name[, default]) -> value\n\
751 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
752 When a default argument is given, it is returned when the attribute doesn't\n\
753 exist; without it, an exception is raised in that case.");
756 static PyObject *
757 builtin_globals(PyObject *self)
759 PyObject *d;
761 d = PyEval_GetGlobals();
762 Py_XINCREF(d);
763 return d;
766 PyDoc_STRVAR(globals_doc,
767 "globals() -> dictionary\n\
769 Return the dictionary containing the current scope's global variables.");
772 static PyObject *
773 builtin_hasattr(PyObject *self, PyObject *args)
775 PyObject *v;
776 PyObject *name;
778 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
779 return NULL;
780 #ifdef Py_USING_UNICODE
781 if (PyUnicode_Check(name)) {
782 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
783 if (name == NULL)
784 return NULL;
786 #endif
788 if (!PyString_Check(name)) {
789 PyErr_SetString(PyExc_TypeError,
790 "hasattr(): attribute name must be string");
791 return NULL;
793 v = PyObject_GetAttr(v, name);
794 if (v == NULL) {
795 PyErr_Clear();
796 Py_INCREF(Py_False);
797 return Py_False;
799 Py_DECREF(v);
800 Py_INCREF(Py_True);
801 return Py_True;
804 PyDoc_STRVAR(hasattr_doc,
805 "hasattr(object, name) -> bool\n\
807 Return whether the object has an attribute with the given name.\n\
808 (This is done by calling getattr(object, name) and catching exceptions.)");
811 static PyObject *
812 builtin_id(PyObject *self, PyObject *v)
814 return PyLong_FromVoidPtr(v);
817 PyDoc_STRVAR(id_doc,
818 "id(object) -> integer\n\
820 Return the identity of an object. This is guaranteed to be unique among\n\
821 simultaneously existing objects. (Hint: it's the object's memory address.)");
824 static PyObject *
825 builtin_map(PyObject *self, PyObject *args)
827 typedef struct {
828 PyObject *it; /* the iterator object */
829 int saw_StopIteration; /* bool: did the iterator end? */
830 } sequence;
832 PyObject *func, *result;
833 sequence *seqs = NULL, *sqp;
834 Py_ssize_t n, len;
835 register int i, j;
837 n = PyTuple_Size(args);
838 if (n < 2) {
839 PyErr_SetString(PyExc_TypeError,
840 "map() requires at least two args");
841 return NULL;
844 func = PyTuple_GetItem(args, 0);
845 n--;
847 if (func == Py_None && n == 1) {
848 /* map(None, S) is the same as list(S). */
849 return PySequence_List(PyTuple_GetItem(args, 1));
852 /* Get space for sequence descriptors. Must NULL out the iterator
853 * pointers so that jumping to Fail_2 later doesn't see trash.
855 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
856 PyErr_NoMemory();
857 return NULL;
859 for (i = 0; i < n; ++i) {
860 seqs[i].it = (PyObject*)NULL;
861 seqs[i].saw_StopIteration = 0;
864 /* Do a first pass to obtain iterators for the arguments, and set len
865 * to the largest of their lengths.
867 len = 0;
868 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
869 PyObject *curseq;
870 Py_ssize_t curlen;
872 /* Get iterator. */
873 curseq = PyTuple_GetItem(args, i+1);
874 sqp->it = PyObject_GetIter(curseq);
875 if (sqp->it == NULL) {
876 static char errmsg[] =
877 "argument %d to map() must support iteration";
878 char errbuf[sizeof(errmsg) + 25];
879 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
880 PyErr_SetString(PyExc_TypeError, errbuf);
881 goto Fail_2;
884 /* Update len. */
885 curlen = _PyObject_LengthHint(curseq);
886 if (curlen < 0) {
887 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
888 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
889 goto Fail_2;
891 PyErr_Clear();
892 curlen = 8; /* arbitrary */
894 if (curlen > len)
895 len = curlen;
898 /* Get space for the result list. */
899 if ((result = (PyObject *) PyList_New(len)) == NULL)
900 goto Fail_2;
902 /* Iterate over the sequences until all have stopped. */
903 for (i = 0; ; ++i) {
904 PyObject *alist, *item=NULL, *value;
905 int numactive = 0;
907 if (func == Py_None && n == 1)
908 alist = NULL;
909 else if ((alist = PyTuple_New(n)) == NULL)
910 goto Fail_1;
912 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
913 if (sqp->saw_StopIteration) {
914 Py_INCREF(Py_None);
915 item = Py_None;
917 else {
918 item = PyIter_Next(sqp->it);
919 if (item)
920 ++numactive;
921 else {
922 if (PyErr_Occurred()) {
923 Py_XDECREF(alist);
924 goto Fail_1;
926 Py_INCREF(Py_None);
927 item = Py_None;
928 sqp->saw_StopIteration = 1;
931 if (alist)
932 PyTuple_SET_ITEM(alist, j, item);
933 else
934 break;
937 if (!alist)
938 alist = item;
940 if (numactive == 0) {
941 Py_DECREF(alist);
942 break;
945 if (func == Py_None)
946 value = alist;
947 else {
948 value = PyEval_CallObject(func, alist);
949 Py_DECREF(alist);
950 if (value == NULL)
951 goto Fail_1;
953 if (i >= len) {
954 int status = PyList_Append(result, value);
955 Py_DECREF(value);
956 if (status < 0)
957 goto Fail_1;
959 else if (PyList_SetItem(result, i, value) < 0)
960 goto Fail_1;
963 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
964 goto Fail_1;
966 goto Succeed;
968 Fail_1:
969 Py_DECREF(result);
970 Fail_2:
971 result = NULL;
972 Succeed:
973 assert(seqs);
974 for (i = 0; i < n; ++i)
975 Py_XDECREF(seqs[i].it);
976 PyMem_DEL(seqs);
977 return result;
980 PyDoc_STRVAR(map_doc,
981 "map(function, sequence[, sequence, ...]) -> list\n\
983 Return a list of the results of applying the function to the items of\n\
984 the argument sequence(s). If more than one sequence is given, the\n\
985 function is called with an argument list consisting of the corresponding\n\
986 item of each sequence, substituting None for missing values when not all\n\
987 sequences have the same length. If the function is None, return a list of\n\
988 the items of the sequence (or a list of tuples if more than one sequence).");
991 static PyObject *
992 builtin_setattr(PyObject *self, PyObject *args)
994 PyObject *v;
995 PyObject *name;
996 PyObject *value;
998 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
999 return NULL;
1000 if (PyObject_SetAttr(v, name, value) != 0)
1001 return NULL;
1002 Py_INCREF(Py_None);
1003 return Py_None;
1006 PyDoc_STRVAR(setattr_doc,
1007 "setattr(object, name, value)\n\
1009 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1010 ``x.y = v''.");
1013 static PyObject *
1014 builtin_delattr(PyObject *self, PyObject *args)
1016 PyObject *v;
1017 PyObject *name;
1019 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1020 return NULL;
1021 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1022 return NULL;
1023 Py_INCREF(Py_None);
1024 return Py_None;
1027 PyDoc_STRVAR(delattr_doc,
1028 "delattr(object, name)\n\
1030 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1031 ``del x.y''.");
1034 static PyObject *
1035 builtin_hash(PyObject *self, PyObject *v)
1037 long x;
1039 x = PyObject_Hash(v);
1040 if (x == -1)
1041 return NULL;
1042 return PyInt_FromLong(x);
1045 PyDoc_STRVAR(hash_doc,
1046 "hash(object) -> integer\n\
1048 Return a hash value for the object. Two objects with the same value have\n\
1049 the same hash value. The reverse is not necessarily true, but likely.");
1052 static PyObject *
1053 builtin_hex(PyObject *self, PyObject *v)
1055 PyNumberMethods *nb;
1056 PyObject *res;
1058 if ((nb = v->ob_type->tp_as_number) == NULL ||
1059 nb->nb_hex == NULL) {
1060 PyErr_SetString(PyExc_TypeError,
1061 "hex() argument can't be converted to hex");
1062 return NULL;
1064 res = (*nb->nb_hex)(v);
1065 if (res && !PyString_Check(res)) {
1066 PyErr_Format(PyExc_TypeError,
1067 "__hex__ returned non-string (type %.200s)",
1068 res->ob_type->tp_name);
1069 Py_DECREF(res);
1070 return NULL;
1072 return res;
1075 PyDoc_STRVAR(hex_doc,
1076 "hex(number) -> string\n\
1078 Return the hexadecimal representation of an integer or long integer.");
1081 static PyObject *builtin_raw_input(PyObject *, PyObject *);
1083 static PyObject *
1084 builtin_input(PyObject *self, PyObject *args)
1086 PyObject *line;
1087 char *str;
1088 PyObject *res;
1089 PyObject *globals, *locals;
1090 PyCompilerFlags cf;
1092 line = builtin_raw_input(self, args);
1093 if (line == NULL)
1094 return line;
1095 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1096 return NULL;
1097 while (*str == ' ' || *str == '\t')
1098 str++;
1099 globals = PyEval_GetGlobals();
1100 locals = PyEval_GetLocals();
1101 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1102 if (PyDict_SetItemString(globals, "__builtins__",
1103 PyEval_GetBuiltins()) != 0)
1104 return NULL;
1106 cf.cf_flags = 0;
1107 PyEval_MergeCompilerFlags(&cf);
1108 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1109 Py_DECREF(line);
1110 return res;
1113 PyDoc_STRVAR(input_doc,
1114 "input([prompt]) -> value\n\
1116 Equivalent to eval(raw_input(prompt)).");
1119 static PyObject *
1120 builtin_intern(PyObject *self, PyObject *args)
1122 PyObject *s;
1123 if (!PyArg_ParseTuple(args, "S:intern", &s))
1124 return NULL;
1125 if (!PyString_CheckExact(s)) {
1126 PyErr_SetString(PyExc_TypeError,
1127 "can't intern subclass of string");
1128 return NULL;
1130 Py_INCREF(s);
1131 PyString_InternInPlace(&s);
1132 return s;
1135 PyDoc_STRVAR(intern_doc,
1136 "intern(string) -> string\n\
1138 ``Intern'' the given string. This enters the string in the (global)\n\
1139 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1140 Return the string itself or the previously interned string object with the\n\
1141 same value.");
1144 static PyObject *
1145 builtin_iter(PyObject *self, PyObject *args)
1147 PyObject *v, *w = NULL;
1149 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1150 return NULL;
1151 if (w == NULL)
1152 return PyObject_GetIter(v);
1153 if (!PyCallable_Check(v)) {
1154 PyErr_SetString(PyExc_TypeError,
1155 "iter(v, w): v must be callable");
1156 return NULL;
1158 return PyCallIter_New(v, w);
1161 PyDoc_STRVAR(iter_doc,
1162 "iter(collection) -> iterator\n\
1163 iter(callable, sentinel) -> iterator\n\
1165 Get an iterator from an object. In the first form, the argument must\n\
1166 supply its own iterator, or be a sequence.\n\
1167 In the second form, the callable is called until it returns the sentinel.");
1170 static PyObject *
1171 builtin_len(PyObject *self, PyObject *v)
1173 Py_ssize_t res;
1175 res = PyObject_Size(v);
1176 if (res < 0 && PyErr_Occurred())
1177 return NULL;
1178 return PyInt_FromSsize_t(res);
1181 PyDoc_STRVAR(len_doc,
1182 "len(object) -> integer\n\
1184 Return the number of items of a sequence or mapping.");
1187 static PyObject *
1188 builtin_locals(PyObject *self)
1190 PyObject *d;
1192 d = PyEval_GetLocals();
1193 Py_XINCREF(d);
1194 return d;
1197 PyDoc_STRVAR(locals_doc,
1198 "locals() -> dictionary\n\
1200 Update and return a dictionary containing the current scope's local variables.");
1203 static PyObject *
1204 min_max(PyObject *args, PyObject *kwds, int op)
1206 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1207 const char *name = op == Py_LT ? "min" : "max";
1209 if (PyTuple_Size(args) > 1)
1210 v = args;
1211 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1212 return NULL;
1214 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1215 keyfunc = PyDict_GetItemString(kwds, "key");
1216 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1217 PyErr_Format(PyExc_TypeError,
1218 "%s() got an unexpected keyword argument", name);
1219 return NULL;
1223 it = PyObject_GetIter(v);
1224 if (it == NULL)
1225 return NULL;
1227 maxitem = NULL; /* the result */
1228 maxval = NULL; /* the value associated with the result */
1229 while (( item = PyIter_Next(it) )) {
1230 /* get the value from the key function */
1231 if (keyfunc != NULL) {
1232 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1233 if (val == NULL)
1234 goto Fail_it_item;
1236 /* no key function; the value is the item */
1237 else {
1238 val = item;
1239 Py_INCREF(val);
1242 /* maximum value and item are unset; set them */
1243 if (maxval == NULL) {
1244 maxitem = item;
1245 maxval = val;
1247 /* maximum value and item are set; update them as necessary */
1248 else {
1249 int cmp = PyObject_RichCompareBool(val, maxval, op);
1250 if (cmp < 0)
1251 goto Fail_it_item_and_val;
1252 else if (cmp > 0) {
1253 Py_DECREF(maxval);
1254 Py_DECREF(maxitem);
1255 maxval = val;
1256 maxitem = item;
1258 else {
1259 Py_DECREF(item);
1260 Py_DECREF(val);
1264 if (PyErr_Occurred())
1265 goto Fail_it;
1266 if (maxval == NULL) {
1267 PyErr_Format(PyExc_ValueError,
1268 "%s() arg is an empty sequence", name);
1269 assert(maxitem == NULL);
1271 else
1272 Py_DECREF(maxval);
1273 Py_DECREF(it);
1274 return maxitem;
1276 Fail_it_item_and_val:
1277 Py_DECREF(val);
1278 Fail_it_item:
1279 Py_DECREF(item);
1280 Fail_it:
1281 Py_XDECREF(maxval);
1282 Py_XDECREF(maxitem);
1283 Py_DECREF(it);
1284 return NULL;
1287 static PyObject *
1288 builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1290 return min_max(args, kwds, Py_LT);
1293 PyDoc_STRVAR(min_doc,
1294 "min(iterable[, key=func]) -> value\n\
1295 min(a, b, c, ...[, key=func]) -> value\n\
1297 With a single iterable argument, return its smallest item.\n\
1298 With two or more arguments, return the smallest argument.");
1301 static PyObject *
1302 builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1304 return min_max(args, kwds, Py_GT);
1307 PyDoc_STRVAR(max_doc,
1308 "max(iterable[, key=func]) -> value\n\
1309 max(a, b, c, ...[, key=func]) -> value\n\
1311 With a single iterable argument, return its largest item.\n\
1312 With two or more arguments, return the largest argument.");
1315 static PyObject *
1316 builtin_oct(PyObject *self, PyObject *v)
1318 PyNumberMethods *nb;
1319 PyObject *res;
1321 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1322 nb->nb_oct == NULL) {
1323 PyErr_SetString(PyExc_TypeError,
1324 "oct() argument can't be converted to oct");
1325 return NULL;
1327 res = (*nb->nb_oct)(v);
1328 if (res && !PyString_Check(res)) {
1329 PyErr_Format(PyExc_TypeError,
1330 "__oct__ returned non-string (type %.200s)",
1331 res->ob_type->tp_name);
1332 Py_DECREF(res);
1333 return NULL;
1335 return res;
1338 PyDoc_STRVAR(oct_doc,
1339 "oct(number) -> string\n\
1341 Return the octal representation of an integer or long integer.");
1344 static PyObject *
1345 builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1347 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
1350 PyDoc_STRVAR(open_doc,
1351 "open(name[, mode[, buffering]]) -> file object\n\
1353 Open a file using the file() type, returns a file object.");
1356 static PyObject *
1357 builtin_ord(PyObject *self, PyObject* obj)
1359 long ord;
1360 Py_ssize_t size;
1362 if (PyString_Check(obj)) {
1363 size = PyString_GET_SIZE(obj);
1364 if (size == 1) {
1365 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1366 return PyInt_FromLong(ord);
1368 #ifdef Py_USING_UNICODE
1369 } else if (PyUnicode_Check(obj)) {
1370 size = PyUnicode_GET_SIZE(obj);
1371 if (size == 1) {
1372 ord = (long)*PyUnicode_AS_UNICODE(obj);
1373 return PyInt_FromLong(ord);
1375 #endif
1376 } else {
1377 PyErr_Format(PyExc_TypeError,
1378 "ord() expected string of length 1, but " \
1379 "%.200s found", obj->ob_type->tp_name);
1380 return NULL;
1383 PyErr_Format(PyExc_TypeError,
1384 "ord() expected a character, "
1385 "but string of length %zd found",
1386 size);
1387 return NULL;
1390 PyDoc_STRVAR(ord_doc,
1391 "ord(c) -> integer\n\
1393 Return the integer ordinal of a one-character string.");
1396 static PyObject *
1397 builtin_pow(PyObject *self, PyObject *args)
1399 PyObject *v, *w, *z = Py_None;
1401 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1402 return NULL;
1403 return PyNumber_Power(v, w, z);
1406 PyDoc_STRVAR(pow_doc,
1407 "pow(x, y[, z]) -> number\n\
1409 With two arguments, equivalent to x**y. With three arguments,\n\
1410 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1414 /* Return number of items in range (lo, hi, step), when arguments are
1415 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1416 * & only if the true value is too large to fit in a signed long.
1417 * Arguments MUST return 1 with either PyInt_Check() or
1418 * PyLong_Check(). Return -1 when there is an error.
1420 static long
1421 get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1423 /* -------------------------------------------------------------
1424 Algorithm is equal to that of get_len_of_range(), but it operates
1425 on PyObjects (which are assumed to be PyLong or PyInt objects).
1426 ---------------------------------------------------------------*/
1427 long n;
1428 PyObject *diff = NULL;
1429 PyObject *one = NULL;
1430 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1431 /* holds sub-expression evaluations */
1433 /* if (lo >= hi), return length of 0. */
1434 if (PyObject_Compare(lo, hi) >= 0)
1435 return 0;
1437 if ((one = PyLong_FromLong(1L)) == NULL)
1438 goto Fail;
1440 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1441 goto Fail;
1443 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1444 goto Fail;
1446 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1447 goto Fail;
1449 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1450 goto Fail;
1452 n = PyLong_AsLong(tmp3);
1453 if (PyErr_Occurred()) { /* Check for Overflow */
1454 PyErr_Clear();
1455 goto Fail;
1458 Py_DECREF(tmp3);
1459 Py_DECREF(tmp2);
1460 Py_DECREF(diff);
1461 Py_DECREF(tmp1);
1462 Py_DECREF(one);
1463 return n;
1465 Fail:
1466 Py_XDECREF(tmp3);
1467 Py_XDECREF(tmp2);
1468 Py_XDECREF(diff);
1469 Py_XDECREF(tmp1);
1470 Py_XDECREF(one);
1471 return -1;
1474 /* An extension of builtin_range() that handles the case when PyLong
1475 * arguments are given. */
1476 static PyObject *
1477 handle_range_longs(PyObject *self, PyObject *args)
1479 PyObject *ilow;
1480 PyObject *ihigh = NULL;
1481 PyObject *istep = NULL;
1483 PyObject *curnum = NULL;
1484 PyObject *v = NULL;
1485 long bign;
1486 int i, n;
1487 int cmp_result;
1489 PyObject *zero = PyLong_FromLong(0);
1491 if (zero == NULL)
1492 return NULL;
1494 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1495 Py_DECREF(zero);
1496 return NULL;
1499 /* Figure out which way we were called, supply defaults, and be
1500 * sure to incref everything so that the decrefs at the end
1501 * are correct.
1503 assert(ilow != NULL);
1504 if (ihigh == NULL) {
1505 /* only 1 arg -- it's the upper limit */
1506 ihigh = ilow;
1507 ilow = NULL;
1509 assert(ihigh != NULL);
1510 Py_INCREF(ihigh);
1512 /* ihigh correct now; do ilow */
1513 if (ilow == NULL)
1514 ilow = zero;
1515 Py_INCREF(ilow);
1517 /* ilow and ihigh correct now; do istep */
1518 if (istep == NULL) {
1519 istep = PyLong_FromLong(1L);
1520 if (istep == NULL)
1521 goto Fail;
1523 else {
1524 Py_INCREF(istep);
1527 if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
1528 PyErr_Format(PyExc_TypeError,
1529 "range() integer start argument expected, got %s.",
1530 ilow->ob_type->tp_name);
1531 goto Fail;
1534 if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
1535 PyErr_Format(PyExc_TypeError,
1536 "range() integer end argument expected, got %s.",
1537 ihigh->ob_type->tp_name);
1538 goto Fail;
1541 if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
1542 PyErr_Format(PyExc_TypeError,
1543 "range() integer step argument expected, got %s.",
1544 istep->ob_type->tp_name);
1545 goto Fail;
1548 if (PyObject_Cmp(istep, zero, &cmp_result) == -1)
1549 goto Fail;
1550 if (cmp_result == 0) {
1551 PyErr_SetString(PyExc_ValueError,
1552 "range() step argument must not be zero");
1553 goto Fail;
1556 if (cmp_result > 0)
1557 bign = get_len_of_range_longs(ilow, ihigh, istep);
1558 else {
1559 PyObject *neg_istep = PyNumber_Negative(istep);
1560 if (neg_istep == NULL)
1561 goto Fail;
1562 bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
1563 Py_DECREF(neg_istep);
1566 n = (int)bign;
1567 if (bign < 0 || (long)n != bign) {
1568 PyErr_SetString(PyExc_OverflowError,
1569 "range() result has too many items");
1570 goto Fail;
1573 v = PyList_New(n);
1574 if (v == NULL)
1575 goto Fail;
1577 curnum = ilow;
1578 Py_INCREF(curnum);
1580 for (i = 0; i < n; i++) {
1581 PyObject *w = PyNumber_Long(curnum);
1582 PyObject *tmp_num;
1583 if (w == NULL)
1584 goto Fail;
1586 PyList_SET_ITEM(v, i, w);
1588 tmp_num = PyNumber_Add(curnum, istep);
1589 if (tmp_num == NULL)
1590 goto Fail;
1592 Py_DECREF(curnum);
1593 curnum = tmp_num;
1595 Py_DECREF(ilow);
1596 Py_DECREF(ihigh);
1597 Py_DECREF(istep);
1598 Py_DECREF(zero);
1599 Py_DECREF(curnum);
1600 return v;
1602 Fail:
1603 Py_DECREF(ilow);
1604 Py_DECREF(ihigh);
1605 Py_XDECREF(istep);
1606 Py_DECREF(zero);
1607 Py_XDECREF(curnum);
1608 Py_XDECREF(v);
1609 return NULL;
1612 /* Return number of items in range/xrange (lo, hi, step). step > 0
1613 * required. Return a value < 0 if & only if the true value is too
1614 * large to fit in a signed long.
1616 static long
1617 get_len_of_range(long lo, long hi, long step)
1619 /* -------------------------------------------------------------
1620 If lo >= hi, the range is empty.
1621 Else if n values are in the range, the last one is
1622 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1623 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1624 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1625 the RHS is non-negative and so truncation is the same as the
1626 floor. Letting M be the largest positive long, the worst case
1627 for the RHS numerator is hi=M, lo=-M-1, and then
1628 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1629 precision to compute the RHS exactly.
1630 ---------------------------------------------------------------*/
1631 long n = 0;
1632 if (lo < hi) {
1633 unsigned long uhi = (unsigned long)hi;
1634 unsigned long ulo = (unsigned long)lo;
1635 unsigned long diff = uhi - ulo - 1;
1636 n = (long)(diff / (unsigned long)step + 1);
1638 return n;
1641 static PyObject *
1642 builtin_range(PyObject *self, PyObject *args)
1644 long ilow = 0, ihigh = 0, istep = 1;
1645 long bign;
1646 int i, n;
1648 PyObject *v;
1650 if (PyTuple_Size(args) <= 1) {
1651 if (!PyArg_ParseTuple(args,
1652 "l;range() requires 1-3 int arguments",
1653 &ihigh)) {
1654 PyErr_Clear();
1655 return handle_range_longs(self, args);
1658 else {
1659 if (!PyArg_ParseTuple(args,
1660 "ll|l;range() requires 1-3 int arguments",
1661 &ilow, &ihigh, &istep)) {
1662 PyErr_Clear();
1663 return handle_range_longs(self, args);
1666 if (istep == 0) {
1667 PyErr_SetString(PyExc_ValueError,
1668 "range() step argument must not be zero");
1669 return NULL;
1671 if (istep > 0)
1672 bign = get_len_of_range(ilow, ihigh, istep);
1673 else
1674 bign = get_len_of_range(ihigh, ilow, -istep);
1675 n = (int)bign;
1676 if (bign < 0 || (long)n != bign) {
1677 PyErr_SetString(PyExc_OverflowError,
1678 "range() result has too many items");
1679 return NULL;
1681 v = PyList_New(n);
1682 if (v == NULL)
1683 return NULL;
1684 for (i = 0; i < n; i++) {
1685 PyObject *w = PyInt_FromLong(ilow);
1686 if (w == NULL) {
1687 Py_DECREF(v);
1688 return NULL;
1690 PyList_SET_ITEM(v, i, w);
1691 ilow += istep;
1693 return v;
1696 PyDoc_STRVAR(range_doc,
1697 "range([start,] stop[, step]) -> list of integers\n\
1699 Return a list containing an arithmetic progression of integers.\n\
1700 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1701 When step is given, it specifies the increment (or decrement).\n\
1702 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1703 These are exactly the valid indices for a list of 4 elements.");
1706 static PyObject *
1707 builtin_raw_input(PyObject *self, PyObject *args)
1709 PyObject *v = NULL;
1710 PyObject *fin = PySys_GetObject("stdin");
1711 PyObject *fout = PySys_GetObject("stdout");
1713 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
1714 return NULL;
1716 if (fin == NULL) {
1717 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
1718 return NULL;
1720 if (fout == NULL) {
1721 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
1722 return NULL;
1724 if (PyFile_SoftSpace(fout, 0)) {
1725 if (PyFile_WriteString(" ", fout) != 0)
1726 return NULL;
1728 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
1729 && isatty(fileno(PyFile_AsFile(fin)))
1730 && isatty(fileno(PyFile_AsFile(fout)))) {
1731 PyObject *po;
1732 char *prompt;
1733 char *s;
1734 PyObject *result;
1735 if (v != NULL) {
1736 po = PyObject_Str(v);
1737 if (po == NULL)
1738 return NULL;
1739 prompt = PyString_AsString(po);
1740 if (prompt == NULL)
1741 return NULL;
1743 else {
1744 po = NULL;
1745 prompt = "";
1747 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
1748 prompt);
1749 Py_XDECREF(po);
1750 if (s == NULL) {
1751 if (!PyErr_Occurred())
1752 PyErr_SetNone(PyExc_KeyboardInterrupt);
1753 return NULL;
1755 if (*s == '\0') {
1756 PyErr_SetNone(PyExc_EOFError);
1757 result = NULL;
1759 else { /* strip trailing '\n' */
1760 size_t len = strlen(s);
1761 if (len > PY_SSIZE_T_MAX) {
1762 PyErr_SetString(PyExc_OverflowError,
1763 "[raw_]input: input too long");
1764 result = NULL;
1766 else {
1767 result = PyString_FromStringAndSize(s, len-1);
1770 PyMem_FREE(s);
1771 return result;
1773 if (v != NULL) {
1774 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
1775 return NULL;
1777 return PyFile_GetLine(fin, -1);
1780 PyDoc_STRVAR(raw_input_doc,
1781 "raw_input([prompt]) -> string\n\
1783 Read a string from standard input. The trailing newline is stripped.\n\
1784 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1785 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1786 is printed without a trailing newline before reading.");
1789 static PyObject *
1790 builtin_reduce(PyObject *self, PyObject *args)
1792 PyObject *seq, *func, *result = NULL, *it;
1794 if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
1795 return NULL;
1796 if (result != NULL)
1797 Py_INCREF(result);
1799 it = PyObject_GetIter(seq);
1800 if (it == NULL) {
1801 PyErr_SetString(PyExc_TypeError,
1802 "reduce() arg 2 must support iteration");
1803 Py_XDECREF(result);
1804 return NULL;
1807 if ((args = PyTuple_New(2)) == NULL)
1808 goto Fail;
1810 for (;;) {
1811 PyObject *op2;
1813 if (args->ob_refcnt > 1) {
1814 Py_DECREF(args);
1815 if ((args = PyTuple_New(2)) == NULL)
1816 goto Fail;
1819 op2 = PyIter_Next(it);
1820 if (op2 == NULL) {
1821 if (PyErr_Occurred())
1822 goto Fail;
1823 break;
1826 if (result == NULL)
1827 result = op2;
1828 else {
1829 PyTuple_SetItem(args, 0, result);
1830 PyTuple_SetItem(args, 1, op2);
1831 if ((result = PyEval_CallObject(func, args)) == NULL)
1832 goto Fail;
1836 Py_DECREF(args);
1838 if (result == NULL)
1839 PyErr_SetString(PyExc_TypeError,
1840 "reduce() of empty sequence with no initial value");
1842 Py_DECREF(it);
1843 return result;
1845 Fail:
1846 Py_XDECREF(args);
1847 Py_XDECREF(result);
1848 Py_DECREF(it);
1849 return NULL;
1852 PyDoc_STRVAR(reduce_doc,
1853 "reduce(function, sequence[, initial]) -> value\n\
1855 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1856 from left to right, so as to reduce the sequence to a single value.\n\
1857 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1858 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1859 of the sequence in the calculation, and serves as a default when the\n\
1860 sequence is empty.");
1863 static PyObject *
1864 builtin_reload(PyObject *self, PyObject *v)
1866 return PyImport_ReloadModule(v);
1869 PyDoc_STRVAR(reload_doc,
1870 "reload(module) -> module\n\
1872 Reload the module. The module must have been successfully imported before.");
1875 static PyObject *
1876 builtin_repr(PyObject *self, PyObject *v)
1878 return PyObject_Repr(v);
1881 PyDoc_STRVAR(repr_doc,
1882 "repr(object) -> string\n\
1884 Return the canonical string representation of the object.\n\
1885 For most object types, eval(repr(object)) == object.");
1888 static PyObject *
1889 builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
1891 double number;
1892 double f;
1893 int ndigits = 0;
1894 int i;
1895 static char *kwlist[] = {"number", "ndigits", 0};
1897 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|i:round",
1898 kwlist, &number, &ndigits))
1899 return NULL;
1900 f = 1.0;
1901 i = abs(ndigits);
1902 while (--i >= 0)
1903 f = f*10.0;
1904 if (ndigits < 0)
1905 number /= f;
1906 else
1907 number *= f;
1908 if (number >= 0.0)
1909 number = floor(number + 0.5);
1910 else
1911 number = ceil(number - 0.5);
1912 if (ndigits < 0)
1913 number *= f;
1914 else
1915 number /= f;
1916 return PyFloat_FromDouble(number);
1919 PyDoc_STRVAR(round_doc,
1920 "round(number[, ndigits]) -> floating point number\n\
1922 Round a number to a given precision in decimal digits (default 0 digits).\n\
1923 This always returns a floating point number. Precision may be negative.");
1925 static PyObject *
1926 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1928 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1929 PyObject *callable;
1930 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
1931 int reverse;
1933 /* args 1-4 should match listsort in Objects/listobject.c */
1934 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1935 kwlist, &seq, &compare, &keyfunc, &reverse))
1936 return NULL;
1938 newlist = PySequence_List(seq);
1939 if (newlist == NULL)
1940 return NULL;
1942 callable = PyObject_GetAttrString(newlist, "sort");
1943 if (callable == NULL) {
1944 Py_DECREF(newlist);
1945 return NULL;
1948 newargs = PyTuple_GetSlice(args, 1, 4);
1949 if (newargs == NULL) {
1950 Py_DECREF(newlist);
1951 Py_DECREF(callable);
1952 return NULL;
1955 v = PyObject_Call(callable, newargs, kwds);
1956 Py_DECREF(newargs);
1957 Py_DECREF(callable);
1958 if (v == NULL) {
1959 Py_DECREF(newlist);
1960 return NULL;
1962 Py_DECREF(v);
1963 return newlist;
1966 PyDoc_STRVAR(sorted_doc,
1967 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
1969 static PyObject *
1970 builtin_vars(PyObject *self, PyObject *args)
1972 PyObject *v = NULL;
1973 PyObject *d;
1975 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1976 return NULL;
1977 if (v == NULL) {
1978 d = PyEval_GetLocals();
1979 if (d == NULL) {
1980 if (!PyErr_Occurred())
1981 PyErr_SetString(PyExc_SystemError,
1982 "vars(): no locals!?");
1984 else
1985 Py_INCREF(d);
1987 else {
1988 d = PyObject_GetAttrString(v, "__dict__");
1989 if (d == NULL) {
1990 PyErr_SetString(PyExc_TypeError,
1991 "vars() argument must have __dict__ attribute");
1992 return NULL;
1995 return d;
1998 PyDoc_STRVAR(vars_doc,
1999 "vars([object]) -> dictionary\n\
2001 Without arguments, equivalent to locals().\n\
2002 With an argument, equivalent to object.__dict__.");
2005 static PyObject*
2006 builtin_sum(PyObject *self, PyObject *args)
2008 PyObject *seq;
2009 PyObject *result = NULL;
2010 PyObject *temp, *item, *iter;
2012 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2013 return NULL;
2015 iter = PyObject_GetIter(seq);
2016 if (iter == NULL)
2017 return NULL;
2019 if (result == NULL) {
2020 result = PyInt_FromLong(0);
2021 if (result == NULL) {
2022 Py_DECREF(iter);
2023 return NULL;
2025 } else {
2026 /* reject string values for 'start' parameter */
2027 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2028 PyErr_SetString(PyExc_TypeError,
2029 "sum() can't sum strings [use ''.join(seq) instead]");
2030 Py_DECREF(iter);
2031 return NULL;
2033 Py_INCREF(result);
2036 for(;;) {
2037 item = PyIter_Next(iter);
2038 if (item == NULL) {
2039 /* error, or end-of-sequence */
2040 if (PyErr_Occurred()) {
2041 Py_DECREF(result);
2042 result = NULL;
2044 break;
2046 temp = PyNumber_Add(result, item);
2047 Py_DECREF(result);
2048 Py_DECREF(item);
2049 result = temp;
2050 if (result == NULL)
2051 break;
2053 Py_DECREF(iter);
2054 return result;
2057 PyDoc_STRVAR(sum_doc,
2058 "sum(sequence[, start]) -> value\n\
2060 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2061 of parameter 'start' (which defaults to 0). When the sequence is\n\
2062 empty, returns start.");
2065 static PyObject *
2066 builtin_isinstance(PyObject *self, PyObject *args)
2068 PyObject *inst;
2069 PyObject *cls;
2070 int retval;
2072 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2073 return NULL;
2075 retval = PyObject_IsInstance(inst, cls);
2076 if (retval < 0)
2077 return NULL;
2078 return PyBool_FromLong(retval);
2081 PyDoc_STRVAR(isinstance_doc,
2082 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2084 Return whether an object is an instance of a class or of a subclass thereof.\n\
2085 With a type as second argument, return whether that is the object's type.\n\
2086 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2087 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2090 static PyObject *
2091 builtin_issubclass(PyObject *self, PyObject *args)
2093 PyObject *derived;
2094 PyObject *cls;
2095 int retval;
2097 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2098 return NULL;
2100 retval = PyObject_IsSubclass(derived, cls);
2101 if (retval < 0)
2102 return NULL;
2103 return PyBool_FromLong(retval);
2106 PyDoc_STRVAR(issubclass_doc,
2107 "issubclass(C, B) -> bool\n\
2109 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2110 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2111 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2114 static PyObject*
2115 builtin_zip(PyObject *self, PyObject *args)
2117 PyObject *ret;
2118 const Py_ssize_t itemsize = PySequence_Length(args);
2119 Py_ssize_t i;
2120 PyObject *itlist; /* tuple of iterators */
2121 Py_ssize_t len; /* guess at result length */
2123 if (itemsize == 0)
2124 return PyList_New(0);
2126 /* args must be a tuple */
2127 assert(PyTuple_Check(args));
2129 /* Guess at result length: the shortest of the input lengths.
2130 If some argument refuses to say, we refuse to guess too, lest
2131 an argument like xrange(sys.maxint) lead us astray.*/
2132 len = -1; /* unknown */
2133 for (i = 0; i < itemsize; ++i) {
2134 PyObject *item = PyTuple_GET_ITEM(args, i);
2135 Py_ssize_t thislen = _PyObject_LengthHint(item);
2136 if (thislen < 0) {
2137 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
2138 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
2139 return NULL;
2141 PyErr_Clear();
2142 len = -1;
2143 break;
2145 else if (len < 0 || thislen < len)
2146 len = thislen;
2149 /* allocate result list */
2150 if (len < 0)
2151 len = 10; /* arbitrary */
2152 if ((ret = PyList_New(len)) == NULL)
2153 return NULL;
2155 /* obtain iterators */
2156 itlist = PyTuple_New(itemsize);
2157 if (itlist == NULL)
2158 goto Fail_ret;
2159 for (i = 0; i < itemsize; ++i) {
2160 PyObject *item = PyTuple_GET_ITEM(args, i);
2161 PyObject *it = PyObject_GetIter(item);
2162 if (it == NULL) {
2163 if (PyErr_ExceptionMatches(PyExc_TypeError))
2164 PyErr_Format(PyExc_TypeError,
2165 "zip argument #%zd must support iteration",
2166 i+1);
2167 goto Fail_ret_itlist;
2169 PyTuple_SET_ITEM(itlist, i, it);
2172 /* build result into ret list */
2173 for (i = 0; ; ++i) {
2174 int j;
2175 PyObject *next = PyTuple_New(itemsize);
2176 if (!next)
2177 goto Fail_ret_itlist;
2179 for (j = 0; j < itemsize; j++) {
2180 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2181 PyObject *item = PyIter_Next(it);
2182 if (!item) {
2183 if (PyErr_Occurred()) {
2184 Py_DECREF(ret);
2185 ret = NULL;
2187 Py_DECREF(next);
2188 Py_DECREF(itlist);
2189 goto Done;
2191 PyTuple_SET_ITEM(next, j, item);
2194 if (i < len)
2195 PyList_SET_ITEM(ret, i, next);
2196 else {
2197 int status = PyList_Append(ret, next);
2198 Py_DECREF(next);
2199 ++len;
2200 if (status < 0)
2201 goto Fail_ret_itlist;
2205 Done:
2206 if (ret != NULL && i < len) {
2207 /* The list is too big. */
2208 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2209 return NULL;
2211 return ret;
2213 Fail_ret_itlist:
2214 Py_DECREF(itlist);
2215 Fail_ret:
2216 Py_DECREF(ret);
2217 return NULL;
2221 PyDoc_STRVAR(zip_doc,
2222 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2224 Return a list of tuples, where each tuple contains the i-th element\n\
2225 from each of the argument sequences. The returned list is truncated\n\
2226 in length to the length of the shortest argument sequence.");
2229 static PyMethodDef builtin_methods[] = {
2230 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2231 {"abs", builtin_abs, METH_O, abs_doc},
2232 {"all", builtin_all, METH_O, all_doc},
2233 {"any", builtin_any, METH_O, any_doc},
2234 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2235 {"callable", builtin_callable, METH_O, callable_doc},
2236 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2237 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2238 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2239 {"compile", builtin_compile, METH_VARARGS, compile_doc},
2240 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2241 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2242 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2243 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2244 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2245 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2246 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2247 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2248 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2249 {"hash", builtin_hash, METH_O, hash_doc},
2250 {"hex", builtin_hex, METH_O, hex_doc},
2251 {"id", builtin_id, METH_O, id_doc},
2252 {"input", builtin_input, METH_VARARGS, input_doc},
2253 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2254 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2255 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2256 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2257 {"len", builtin_len, METH_O, len_doc},
2258 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2259 {"map", builtin_map, METH_VARARGS, map_doc},
2260 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2261 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2262 {"oct", builtin_oct, METH_O, oct_doc},
2263 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2264 {"ord", builtin_ord, METH_O, ord_doc},
2265 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2266 {"range", builtin_range, METH_VARARGS, range_doc},
2267 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2268 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2269 {"reload", builtin_reload, METH_O, reload_doc},
2270 {"repr", builtin_repr, METH_O, repr_doc},
2271 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2272 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2273 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2274 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2275 #ifdef Py_USING_UNICODE
2276 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
2277 #endif
2278 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2279 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2280 {NULL, NULL},
2283 PyDoc_STRVAR(builtin_doc,
2284 "Built-in functions, exceptions, and other objects.\n\
2286 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2288 PyObject *
2289 _PyBuiltin_Init(void)
2291 PyObject *mod, *dict, *debug;
2292 mod = Py_InitModule4("__builtin__", builtin_methods,
2293 builtin_doc, (PyObject *)NULL,
2294 PYTHON_API_VERSION);
2295 if (mod == NULL)
2296 return NULL;
2297 dict = PyModule_GetDict(mod);
2299 #ifdef Py_TRACE_REFS
2300 /* __builtin__ exposes a number of statically allocated objects
2301 * that, before this code was added in 2.3, never showed up in
2302 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2303 * result, programs leaking references to None and False (etc)
2304 * couldn't be diagnosed by examining sys.getobjects(0).
2306 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2307 #else
2308 #define ADD_TO_ALL(OBJECT) (void)0
2309 #endif
2311 #define SETBUILTIN(NAME, OBJECT) \
2312 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2313 return NULL; \
2314 ADD_TO_ALL(OBJECT)
2316 SETBUILTIN("None", Py_None);
2317 SETBUILTIN("Ellipsis", Py_Ellipsis);
2318 SETBUILTIN("NotImplemented", Py_NotImplemented);
2319 SETBUILTIN("False", Py_False);
2320 SETBUILTIN("True", Py_True);
2321 SETBUILTIN("basestring", &PyBaseString_Type);
2322 SETBUILTIN("bool", &PyBool_Type);
2323 SETBUILTIN("buffer", &PyBuffer_Type);
2324 SETBUILTIN("classmethod", &PyClassMethod_Type);
2325 #ifndef WITHOUT_COMPLEX
2326 SETBUILTIN("complex", &PyComplex_Type);
2327 #endif
2328 SETBUILTIN("dict", &PyDict_Type);
2329 SETBUILTIN("enumerate", &PyEnum_Type);
2330 SETBUILTIN("file", &PyFile_Type);
2331 SETBUILTIN("float", &PyFloat_Type);
2332 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2333 SETBUILTIN("property", &PyProperty_Type);
2334 SETBUILTIN("int", &PyInt_Type);
2335 SETBUILTIN("list", &PyList_Type);
2336 SETBUILTIN("long", &PyLong_Type);
2337 SETBUILTIN("object", &PyBaseObject_Type);
2338 SETBUILTIN("reversed", &PyReversed_Type);
2339 SETBUILTIN("set", &PySet_Type);
2340 SETBUILTIN("slice", &PySlice_Type);
2341 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2342 SETBUILTIN("str", &PyString_Type);
2343 SETBUILTIN("super", &PySuper_Type);
2344 SETBUILTIN("tuple", &PyTuple_Type);
2345 SETBUILTIN("type", &PyType_Type);
2346 SETBUILTIN("xrange", &PyRange_Type);
2347 #ifdef Py_USING_UNICODE
2348 SETBUILTIN("unicode", &PyUnicode_Type);
2349 #endif
2350 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2351 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2352 Py_XDECREF(debug);
2353 return NULL;
2355 Py_XDECREF(debug);
2357 return mod;
2358 #undef ADD_TO_ALL
2359 #undef SETBUILTIN
2362 /* Helper for filter(): filter a tuple through a function */
2364 static PyObject *
2365 filtertuple(PyObject *func, PyObject *tuple)
2367 PyObject *result;
2368 Py_ssize_t i, j;
2369 Py_ssize_t len = PyTuple_Size(tuple);
2371 if (len == 0) {
2372 if (PyTuple_CheckExact(tuple))
2373 Py_INCREF(tuple);
2374 else
2375 tuple = PyTuple_New(0);
2376 return tuple;
2379 if ((result = PyTuple_New(len)) == NULL)
2380 return NULL;
2382 for (i = j = 0; i < len; ++i) {
2383 PyObject *item, *good;
2384 int ok;
2386 if (tuple->ob_type->tp_as_sequence &&
2387 tuple->ob_type->tp_as_sequence->sq_item) {
2388 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2389 if (item == NULL)
2390 goto Fail_1;
2391 } else {
2392 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2393 goto Fail_1;
2395 if (func == Py_None) {
2396 Py_INCREF(item);
2397 good = item;
2399 else {
2400 PyObject *arg = PyTuple_Pack(1, item);
2401 if (arg == NULL) {
2402 Py_DECREF(item);
2403 goto Fail_1;
2405 good = PyEval_CallObject(func, arg);
2406 Py_DECREF(arg);
2407 if (good == NULL) {
2408 Py_DECREF(item);
2409 goto Fail_1;
2412 ok = PyObject_IsTrue(good);
2413 Py_DECREF(good);
2414 if (ok) {
2415 if (PyTuple_SetItem(result, j++, item) < 0)
2416 goto Fail_1;
2418 else
2419 Py_DECREF(item);
2422 if (_PyTuple_Resize(&result, j) < 0)
2423 return NULL;
2425 return result;
2427 Fail_1:
2428 Py_DECREF(result);
2429 return NULL;
2433 /* Helper for filter(): filter a string through a function */
2435 static PyObject *
2436 filterstring(PyObject *func, PyObject *strobj)
2438 PyObject *result;
2439 Py_ssize_t i, j;
2440 Py_ssize_t len = PyString_Size(strobj);
2441 Py_ssize_t outlen = len;
2443 if (func == Py_None) {
2444 /* If it's a real string we can return the original,
2445 * as no character is ever false and __getitem__
2446 * does return this character. If it's a subclass
2447 * we must go through the __getitem__ loop */
2448 if (PyString_CheckExact(strobj)) {
2449 Py_INCREF(strobj);
2450 return strobj;
2453 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2454 return NULL;
2456 for (i = j = 0; i < len; ++i) {
2457 PyObject *item;
2458 int ok;
2460 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2461 if (item == NULL)
2462 goto Fail_1;
2463 if (func==Py_None) {
2464 ok = 1;
2465 } else {
2466 PyObject *arg, *good;
2467 arg = PyTuple_Pack(1, item);
2468 if (arg == NULL) {
2469 Py_DECREF(item);
2470 goto Fail_1;
2472 good = PyEval_CallObject(func, arg);
2473 Py_DECREF(arg);
2474 if (good == NULL) {
2475 Py_DECREF(item);
2476 goto Fail_1;
2478 ok = PyObject_IsTrue(good);
2479 Py_DECREF(good);
2481 if (ok) {
2482 Py_ssize_t reslen;
2483 if (!PyString_Check(item)) {
2484 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2485 " __getitem__ returned different type");
2486 Py_DECREF(item);
2487 goto Fail_1;
2489 reslen = PyString_GET_SIZE(item);
2490 if (reslen == 1) {
2491 PyString_AS_STRING(result)[j++] =
2492 PyString_AS_STRING(item)[0];
2493 } else {
2494 /* do we need more space? */
2495 Py_ssize_t need = j + reslen + len-i-1;
2496 if (need > outlen) {
2497 /* overallocate, to avoid reallocations */
2498 if (need<2*outlen)
2499 need = 2*outlen;
2500 if (_PyString_Resize(&result, need)) {
2501 Py_DECREF(item);
2502 return NULL;
2504 outlen = need;
2506 memcpy(
2507 PyString_AS_STRING(result) + j,
2508 PyString_AS_STRING(item),
2509 reslen
2511 j += reslen;
2514 Py_DECREF(item);
2517 if (j < outlen)
2518 _PyString_Resize(&result, j);
2520 return result;
2522 Fail_1:
2523 Py_DECREF(result);
2524 return NULL;
2527 #ifdef Py_USING_UNICODE
2528 /* Helper for filter(): filter a Unicode object through a function */
2530 static PyObject *
2531 filterunicode(PyObject *func, PyObject *strobj)
2533 PyObject *result;
2534 register Py_ssize_t i, j;
2535 Py_ssize_t len = PyUnicode_GetSize(strobj);
2536 Py_ssize_t outlen = len;
2538 if (func == Py_None) {
2539 /* If it's a real string we can return the original,
2540 * as no character is ever false and __getitem__
2541 * does return this character. If it's a subclass
2542 * we must go through the __getitem__ loop */
2543 if (PyUnicode_CheckExact(strobj)) {
2544 Py_INCREF(strobj);
2545 return strobj;
2548 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2549 return NULL;
2551 for (i = j = 0; i < len; ++i) {
2552 PyObject *item, *arg, *good;
2553 int ok;
2555 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2556 if (item == NULL)
2557 goto Fail_1;
2558 if (func == Py_None) {
2559 ok = 1;
2560 } else {
2561 arg = PyTuple_Pack(1, item);
2562 if (arg == NULL) {
2563 Py_DECREF(item);
2564 goto Fail_1;
2566 good = PyEval_CallObject(func, arg);
2567 Py_DECREF(arg);
2568 if (good == NULL) {
2569 Py_DECREF(item);
2570 goto Fail_1;
2572 ok = PyObject_IsTrue(good);
2573 Py_DECREF(good);
2575 if (ok) {
2576 Py_ssize_t reslen;
2577 if (!PyUnicode_Check(item)) {
2578 PyErr_SetString(PyExc_TypeError,
2579 "can't filter unicode to unicode:"
2580 " __getitem__ returned different type");
2581 Py_DECREF(item);
2582 goto Fail_1;
2584 reslen = PyUnicode_GET_SIZE(item);
2585 if (reslen == 1)
2586 PyUnicode_AS_UNICODE(result)[j++] =
2587 PyUnicode_AS_UNICODE(item)[0];
2588 else {
2589 /* do we need more space? */
2590 Py_ssize_t need = j + reslen + len - i - 1;
2591 if (need > outlen) {
2592 /* overallocate,
2593 to avoid reallocations */
2594 if (need < 2 * outlen)
2595 need = 2 * outlen;
2596 if (PyUnicode_Resize(
2597 &result, need) < 0) {
2598 Py_DECREF(item);
2599 goto Fail_1;
2601 outlen = need;
2603 memcpy(PyUnicode_AS_UNICODE(result) + j,
2604 PyUnicode_AS_UNICODE(item),
2605 reslen*sizeof(Py_UNICODE));
2606 j += reslen;
2609 Py_DECREF(item);
2612 if (j < outlen)
2613 PyUnicode_Resize(&result, j);
2615 return result;
2617 Fail_1:
2618 Py_DECREF(result);
2619 return NULL;
2621 #endif