bltinmodule.c revision 77c85e63b42743b22dda5538cedfb1dd1282a657
183e085b7a331c96237cf8e814f97b3ef4c36a70fjimblandy 2f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com/* Built-in functions */ 3f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 4f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#include "Python.h" 5f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 6f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#include "node.h" 7f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#include "compile.h" 8f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#include "eval.h" 9f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 10f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#include <ctype.h> 11f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 12f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#ifdef RISCOS 13f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#include "unixstuff.h" 14f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#endif 15f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 16f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com/* The default encoding used by the platform file system APIs 17f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com Can remain NULL for all platforms that don't have such a concept 18f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com*/ 19f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) 20f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comconst char *Py_FileSystemDefaultEncoding = "mbcs"; 21f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#elif defined(__APPLE__) 22f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comconst char *Py_FileSystemDefaultEncoding = "utf-8"; 23f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#else 24f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comconst char *Py_FileSystemDefaultEncoding = NULL; /* use default */ 25f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#endif 26f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 27f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com/* Forward */ 28f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comstatic PyObject *filterstring(PyObject *, PyObject *); 29c50e7c604cd1b12bba9421b0a95357fc942ecd7cjimblandy#ifdef Py_USING_UNICODE 30c50e7c604cd1b12bba9421b0a95357fc942ecd7cjimblandystatic PyObject *filterunicode(PyObject *, PyObject *); 31f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#endif 32c50e7c604cd1b12bba9421b0a95357fc942ecd7cjimblandystatic PyObject *filtertuple (PyObject *, PyObject *); 33f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 3487855248f1fab83caf002418196a34051d359f2cjimblandystatic PyObject * 35f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.combuiltin___import__(PyObject *self, PyObject *args) 36b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy{ 37b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy char *name; 38b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy PyObject *globals = NULL; 39b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy PyObject *locals = NULL; 404e518a4357a2d1c379d4a91df6d4e153ee791101ivan.penkov@gmail.com PyObject *fromlist = NULL; 414e518a4357a2d1c379d4a91df6d4e153ee791101ivan.penkov@gmail.com 424e518a4357a2d1c379d4a91df6d4e153ee791101ivan.penkov@gmail.com if (!PyArg_ParseTuple(args, "s|OOO:__import__", 434e518a4357a2d1c379d4a91df6d4e153ee791101ivan.penkov@gmail.com &name, &globals, &locals, &fromlist)) 44775c6f7640a02841b667fd6300e877bbed574544jimblandy return NULL; 45775c6f7640a02841b667fd6300e877bbed574544jimblandy return PyImport_ImportModuleEx(name, globals, locals, fromlist); 46f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com} 47f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 48b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandyPyDoc_STRVAR(import_doc, 49b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy"__import__(name, globals, locals, fromlist) -> module\n\ 50b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy\n\ 51b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandyImport a module. The globals are only used to determine the context;\n\ 52b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandythey are not modified. The locals are currently unused. The fromlist\n\ 53b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandyshould be a list of names to emulate ``from name import ...'', or an\n\ 54b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandyempty list to emulate ``import name''.\n\ 55b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandyWhen importing a module from a package, note that __import__('A.B', ...)\n\ 56b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandyreturns package A when fromlist is empty, but its submodule B when\n\ 57b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandyfromlist is not empty."); 58b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy 59b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy 60b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandystatic PyObject * 61b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandybuiltin_abs(PyObject *self, PyObject *v) 62b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy{ 63b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy return PyNumber_Absolute(v); 64b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy} 65b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy 66b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandyPyDoc_STRVAR(abs_doc, 67b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy"abs(number) -> number\n\ 68f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com\n\ 69f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comReturn the absolute value of the argument."); 70775c6f7640a02841b667fd6300e877bbed574544jimblandy 71b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandystatic PyObject * 72b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandybuiltin_all(PyObject *self, PyObject *v) 73b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy{ 74b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy PyObject *it, *item; 75775c6f7640a02841b667fd6300e877bbed574544jimblandy 76b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy it = PyObject_GetIter(v); 77b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy if (it == NULL) 78b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy return NULL; 79b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy 80f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com while ((item = PyIter_Next(it)) != NULL) { 81f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com int cmp = PyObject_IsTrue(item); 82b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy Py_DECREF(item); 83b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy if (cmp < 0) { 8443135e6e46da10bd0b94f28b9392c9b2015152ebjimblandy Py_DECREF(it); 85b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy return NULL; 86f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com } 87f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (cmp == 0) { 88f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com Py_DECREF(it); 89f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com Py_RETURN_FALSE; 90b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy } 91f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com } 92f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com Py_DECREF(it); 93f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (PyErr_Occurred()) 94b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy return NULL; 95b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy Py_RETURN_TRUE; 96f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com} 97f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 98775c6f7640a02841b667fd6300e877bbed574544jimblandyPyDoc_STRVAR(all_doc, 99775c6f7640a02841b667fd6300e877bbed574544jimblandy"all(iterable) -> bool\n\ 100775c6f7640a02841b667fd6300e877bbed574544jimblandy\n\ 101775c6f7640a02841b667fd6300e877bbed574544jimblandyReturn True if bool(x) is True for all values x in the iterable."); 102775c6f7640a02841b667fd6300e877bbed574544jimblandy 103775c6f7640a02841b667fd6300e877bbed574544jimblandystatic PyObject * 104775c6f7640a02841b667fd6300e877bbed574544jimblandybuiltin_any(PyObject *self, PyObject *v) 105775c6f7640a02841b667fd6300e877bbed574544jimblandy{ 1065251e64f48f52f0bc73a4b4dcfa6efa327b1b2ffjimblandy PyObject *it, *item; 1075251e64f48f52f0bc73a4b4dcfa6efa327b1b2ffjimblandy 1085251e64f48f52f0bc73a4b4dcfa6efa327b1b2ffjimblandy it = PyObject_GetIter(v); 1095251e64f48f52f0bc73a4b4dcfa6efa327b1b2ffjimblandy if (it == NULL) 1105251e64f48f52f0bc73a4b4dcfa6efa327b1b2ffjimblandy return NULL; 1115251e64f48f52f0bc73a4b4dcfa6efa327b1b2ffjimblandy 112b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy while ((item = PyIter_Next(it)) != NULL) { 113b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy int cmp = PyObject_IsTrue(item); 114bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek Py_DECREF(item); 115bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek if (cmp < 0) { 116bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek Py_DECREF(it); 117bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek return NULL; 118bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek } 119bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek if (cmp == 1) { 120bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek Py_DECREF(it); 121bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek Py_RETURN_TRUE; 122bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek } 123bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek } 124bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek Py_DECREF(it); 125b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy if (PyErr_Occurred()) 126bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek return NULL; 127f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com Py_RETURN_FALSE; 128f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com} 129f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 130f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comPyDoc_STRVAR(any_doc, 131f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com"any(iterable) -> bool\n\ 132b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy\n\ 133f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comReturn True if bool(x) is True for any x in the iterable."); 134f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 135f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comstatic PyObject * 136f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.combuiltin_apply(PyObject *self, PyObject *args) 1374fd4efe1c615da174abe42f3ca40662bb50763bfthestig@chromium.org{ 138f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com PyObject *func, *alist = NULL, *kwdict = NULL; 139f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com PyObject *t = NULL, *retval = NULL; 140f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 141f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict)) 142b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy return NULL; 143f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (alist != NULL) { 144f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (!PyTuple_Check(alist)) { 1454fd4efe1c615da174abe42f3ca40662bb50763bfthestig@chromium.org if (!PySequence_Check(alist)) { 146f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com PyErr_Format(PyExc_TypeError, 147f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com "apply() arg 2 expected sequence, found %s", 148f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com alist->ob_type->tp_name); 149b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy return NULL; 150f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com } 151f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com t = PySequence_Tuple(alist); 1520397da8e089e755cdfdd83348965a60f176dad14jimblandy@gmail.com if (t == NULL) 1530397da8e089e755cdfdd83348965a60f176dad14jimblandy@gmail.com return NULL; 1540397da8e089e755cdfdd83348965a60f176dad14jimblandy@gmail.com alist = t; 1550397da8e089e755cdfdd83348965a60f176dad14jimblandy@gmail.com } 156b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy } 157f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (kwdict != NULL && !PyDict_Check(kwdict)) { 1580397da8e089e755cdfdd83348965a60f176dad14jimblandy@gmail.com PyErr_Format(PyExc_TypeError, 159f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com "apply() arg 3 expected dictionary, found %s", 160f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com kwdict->ob_type->tp_name); 161f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com goto finally; 162f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com } 163b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy retval = PyEval_CallObjectWithKeywords(func, alist, kwdict); 164f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com finally: 165f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com Py_XDECREF(t); 166f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com return retval; 167b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy} 168f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 169f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comPyDoc_STRVAR(apply_doc, 17008fecb2e43df254f9c1e4d4c6ce1a249b52b238fjimblandy@gmail.com"apply(object[, args[, kwargs]]) -> value\n\ 17108fecb2e43df254f9c1e4d4c6ce1a249b52b238fjimblandy@gmail.com\n\ 17208fecb2e43df254f9c1e4d4c6ce1a249b52b238fjimblandy@gmail.comCall a callable object with positional arguments taken from the tuple args,\n\ 173f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comand keyword arguments taken from the optional dictionary kwargs.\n\ 174f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comNote that classes are callable, as are instances with a __call__() method.\n\ 175b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy\n\ 176b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandyDeprecated since release 2.3. Instead, use the extended call syntax:\n\ 177f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com function(*args, **keywords)."); 178f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 179775c6f7640a02841b667fd6300e877bbed574544jimblandy 180775c6f7640a02841b667fd6300e877bbed574544jimblandystatic PyObject * 181775c6f7640a02841b667fd6300e877bbed574544jimblandybuiltin_callable(PyObject *self, PyObject *v) 182775c6f7640a02841b667fd6300e877bbed574544jimblandy{ 183775c6f7640a02841b667fd6300e877bbed574544jimblandy return PyBool_FromLong((long)PyCallable_Check(v)); 184775c6f7640a02841b667fd6300e877bbed574544jimblandy} 185775c6f7640a02841b667fd6300e877bbed574544jimblandy 186775c6f7640a02841b667fd6300e877bbed574544jimblandyPyDoc_STRVAR(callable_doc, 187775c6f7640a02841b667fd6300e877bbed574544jimblandy"callable(object) -> bool\n\ 188775c6f7640a02841b667fd6300e877bbed574544jimblandy\n\ 189775c6f7640a02841b667fd6300e877bbed574544jimblandyReturn whether the object is callable (i.e., some kind of function).\n\ 190775c6f7640a02841b667fd6300e877bbed574544jimblandyNote that classes are callable, as are instances with a __call__() method."); 191775c6f7640a02841b667fd6300e877bbed574544jimblandy 192775c6f7640a02841b667fd6300e877bbed574544jimblandy 193775c6f7640a02841b667fd6300e877bbed574544jimblandystatic PyObject * 194775c6f7640a02841b667fd6300e877bbed574544jimblandybuiltin_filter(PyObject *self, PyObject *args) 195775c6f7640a02841b667fd6300e877bbed574544jimblandy{ 196f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com PyObject *func, *seq, *result, *it, *arg; 197b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy int len; /* guess for result list size */ 198775c6f7640a02841b667fd6300e877bbed574544jimblandy register int j; 199f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 200f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq)) 201f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com return NULL; 202f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 203f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com /* Strings and tuples return a result of the same type. */ 204b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy if (PyString_Check(seq)) 205b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy return filterstring(func, seq); 206f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com#ifdef Py_USING_UNICODE 207f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (PyUnicode_Check(seq)) 208b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy return filterunicode(func, seq); 209b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy#endif 210f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (PyTuple_Check(seq)) 211f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com return filtertuple(func, seq); 212f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 213f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com /* Pre-allocate argument list tuple. */ 214f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com arg = PyTuple_New(1); 215f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (arg == NULL) 216775c6f7640a02841b667fd6300e877bbed574544jimblandy return NULL; 217775c6f7640a02841b667fd6300e877bbed574544jimblandy 218f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com /* Get iterator. */ 2194fd4efe1c615da174abe42f3ca40662bb50763bfthestig@chromium.org it = PyObject_GetIter(seq); 220f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (it == NULL) 221f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com goto Fail_arg; 222b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy 223f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com /* Guess a result list size. */ 224b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy len = PyObject_Size(seq); 225f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (len < 0) { 226f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (!PyErr_ExceptionMatches(PyExc_TypeError) && 227f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com !PyErr_ExceptionMatches(PyExc_AttributeError)) { 228f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com goto Fail_it; 229f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com } 230f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com PyErr_Clear(); 231f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com len = 8; /* arbitrary */ 2324e518a4357a2d1c379d4a91df6d4e153ee791101ivan.penkov@gmail.com } 233f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 234f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com /* Get a result list. */ 235b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy if (PyList_Check(seq) && seq->ob_refcnt == 1) { 236f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com /* Eww - can modify the list in-place. */ 237775c6f7640a02841b667fd6300e877bbed574544jimblandy Py_INCREF(seq); 238775c6f7640a02841b667fd6300e877bbed574544jimblandy result = seq; 239775c6f7640a02841b667fd6300e877bbed574544jimblandy } 240775c6f7640a02841b667fd6300e877bbed574544jimblandy else { 241775c6f7640a02841b667fd6300e877bbed574544jimblandy result = PyList_New(len); 242775c6f7640a02841b667fd6300e877bbed574544jimblandy if (result == NULL) 243775c6f7640a02841b667fd6300e877bbed574544jimblandy goto Fail_it; 2444fd4efe1c615da174abe42f3ca40662bb50763bfthestig@chromium.org } 245b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy 246b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy /* Build the result list. */ 247f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com j = 0; 248b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy for (;;) { 249f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com PyObject *item; 250f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com int ok; 251b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy 252f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com item = PyIter_Next(it); 253f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (item == NULL) { 254f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com if (PyErr_Occurred()) 255b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy goto Fail_result_it; 256f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com break; 257f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com } 258b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy 259b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy if (func == (PyObject *)&PyBool_Type || func == Py_None) { 260f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com ok = PyObject_IsTrue(item); 261b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy } 262f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com else { 263f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com PyObject *good; 264b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy PyTuple_SET_ITEM(arg, 0, item); 265f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com good = PyObject_Call(func, arg, NULL); 266f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com PyTuple_SET_ITEM(arg, 0, NULL); 267deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy if (good == NULL) { 268deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy Py_DECREF(item); 269f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com goto Fail_result_it; 270b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy } 271b0ec96cee2ab186c9e7e480d03751588f0640bf1jimblandy ok = PyObject_IsTrue(good); 272deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy Py_DECREF(good); 2734fd4efe1c615da174abe42f3ca40662bb50763bfthestig@chromium.org } 2744fd4efe1c615da174abe42f3ca40662bb50763bfthestig@chromium.org if (ok) { 275deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy if (j < len) 276deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy PyList_SET_ITEM(result, j, item); 277deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy else { 278deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy int status = PyList_Append(result, item); 279deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy Py_DECREF(item); 280deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy if (status < 0) 281deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy goto Fail_result_it; 282deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy } 283deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy ++j; 284deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy } 285deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy else 286deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy Py_DECREF(item); 287deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy } 288deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy 289deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy 290deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy /* Cut back result list if len is too big. */ 291deb500f6c85e4eb65218d171dbdbc528df8ebcfejimblandy if (j < len && PyList_SetSlice(result, j, len, NULL) < 0) 292f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com goto Fail_result_it; 293f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 294f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com Py_DECREF(it); 295f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com Py_DECREF(arg); 296f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com return result; 297f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com 298f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.comFail_result_it: 299f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.com Py_DECREF(result); 300bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarekFail_it: 301bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek Py_DECREF(it); 302bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarekFail_arg: 303bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek Py_DECREF(arg); 304bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek return NULL; 305bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek} 306bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek 307bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarekPyDoc_STRVAR(filter_doc, 308bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek"filter(function or None, sequence) -> list, tuple, or string\n" 309bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek"\n" 310bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek"Return those items of sequence for which function(item) is true. If\n" 311bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek"function is None, return the items that are true. If sequence is a tuple\n" 312bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek"or string, return the same type, else return a list."); 313bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarek 314bf25801d837b8fc496bf9c3a34eac525d8a3d8aeted.mielczarekstatic PyObject * 315f7cc9ef6f5bd9bcf455e54f7ad8532001cee7fb0jimblandy@gmail.combuiltin_chr(PyObject *self, PyObject *args) 316{ 317 long x; 318 char s[1]; 319 320 if (!PyArg_ParseTuple(args, "l:chr", &x)) 321 return NULL; 322 if (x < 0 || x >= 256) { 323 PyErr_SetString(PyExc_ValueError, 324 "chr() arg not in range(256)"); 325 return NULL; 326 } 327 s[0] = (char)x; 328 return PyString_FromStringAndSize(s, 1); 329} 330 331PyDoc_STRVAR(chr_doc, 332"chr(i) -> character\n\ 333\n\ 334Return a string of one character with ordinal i; 0 <= i < 256."); 335 336 337#ifdef Py_USING_UNICODE 338static PyObject * 339builtin_unichr(PyObject *self, PyObject *args) 340{ 341 long x; 342 343 if (!PyArg_ParseTuple(args, "l:unichr", &x)) 344 return NULL; 345 346 return PyUnicode_FromOrdinal(x); 347} 348 349PyDoc_STRVAR(unichr_doc, 350"unichr(i) -> Unicode character\n\ 351\n\ 352Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."); 353#endif 354 355 356static PyObject * 357builtin_cmp(PyObject *self, PyObject *args) 358{ 359 PyObject *a, *b; 360 int c; 361 362 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b)) 363 return NULL; 364 if (PyObject_Cmp(a, b, &c) < 0) 365 return NULL; 366 return PyInt_FromLong((long)c); 367} 368 369PyDoc_STRVAR(cmp_doc, 370"cmp(x, y) -> integer\n\ 371\n\ 372Return negative if x<y, zero if x==y, positive if x>y."); 373 374 375static PyObject * 376builtin_coerce(PyObject *self, PyObject *args) 377{ 378 PyObject *v, *w; 379 PyObject *res; 380 381 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w)) 382 return NULL; 383 if (PyNumber_Coerce(&v, &w) < 0) 384 return NULL; 385 res = PyTuple_Pack(2, v, w); 386 Py_DECREF(v); 387 Py_DECREF(w); 388 return res; 389} 390 391PyDoc_STRVAR(coerce_doc, 392"coerce(x, y) -> (x1, y1)\n\ 393\n\ 394Return a tuple consisting of the two numeric arguments converted to\n\ 395a common type, using the same rules as used by arithmetic operations.\n\ 396If coercion is not possible, raise TypeError."); 397 398static PyObject * 399builtin_compile(PyObject *self, PyObject *args) 400{ 401 char *str; 402 char *filename; 403 char *startstr; 404 int start; 405 int dont_inherit = 0; 406 int supplied_flags = 0; 407 PyCompilerFlags cf; 408 PyObject *result, *cmd, *tmp = NULL; 409 int length; 410 411 if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename, 412 &startstr, &supplied_flags, &dont_inherit)) 413 return NULL; 414 415 cf.cf_flags = supplied_flags; 416 417#ifdef Py_USING_UNICODE 418 if (PyUnicode_Check(cmd)) { 419 tmp = PyUnicode_AsUTF8String(cmd); 420 if (tmp == NULL) 421 return NULL; 422 cmd = tmp; 423 cf.cf_flags |= PyCF_SOURCE_IS_UTF8; 424 } 425#endif 426 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length)) 427 return NULL; 428 if ((size_t)length != strlen(str)) { 429 PyErr_SetString(PyExc_TypeError, 430 "compile() expected string without null bytes"); 431 return NULL; 432 } 433 434 if (strcmp(startstr, "exec") == 0) 435 start = Py_file_input; 436 else if (strcmp(startstr, "eval") == 0) 437 start = Py_eval_input; 438 else if (strcmp(startstr, "single") == 0) 439 start = Py_single_input; 440 else { 441 PyErr_SetString(PyExc_ValueError, 442 "compile() arg 3 must be 'exec' or 'eval' or 'single'"); 443 return NULL; 444 } 445 446 if (supplied_flags & 447 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT)) 448 { 449 PyErr_SetString(PyExc_ValueError, 450 "compile(): unrecognised flags"); 451 return NULL; 452 } 453 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ 454 455 if (!dont_inherit) { 456 PyEval_MergeCompilerFlags(&cf); 457 } 458 result = Py_CompileStringFlags(str, filename, start, &cf); 459 Py_XDECREF(tmp); 460 return result; 461} 462 463PyDoc_STRVAR(compile_doc, 464"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\ 465\n\ 466Compile the source string (a Python module, statement or expression)\n\ 467into a code object that can be executed by the exec statement or eval().\n\ 468The filename will be used for run-time error messages.\n\ 469The mode must be 'exec' to compile a module, 'single' to compile a\n\ 470single (interactive) statement, or 'eval' to compile an expression.\n\ 471The flags argument, if present, controls which future statements influence\n\ 472the compilation of the code.\n\ 473The dont_inherit argument, if non-zero, stops the compilation inheriting\n\ 474the effects of any future statements in effect in the code calling\n\ 475compile; if absent or zero these statements do influence the compilation,\n\ 476in addition to any features explicitly specified."); 477 478static PyObject * 479builtin_dir(PyObject *self, PyObject *args) 480{ 481 PyObject *arg = NULL; 482 483 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg)) 484 return NULL; 485 return PyObject_Dir(arg); 486} 487 488PyDoc_STRVAR(dir_doc, 489"dir([object]) -> list of strings\n" 490"\n" 491"Return an alphabetized list of names comprising (some of) the attributes\n" 492"of the given object, and of attributes reachable from it:\n" 493"\n" 494"No argument: the names in the current scope.\n" 495"Module object: the module attributes.\n" 496"Type or class object: its attributes, and recursively the attributes of\n" 497" its bases.\n" 498"Otherwise: its attributes, its class's attributes, and recursively the\n" 499" attributes of its class's base classes."); 500 501static PyObject * 502builtin_divmod(PyObject *self, PyObject *args) 503{ 504 PyObject *v, *w; 505 506 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w)) 507 return NULL; 508 return PyNumber_Divmod(v, w); 509} 510 511PyDoc_STRVAR(divmod_doc, 512"divmod(x, y) -> (div, mod)\n\ 513\n\ 514Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x."); 515 516 517static PyObject * 518builtin_eval(PyObject *self, PyObject *args) 519{ 520 PyObject *cmd, *result, *tmp = NULL; 521 PyObject *globals = Py_None, *locals = Py_None; 522 char *str; 523 PyCompilerFlags cf; 524 525 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals)) 526 return NULL; 527 if (locals != Py_None && !PyMapping_Check(locals)) { 528 PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); 529 return NULL; 530 } 531 if (globals != Py_None && !PyDict_Check(globals)) { 532 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ? 533 "globals must be a real dict; try eval(expr, {}, mapping)" 534 : "globals must be a dict"); 535 return NULL; 536 } 537 if (globals == Py_None) { 538 globals = PyEval_GetGlobals(); 539 if (locals == Py_None) 540 locals = PyEval_GetLocals(); 541 } 542 else if (locals == Py_None) 543 locals = globals; 544 545 if (globals == NULL || locals == NULL) { 546 PyErr_SetString(PyExc_TypeError, 547 "eval must be given globals and locals " 548 "when called without a frame"); 549 return NULL; 550 } 551 552 if (PyDict_GetItemString(globals, "__builtins__") == NULL) { 553 if (PyDict_SetItemString(globals, "__builtins__", 554 PyEval_GetBuiltins()) != 0) 555 return NULL; 556 } 557 558 if (PyCode_Check(cmd)) { 559 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) { 560 PyErr_SetString(PyExc_TypeError, 561 "code object passed to eval() may not contain free variables"); 562 return NULL; 563 } 564 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals); 565 } 566 567 if (!PyString_Check(cmd) && 568 !PyUnicode_Check(cmd)) { 569 PyErr_SetString(PyExc_TypeError, 570 "eval() arg 1 must be a string or code object"); 571 return NULL; 572 } 573 cf.cf_flags = 0; 574 575#ifdef Py_USING_UNICODE 576 if (PyUnicode_Check(cmd)) { 577 tmp = PyUnicode_AsUTF8String(cmd); 578 if (tmp == NULL) 579 return NULL; 580 cmd = tmp; 581 cf.cf_flags |= PyCF_SOURCE_IS_UTF8; 582 } 583#endif 584 if (PyString_AsStringAndSize(cmd, &str, NULL)) 585 return NULL; 586 while (*str == ' ' || *str == '\t') 587 str++; 588 589 (void)PyEval_MergeCompilerFlags(&cf); 590 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); 591 Py_XDECREF(tmp); 592 return result; 593} 594 595PyDoc_STRVAR(eval_doc, 596"eval(source[, globals[, locals]]) -> value\n\ 597\n\ 598Evaluate the source in the context of globals and locals.\n\ 599The source may be a string representing a Python expression\n\ 600or a code object as returned by compile().\n\ 601The globals must be a dictionary and locals can be any mappping,\n\ 602defaulting to the current globals and locals.\n\ 603If only globals is given, locals defaults to it.\n"); 604 605 606static PyObject * 607builtin_execfile(PyObject *self, PyObject *args) 608{ 609 char *filename; 610 PyObject *globals = Py_None, *locals = Py_None; 611 PyObject *res; 612 FILE* fp = NULL; 613 PyCompilerFlags cf; 614 int exists; 615 616 if (!PyArg_ParseTuple(args, "s|O!O:execfile", 617 &filename, 618 &PyDict_Type, &globals, 619 &locals)) 620 return NULL; 621 if (locals != Py_None && !PyMapping_Check(locals)) { 622 PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); 623 return NULL; 624 } 625 if (globals == Py_None) { 626 globals = PyEval_GetGlobals(); 627 if (locals == Py_None) 628 locals = PyEval_GetLocals(); 629 } 630 else if (locals == Py_None) 631 locals = globals; 632 if (PyDict_GetItemString(globals, "__builtins__") == NULL) { 633 if (PyDict_SetItemString(globals, "__builtins__", 634 PyEval_GetBuiltins()) != 0) 635 return NULL; 636 } 637 638 exists = 0; 639 /* Test for existence or directory. */ 640#if defined(PLAN9) 641 { 642 Dir *d; 643 644 if ((d = dirstat(filename))!=nil) { 645 if(d->mode & DMDIR) 646 werrstr("is a directory"); 647 else 648 exists = 1; 649 free(d); 650 } 651 } 652#elif defined(RISCOS) 653 if (object_exists(filename)) { 654 if (isdir(filename)) 655 errno = EISDIR; 656 else 657 exists = 1; 658 } 659#else /* standard Posix */ 660 { 661 struct stat s; 662 if (stat(filename, &s) == 0) { 663 if (S_ISDIR(s.st_mode)) 664# if defined(PYOS_OS2) && defined(PYCC_VACPP) 665 errno = EOS2ERR; 666# else 667 errno = EISDIR; 668# endif 669 else 670 exists = 1; 671 } 672 } 673#endif 674 675 if (exists) { 676 Py_BEGIN_ALLOW_THREADS 677 fp = fopen(filename, "r" PY_STDIOTEXTMODE); 678 Py_END_ALLOW_THREADS 679 680 if (fp == NULL) { 681 exists = 0; 682 } 683 } 684 685 if (!exists) { 686 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename); 687 return NULL; 688 } 689 cf.cf_flags = 0; 690 if (PyEval_MergeCompilerFlags(&cf)) 691 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals, 692 locals, 1, &cf); 693 else 694 res = PyRun_FileEx(fp, filename, Py_file_input, globals, 695 locals, 1); 696 return res; 697} 698 699PyDoc_STRVAR(execfile_doc, 700"execfile(filename[, globals[, locals]])\n\ 701\n\ 702Read and execute a Python script from a file.\n\ 703The globals and locals are dictionaries, defaulting to the current\n\ 704globals and locals. If only globals is given, locals defaults to it."); 705 706 707static PyObject * 708builtin_getattr(PyObject *self, PyObject *args) 709{ 710 PyObject *v, *result, *dflt = NULL; 711 PyObject *name; 712 713 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt)) 714 return NULL; 715#ifdef Py_USING_UNICODE 716 if (PyUnicode_Check(name)) { 717 name = _PyUnicode_AsDefaultEncodedString(name, NULL); 718 if (name == NULL) 719 return NULL; 720 } 721#endif 722 723 if (!PyString_Check(name)) { 724 PyErr_SetString(PyExc_TypeError, 725 "getattr(): attribute name must be string"); 726 return NULL; 727 } 728 result = PyObject_GetAttr(v, name); 729 if (result == NULL && dflt != NULL && 730 PyErr_ExceptionMatches(PyExc_AttributeError)) 731 { 732 PyErr_Clear(); 733 Py_INCREF(dflt); 734 result = dflt; 735 } 736 return result; 737} 738 739PyDoc_STRVAR(getattr_doc, 740"getattr(object, name[, default]) -> value\n\ 741\n\ 742Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\ 743When a default argument is given, it is returned when the attribute doesn't\n\ 744exist; without it, an exception is raised in that case."); 745 746 747static PyObject * 748builtin_globals(PyObject *self) 749{ 750 PyObject *d; 751 752 d = PyEval_GetGlobals(); 753 Py_INCREF(d); 754 return d; 755} 756 757PyDoc_STRVAR(globals_doc, 758"globals() -> dictionary\n\ 759\n\ 760Return the dictionary containing the current scope's global variables."); 761 762 763static PyObject * 764builtin_hasattr(PyObject *self, PyObject *args) 765{ 766 PyObject *v; 767 PyObject *name; 768 769 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name)) 770 return NULL; 771#ifdef Py_USING_UNICODE 772 if (PyUnicode_Check(name)) { 773 name = _PyUnicode_AsDefaultEncodedString(name, NULL); 774 if (name == NULL) 775 return NULL; 776 } 777#endif 778 779 if (!PyString_Check(name)) { 780 PyErr_SetString(PyExc_TypeError, 781 "hasattr(): attribute name must be string"); 782 return NULL; 783 } 784 v = PyObject_GetAttr(v, name); 785 if (v == NULL) { 786 PyErr_Clear(); 787 Py_INCREF(Py_False); 788 return Py_False; 789 } 790 Py_DECREF(v); 791 Py_INCREF(Py_True); 792 return Py_True; 793} 794 795PyDoc_STRVAR(hasattr_doc, 796"hasattr(object, name) -> bool\n\ 797\n\ 798Return whether the object has an attribute with the given name.\n\ 799(This is done by calling getattr(object, name) and catching exceptions.)"); 800 801 802static PyObject * 803builtin_id(PyObject *self, PyObject *v) 804{ 805 return PyLong_FromVoidPtr(v); 806} 807 808PyDoc_STRVAR(id_doc, 809"id(object) -> integer\n\ 810\n\ 811Return the identity of an object. This is guaranteed to be unique among\n\ 812simultaneously existing objects. (Hint: it's the object's memory address.)"); 813 814 815static PyObject * 816builtin_map(PyObject *self, PyObject *args) 817{ 818 typedef struct { 819 PyObject *it; /* the iterator object */ 820 int saw_StopIteration; /* bool: did the iterator end? */ 821 } sequence; 822 823 PyObject *func, *result; 824 sequence *seqs = NULL, *sqp; 825 int n, len; 826 register int i, j; 827 828 n = PyTuple_Size(args); 829 if (n < 2) { 830 PyErr_SetString(PyExc_TypeError, 831 "map() requires at least two args"); 832 return NULL; 833 } 834 835 func = PyTuple_GetItem(args, 0); 836 n--; 837 838 if (func == Py_None && n == 1) { 839 /* map(None, S) is the same as list(S). */ 840 return PySequence_List(PyTuple_GetItem(args, 1)); 841 } 842 843 /* Get space for sequence descriptors. Must NULL out the iterator 844 * pointers so that jumping to Fail_2 later doesn't see trash. 845 */ 846 if ((seqs = PyMem_NEW(sequence, n)) == NULL) { 847 PyErr_NoMemory(); 848 return NULL; 849 } 850 for (i = 0; i < n; ++i) { 851 seqs[i].it = (PyObject*)NULL; 852 seqs[i].saw_StopIteration = 0; 853 } 854 855 /* Do a first pass to obtain iterators for the arguments, and set len 856 * to the largest of their lengths. 857 */ 858 len = 0; 859 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) { 860 PyObject *curseq; 861 int curlen; 862 863 /* Get iterator. */ 864 curseq = PyTuple_GetItem(args, i+1); 865 sqp->it = PyObject_GetIter(curseq); 866 if (sqp->it == NULL) { 867 static char errmsg[] = 868 "argument %d to map() must support iteration"; 869 char errbuf[sizeof(errmsg) + 25]; 870 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2); 871 PyErr_SetString(PyExc_TypeError, errbuf); 872 goto Fail_2; 873 } 874 875 /* Update len. */ 876 curlen = PyObject_Size(curseq); 877 if (curlen < 0) { 878 if (!PyErr_ExceptionMatches(PyExc_TypeError) && 879 !PyErr_ExceptionMatches(PyExc_AttributeError)) { 880 goto Fail_2; 881 } 882 PyErr_Clear(); 883 curlen = 8; /* arbitrary */ 884 } 885 if (curlen > len) 886 len = curlen; 887 } 888 889 /* Get space for the result list. */ 890 if ((result = (PyObject *) PyList_New(len)) == NULL) 891 goto Fail_2; 892 893 /* Iterate over the sequences until all have stopped. */ 894 for (i = 0; ; ++i) { 895 PyObject *alist, *item=NULL, *value; 896 int numactive = 0; 897 898 if (func == Py_None && n == 1) 899 alist = NULL; 900 else if ((alist = PyTuple_New(n)) == NULL) 901 goto Fail_1; 902 903 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) { 904 if (sqp->saw_StopIteration) { 905 Py_INCREF(Py_None); 906 item = Py_None; 907 } 908 else { 909 item = PyIter_Next(sqp->it); 910 if (item) 911 ++numactive; 912 else { 913 if (PyErr_Occurred()) { 914 Py_XDECREF(alist); 915 goto Fail_1; 916 } 917 Py_INCREF(Py_None); 918 item = Py_None; 919 sqp->saw_StopIteration = 1; 920 } 921 } 922 if (alist) 923 PyTuple_SET_ITEM(alist, j, item); 924 else 925 break; 926 } 927 928 if (!alist) 929 alist = item; 930 931 if (numactive == 0) { 932 Py_DECREF(alist); 933 break; 934 } 935 936 if (func == Py_None) 937 value = alist; 938 else { 939 value = PyEval_CallObject(func, alist); 940 Py_DECREF(alist); 941 if (value == NULL) 942 goto Fail_1; 943 } 944 if (i >= len) { 945 int status = PyList_Append(result, value); 946 Py_DECREF(value); 947 if (status < 0) 948 goto Fail_1; 949 } 950 else if (PyList_SetItem(result, i, value) < 0) 951 goto Fail_1; 952 } 953 954 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0) 955 goto Fail_1; 956 957 goto Succeed; 958 959Fail_1: 960 Py_DECREF(result); 961Fail_2: 962 result = NULL; 963Succeed: 964 assert(seqs); 965 for (i = 0; i < n; ++i) 966 Py_XDECREF(seqs[i].it); 967 PyMem_DEL(seqs); 968 return result; 969} 970 971PyDoc_STRVAR(map_doc, 972"map(function, sequence[, sequence, ...]) -> list\n\ 973\n\ 974Return a list of the results of applying the function to the items of\n\ 975the argument sequence(s). If more than one sequence is given, the\n\ 976function is called with an argument list consisting of the corresponding\n\ 977item of each sequence, substituting None for missing values when not all\n\ 978sequences have the same length. If the function is None, return a list of\n\ 979the items of the sequence (or a list of tuples if more than one sequence)."); 980 981 982static PyObject * 983builtin_setattr(PyObject *self, PyObject *args) 984{ 985 PyObject *v; 986 PyObject *name; 987 PyObject *value; 988 989 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value)) 990 return NULL; 991 if (PyObject_SetAttr(v, name, value) != 0) 992 return NULL; 993 Py_INCREF(Py_None); 994 return Py_None; 995} 996 997PyDoc_STRVAR(setattr_doc, 998"setattr(object, name, value)\n\ 999\n\ 1000Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\ 1001``x.y = v''."); 1002 1003 1004static PyObject * 1005builtin_delattr(PyObject *self, PyObject *args) 1006{ 1007 PyObject *v; 1008 PyObject *name; 1009 1010 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name)) 1011 return NULL; 1012 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) 1013 return NULL; 1014 Py_INCREF(Py_None); 1015 return Py_None; 1016} 1017 1018PyDoc_STRVAR(delattr_doc, 1019"delattr(object, name)\n\ 1020\n\ 1021Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\ 1022``del x.y''."); 1023 1024 1025static PyObject * 1026builtin_hash(PyObject *self, PyObject *v) 1027{ 1028 long x; 1029 1030 x = PyObject_Hash(v); 1031 if (x == -1) 1032 return NULL; 1033 return PyInt_FromLong(x); 1034} 1035 1036PyDoc_STRVAR(hash_doc, 1037"hash(object) -> integer\n\ 1038\n\ 1039Return a hash value for the object. Two objects with the same value have\n\ 1040the same hash value. The reverse is not necessarily true, but likely."); 1041 1042 1043static PyObject * 1044builtin_hex(PyObject *self, PyObject *v) 1045{ 1046 PyNumberMethods *nb; 1047 PyObject *res; 1048 1049 if ((nb = v->ob_type->tp_as_number) == NULL || 1050 nb->nb_hex == NULL) { 1051 PyErr_SetString(PyExc_TypeError, 1052 "hex() argument can't be converted to hex"); 1053 return NULL; 1054 } 1055 res = (*nb->nb_hex)(v); 1056 if (res && !PyString_Check(res)) { 1057 PyErr_Format(PyExc_TypeError, 1058 "__hex__ returned non-string (type %.200s)", 1059 res->ob_type->tp_name); 1060 Py_DECREF(res); 1061 return NULL; 1062 } 1063 return res; 1064} 1065 1066PyDoc_STRVAR(hex_doc, 1067"hex(number) -> string\n\ 1068\n\ 1069Return the hexadecimal representation of an integer or long integer."); 1070 1071 1072static PyObject *builtin_raw_input(PyObject *, PyObject *); 1073 1074static PyObject * 1075builtin_input(PyObject *self, PyObject *args) 1076{ 1077 PyObject *line; 1078 char *str; 1079 PyObject *res; 1080 PyObject *globals, *locals; 1081 PyCompilerFlags cf; 1082 1083 line = builtin_raw_input(self, args); 1084 if (line == NULL) 1085 return line; 1086 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str)) 1087 return NULL; 1088 while (*str == ' ' || *str == '\t') 1089 str++; 1090 globals = PyEval_GetGlobals(); 1091 locals = PyEval_GetLocals(); 1092 if (PyDict_GetItemString(globals, "__builtins__") == NULL) { 1093 if (PyDict_SetItemString(globals, "__builtins__", 1094 PyEval_GetBuiltins()) != 0) 1095 return NULL; 1096 } 1097 cf.cf_flags = 0; 1098 PyEval_MergeCompilerFlags(&cf); 1099 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); 1100 Py_DECREF(line); 1101 return res; 1102} 1103 1104PyDoc_STRVAR(input_doc, 1105"input([prompt]) -> value\n\ 1106\n\ 1107Equivalent to eval(raw_input(prompt))."); 1108 1109 1110static PyObject * 1111builtin_intern(PyObject *self, PyObject *args) 1112{ 1113 PyObject *s; 1114 if (!PyArg_ParseTuple(args, "S:intern", &s)) 1115 return NULL; 1116 if (!PyString_CheckExact(s)) { 1117 PyErr_SetString(PyExc_TypeError, 1118 "can't intern subclass of string"); 1119 return NULL; 1120 } 1121 Py_INCREF(s); 1122 PyString_InternInPlace(&s); 1123 return s; 1124} 1125 1126PyDoc_STRVAR(intern_doc, 1127"intern(string) -> string\n\ 1128\n\ 1129``Intern'' the given string. This enters the string in the (global)\n\ 1130table of interned strings whose purpose is to speed up dictionary lookups.\n\ 1131Return the string itself or the previously interned string object with the\n\ 1132same value."); 1133 1134 1135static PyObject * 1136builtin_iter(PyObject *self, PyObject *args) 1137{ 1138 PyObject *v, *w = NULL; 1139 1140 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w)) 1141 return NULL; 1142 if (w == NULL) 1143 return PyObject_GetIter(v); 1144 if (!PyCallable_Check(v)) { 1145 PyErr_SetString(PyExc_TypeError, 1146 "iter(v, w): v must be callable"); 1147 return NULL; 1148 } 1149 return PyCallIter_New(v, w); 1150} 1151 1152PyDoc_STRVAR(iter_doc, 1153"iter(collection) -> iterator\n\ 1154iter(callable, sentinel) -> iterator\n\ 1155\n\ 1156Get an iterator from an object. In the first form, the argument must\n\ 1157supply its own iterator, or be a sequence.\n\ 1158In the second form, the callable is called until it returns the sentinel."); 1159 1160 1161static PyObject * 1162builtin_len(PyObject *self, PyObject *v) 1163{ 1164 long res; 1165 1166 res = PyObject_Size(v); 1167 if (res < 0 && PyErr_Occurred()) 1168 return NULL; 1169 return PyInt_FromLong(res); 1170} 1171 1172PyDoc_STRVAR(len_doc, 1173"len(object) -> integer\n\ 1174\n\ 1175Return the number of items of a sequence or mapping."); 1176 1177 1178static PyObject * 1179builtin_locals(PyObject *self) 1180{ 1181 PyObject *d; 1182 1183 d = PyEval_GetLocals(); 1184 Py_INCREF(d); 1185 return d; 1186} 1187 1188PyDoc_STRVAR(locals_doc, 1189"locals() -> dictionary\n\ 1190\n\ 1191Update and return a dictionary containing the current scope's local variables."); 1192 1193 1194static PyObject * 1195min_max(PyObject *args, PyObject *kwds, int op) 1196{ 1197 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL; 1198 const char *name = op == Py_LT ? "min" : "max"; 1199 1200 if (PyTuple_Size(args) > 1) 1201 v = args; 1202 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v)) 1203 return NULL; 1204 1205 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) { 1206 keyfunc = PyDict_GetItemString(kwds, "key"); 1207 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) { 1208 PyErr_Format(PyExc_TypeError, 1209 "%s() got an unexpected keyword argument", name); 1210 return NULL; 1211 } 1212 } 1213 1214 it = PyObject_GetIter(v); 1215 if (it == NULL) 1216 return NULL; 1217 1218 maxitem = NULL; /* the result */ 1219 maxval = NULL; /* the value associated with the result */ 1220 while (( item = PyIter_Next(it) )) { 1221 /* get the value from the key function */ 1222 if (keyfunc != NULL) { 1223 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); 1224 if (val == NULL) 1225 goto Fail_it_item; 1226 } 1227 /* no key function; the value is the item */ 1228 else { 1229 val = item; 1230 Py_INCREF(val); 1231 } 1232 1233 /* maximum value and item are unset; set them */ 1234 if (maxval == NULL) { 1235 maxitem = item; 1236 maxval = val; 1237 } 1238 /* maximum value and item are set; update them as necessary */ 1239 else { 1240 int cmp = PyObject_RichCompareBool(val, maxval, op); 1241 if (cmp < 0) 1242 goto Fail_it_item_and_val; 1243 else if (cmp > 0) { 1244 Py_DECREF(maxval); 1245 Py_DECREF(maxitem); 1246 maxval = val; 1247 maxitem = item; 1248 } 1249 else { 1250 Py_DECREF(item); 1251 Py_DECREF(val); 1252 } 1253 } 1254 } 1255 if (PyErr_Occurred()) 1256 goto Fail_it; 1257 if (maxval == NULL) { 1258 PyErr_Format(PyExc_ValueError, 1259 "%s() arg is an empty sequence", name); 1260 assert(maxitem == NULL); 1261 } 1262 else 1263 Py_DECREF(maxval); 1264 Py_DECREF(it); 1265 return maxitem; 1266 1267Fail_it_item_and_val: 1268 Py_DECREF(val); 1269Fail_it_item: 1270 Py_DECREF(item); 1271Fail_it: 1272 Py_XDECREF(maxval); 1273 Py_XDECREF(maxitem); 1274 Py_DECREF(it); 1275 return NULL; 1276} 1277 1278static PyObject * 1279builtin_min(PyObject *self, PyObject *args, PyObject *kwds) 1280{ 1281 return min_max(args, kwds, Py_LT); 1282} 1283 1284PyDoc_STRVAR(min_doc, 1285"min(iterable[, key=func]) -> value\n\ 1286min(a, b, c, ...[, key=func]) -> value\n\ 1287\n\ 1288With a single iterable argument, return its smallest item.\n\ 1289With two or more arguments, return the smallest argument."); 1290 1291 1292static PyObject * 1293builtin_max(PyObject *self, PyObject *args, PyObject *kwds) 1294{ 1295 return min_max(args, kwds, Py_GT); 1296} 1297 1298PyDoc_STRVAR(max_doc, 1299"max(iterable[, key=func]) -> value\n\ 1300max(a, b, c, ...[, key=func]) -> value\n\ 1301\n\ 1302With a single iterable argument, return its largest item.\n\ 1303With two or more arguments, return the largest argument."); 1304 1305 1306static PyObject * 1307builtin_oct(PyObject *self, PyObject *v) 1308{ 1309 PyNumberMethods *nb; 1310 PyObject *res; 1311 1312 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL || 1313 nb->nb_oct == NULL) { 1314 PyErr_SetString(PyExc_TypeError, 1315 "oct() argument can't be converted to oct"); 1316 return NULL; 1317 } 1318 res = (*nb->nb_oct)(v); 1319 if (res && !PyString_Check(res)) { 1320 PyErr_Format(PyExc_TypeError, 1321 "__oct__ returned non-string (type %.200s)", 1322 res->ob_type->tp_name); 1323 Py_DECREF(res); 1324 return NULL; 1325 } 1326 return res; 1327} 1328 1329PyDoc_STRVAR(oct_doc, 1330"oct(number) -> string\n\ 1331\n\ 1332Return the octal representation of an integer or long integer."); 1333 1334 1335static PyObject * 1336builtin_ord(PyObject *self, PyObject* obj) 1337{ 1338 long ord; 1339 int size; 1340 1341 if (PyString_Check(obj)) { 1342 size = PyString_GET_SIZE(obj); 1343 if (size == 1) { 1344 ord = (long)((unsigned char)*PyString_AS_STRING(obj)); 1345 return PyInt_FromLong(ord); 1346 } 1347#ifdef Py_USING_UNICODE 1348 } else if (PyUnicode_Check(obj)) { 1349 size = PyUnicode_GET_SIZE(obj); 1350 if (size == 1) { 1351 ord = (long)*PyUnicode_AS_UNICODE(obj); 1352 return PyInt_FromLong(ord); 1353 } 1354#endif 1355 } else { 1356 PyErr_Format(PyExc_TypeError, 1357 "ord() expected string of length 1, but " \ 1358 "%.200s found", obj->ob_type->tp_name); 1359 return NULL; 1360 } 1361 1362 PyErr_Format(PyExc_TypeError, 1363 "ord() expected a character, " 1364 "but string of length %d found", 1365 size); 1366 return NULL; 1367} 1368 1369PyDoc_STRVAR(ord_doc, 1370"ord(c) -> integer\n\ 1371\n\ 1372Return the integer ordinal of a one-character string."); 1373 1374 1375static PyObject * 1376builtin_pow(PyObject *self, PyObject *args) 1377{ 1378 PyObject *v, *w, *z = Py_None; 1379 1380 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z)) 1381 return NULL; 1382 return PyNumber_Power(v, w, z); 1383} 1384 1385PyDoc_STRVAR(pow_doc, 1386"pow(x, y[, z]) -> number\n\ 1387\n\ 1388With two arguments, equivalent to x**y. With three arguments,\n\ 1389equivalent to (x**y) % z, but may be more efficient (e.g. for longs)."); 1390 1391 1392 1393/* Return number of items in range (lo, hi, step), when arguments are 1394 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if 1395 * & only if the true value is too large to fit in a signed long. 1396 * Arguments MUST return 1 with either PyInt_Check() or 1397 * PyLong_Check(). Return -1 when there is an error. 1398 */ 1399static long 1400get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step) 1401{ 1402 /* ------------------------------------------------------------- 1403 Algorithm is equal to that of get_len_of_range(), but it operates 1404 on PyObjects (which are assumed to be PyLong or PyInt objects). 1405 ---------------------------------------------------------------*/ 1406 long n; 1407 PyObject *diff = NULL; 1408 PyObject *one = NULL; 1409 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL; 1410 /* holds sub-expression evaluations */ 1411 1412 /* if (lo >= hi), return length of 0. */ 1413 if (PyObject_Compare(lo, hi) >= 0) 1414 return 0; 1415 1416 if ((one = PyLong_FromLong(1L)) == NULL) 1417 goto Fail; 1418 1419 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL) 1420 goto Fail; 1421 1422 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL) 1423 goto Fail; 1424 1425 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL) 1426 goto Fail; 1427 1428 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL) 1429 goto Fail; 1430 1431 n = PyLong_AsLong(tmp3); 1432 if (PyErr_Occurred()) { /* Check for Overflow */ 1433 PyErr_Clear(); 1434 goto Fail; 1435 } 1436 1437 Py_DECREF(tmp3); 1438 Py_DECREF(tmp2); 1439 Py_DECREF(diff); 1440 Py_DECREF(tmp1); 1441 Py_DECREF(one); 1442 return n; 1443 1444 Fail: 1445 Py_XDECREF(tmp3); 1446 Py_XDECREF(tmp2); 1447 Py_XDECREF(diff); 1448 Py_XDECREF(tmp1); 1449 Py_XDECREF(one); 1450 return -1; 1451} 1452 1453/* An extension of builtin_range() that handles the case when PyLong 1454 * arguments are given. */ 1455static PyObject * 1456handle_range_longs(PyObject *self, PyObject *args) 1457{ 1458 PyObject *ilow; 1459 PyObject *ihigh = NULL; 1460 PyObject *istep = NULL; 1461 1462 PyObject *curnum = NULL; 1463 PyObject *v = NULL; 1464 long bign; 1465 int i, n; 1466 int cmp_result; 1467 1468 PyObject *zero = PyLong_FromLong(0); 1469 1470 if (zero == NULL) 1471 return NULL; 1472 1473 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) { 1474 Py_DECREF(zero); 1475 return NULL; 1476 } 1477 1478 /* Figure out which way we were called, supply defaults, and be 1479 * sure to incref everything so that the decrefs at the end 1480 * are correct. 1481 */ 1482 assert(ilow != NULL); 1483 if (ihigh == NULL) { 1484 /* only 1 arg -- it's the upper limit */ 1485 ihigh = ilow; 1486 ilow = NULL; 1487 } 1488 assert(ihigh != NULL); 1489 Py_INCREF(ihigh); 1490 1491 /* ihigh correct now; do ilow */ 1492 if (ilow == NULL) 1493 ilow = zero; 1494 Py_INCREF(ilow); 1495 1496 /* ilow and ihigh correct now; do istep */ 1497 if (istep == NULL) { 1498 istep = PyLong_FromLong(1L); 1499 if (istep == NULL) 1500 goto Fail; 1501 } 1502 else { 1503 Py_INCREF(istep); 1504 } 1505 1506 if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) { 1507 PyErr_Format(PyExc_TypeError, 1508 "range() integer start argument expected, got %s.", 1509 ilow->ob_type->tp_name); 1510 goto Fail; 1511 } 1512 1513 if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) { 1514 PyErr_Format(PyExc_TypeError, 1515 "range() integer end argument expected, got %s.", 1516 ihigh->ob_type->tp_name); 1517 goto Fail; 1518 } 1519 1520 if (!PyInt_Check(istep) && !PyLong_Check(istep)) { 1521 PyErr_Format(PyExc_TypeError, 1522 "range() integer step argument expected, got %s.", 1523 istep->ob_type->tp_name); 1524 goto Fail; 1525 } 1526 1527 if (PyObject_Cmp(istep, zero, &cmp_result) == -1) 1528 goto Fail; 1529 if (cmp_result == 0) { 1530 PyErr_SetString(PyExc_ValueError, 1531 "range() step argument must not be zero"); 1532 goto Fail; 1533 } 1534 1535 if (cmp_result > 0) 1536 bign = get_len_of_range_longs(ilow, ihigh, istep); 1537 else { 1538 PyObject *neg_istep = PyNumber_Negative(istep); 1539 if (neg_istep == NULL) 1540 goto Fail; 1541 bign = get_len_of_range_longs(ihigh, ilow, neg_istep); 1542 Py_DECREF(neg_istep); 1543 } 1544 1545 n = (int)bign; 1546 if (bign < 0 || (long)n != bign) { 1547 PyErr_SetString(PyExc_OverflowError, 1548 "range() result has too many items"); 1549 goto Fail; 1550 } 1551 1552 v = PyList_New(n); 1553 if (v == NULL) 1554 goto Fail; 1555 1556 curnum = ilow; 1557 Py_INCREF(curnum); 1558 1559 for (i = 0; i < n; i++) { 1560 PyObject *w = PyNumber_Long(curnum); 1561 PyObject *tmp_num; 1562 if (w == NULL) 1563 goto Fail; 1564 1565 PyList_SET_ITEM(v, i, w); 1566 1567 tmp_num = PyNumber_Add(curnum, istep); 1568 if (tmp_num == NULL) 1569 goto Fail; 1570 1571 Py_DECREF(curnum); 1572 curnum = tmp_num; 1573 } 1574 Py_DECREF(ilow); 1575 Py_DECREF(ihigh); 1576 Py_DECREF(istep); 1577 Py_DECREF(zero); 1578 Py_DECREF(curnum); 1579 return v; 1580 1581 Fail: 1582 Py_DECREF(ilow); 1583 Py_DECREF(ihigh); 1584 Py_XDECREF(istep); 1585 Py_DECREF(zero); 1586 Py_XDECREF(curnum); 1587 Py_XDECREF(v); 1588 return NULL; 1589} 1590 1591/* Return number of items in range/xrange (lo, hi, step). step > 0 1592 * required. Return a value < 0 if & only if the true value is too 1593 * large to fit in a signed long. 1594 */ 1595static long 1596get_len_of_range(long lo, long hi, long step) 1597{ 1598 /* ------------------------------------------------------------- 1599 If lo >= hi, the range is empty. 1600 Else if n values are in the range, the last one is 1601 lo + (n-1)*step, which must be <= hi-1. Rearranging, 1602 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives 1603 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so 1604 the RHS is non-negative and so truncation is the same as the 1605 floor. Letting M be the largest positive long, the worst case 1606 for the RHS numerator is hi=M, lo=-M-1, and then 1607 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough 1608 precision to compute the RHS exactly. 1609 ---------------------------------------------------------------*/ 1610 long n = 0; 1611 if (lo < hi) { 1612 unsigned long uhi = (unsigned long)hi; 1613 unsigned long ulo = (unsigned long)lo; 1614 unsigned long diff = uhi - ulo - 1; 1615 n = (long)(diff / (unsigned long)step + 1); 1616 } 1617 return n; 1618} 1619 1620static PyObject * 1621builtin_range(PyObject *self, PyObject *args) 1622{ 1623 long ilow = 0, ihigh = 0, istep = 1; 1624 long bign; 1625 int i, n; 1626 1627 PyObject *v; 1628 1629 if (PyTuple_Size(args) <= 1) { 1630 if (!PyArg_ParseTuple(args, 1631 "l;range() requires 1-3 int arguments", 1632 &ihigh)) { 1633 PyErr_Clear(); 1634 return handle_range_longs(self, args); 1635 } 1636 } 1637 else { 1638 if (!PyArg_ParseTuple(args, 1639 "ll|l;range() requires 1-3 int arguments", 1640 &ilow, &ihigh, &istep)) { 1641 PyErr_Clear(); 1642 return handle_range_longs(self, args); 1643 } 1644 } 1645 if (istep == 0) { 1646 PyErr_SetString(PyExc_ValueError, 1647 "range() step argument must not be zero"); 1648 return NULL; 1649 } 1650 if (istep > 0) 1651 bign = get_len_of_range(ilow, ihigh, istep); 1652 else 1653 bign = get_len_of_range(ihigh, ilow, -istep); 1654 n = (int)bign; 1655 if (bign < 0 || (long)n != bign) { 1656 PyErr_SetString(PyExc_OverflowError, 1657 "range() result has too many items"); 1658 return NULL; 1659 } 1660 v = PyList_New(n); 1661 if (v == NULL) 1662 return NULL; 1663 for (i = 0; i < n; i++) { 1664 PyObject *w = PyInt_FromLong(ilow); 1665 if (w == NULL) { 1666 Py_DECREF(v); 1667 return NULL; 1668 } 1669 PyList_SET_ITEM(v, i, w); 1670 ilow += istep; 1671 } 1672 return v; 1673} 1674 1675PyDoc_STRVAR(range_doc, 1676"range([start,] stop[, step]) -> list of integers\n\ 1677\n\ 1678Return a list containing an arithmetic progression of integers.\n\ 1679range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\ 1680When step is given, it specifies the increment (or decrement).\n\ 1681For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\ 1682These are exactly the valid indices for a list of 4 elements."); 1683 1684 1685static PyObject * 1686builtin_raw_input(PyObject *self, PyObject *args) 1687{ 1688 PyObject *v = NULL; 1689 PyObject *fin = PySys_GetObject("stdin"); 1690 PyObject *fout = PySys_GetObject("stdout"); 1691 1692 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v)) 1693 return NULL; 1694 1695 if (fin == NULL) { 1696 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin"); 1697 return NULL; 1698 } 1699 if (fout == NULL) { 1700 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout"); 1701 return NULL; 1702 } 1703 if (PyFile_SoftSpace(fout, 0)) { 1704 if (PyFile_WriteString(" ", fout) != 0) 1705 return NULL; 1706 } 1707 if (PyFile_Check(fin) && PyFile_Check(fout) 1708 && isatty(fileno(PyFile_AsFile(fin))) 1709 && isatty(fileno(PyFile_AsFile(fout)))) { 1710 PyObject *po; 1711 char *prompt; 1712 char *s; 1713 PyObject *result; 1714 if (v != NULL) { 1715 po = PyObject_Str(v); 1716 if (po == NULL) 1717 return NULL; 1718 prompt = PyString_AsString(po); 1719 if (prompt == NULL) 1720 return NULL; 1721 } 1722 else { 1723 po = NULL; 1724 prompt = ""; 1725 } 1726 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout), 1727 prompt); 1728 Py_XDECREF(po); 1729 if (s == NULL) { 1730 if (!PyErr_Occurred()) 1731 PyErr_SetNone(PyExc_KeyboardInterrupt); 1732 return NULL; 1733 } 1734 if (*s == '\0') { 1735 PyErr_SetNone(PyExc_EOFError); 1736 result = NULL; 1737 } 1738 else { /* strip trailing '\n' */ 1739 size_t len = strlen(s); 1740 if (len > INT_MAX) { 1741 PyErr_SetString(PyExc_OverflowError, 1742 "[raw_]input: input too long"); 1743 result = NULL; 1744 } 1745 else { 1746 result = PyString_FromStringAndSize(s, 1747 (int)(len-1)); 1748 } 1749 } 1750 PyMem_FREE(s); 1751 return result; 1752 } 1753 if (v != NULL) { 1754 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0) 1755 return NULL; 1756 } 1757 return PyFile_GetLine(fin, -1); 1758} 1759 1760PyDoc_STRVAR(raw_input_doc, 1761"raw_input([prompt]) -> string\n\ 1762\n\ 1763Read a string from standard input. The trailing newline is stripped.\n\ 1764If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\ 1765On Unix, GNU readline is used if enabled. The prompt string, if given,\n\ 1766is printed without a trailing newline before reading."); 1767 1768 1769static PyObject * 1770builtin_reduce(PyObject *self, PyObject *args) 1771{ 1772 PyObject *seq, *func, *result = NULL, *it; 1773 1774 if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result)) 1775 return NULL; 1776 if (result != NULL) 1777 Py_INCREF(result); 1778 1779 it = PyObject_GetIter(seq); 1780 if (it == NULL) { 1781 PyErr_SetString(PyExc_TypeError, 1782 "reduce() arg 2 must support iteration"); 1783 Py_XDECREF(result); 1784 return NULL; 1785 } 1786 1787 if ((args = PyTuple_New(2)) == NULL) 1788 goto Fail; 1789 1790 for (;;) { 1791 PyObject *op2; 1792 1793 if (args->ob_refcnt > 1) { 1794 Py_DECREF(args); 1795 if ((args = PyTuple_New(2)) == NULL) 1796 goto Fail; 1797 } 1798 1799 op2 = PyIter_Next(it); 1800 if (op2 == NULL) { 1801 if (PyErr_Occurred()) 1802 goto Fail; 1803 break; 1804 } 1805 1806 if (result == NULL) 1807 result = op2; 1808 else { 1809 PyTuple_SetItem(args, 0, result); 1810 PyTuple_SetItem(args, 1, op2); 1811 if ((result = PyEval_CallObject(func, args)) == NULL) 1812 goto Fail; 1813 } 1814 } 1815 1816 Py_DECREF(args); 1817 1818 if (result == NULL) 1819 PyErr_SetString(PyExc_TypeError, 1820 "reduce() of empty sequence with no initial value"); 1821 1822 Py_DECREF(it); 1823 return result; 1824 1825Fail: 1826 Py_XDECREF(args); 1827 Py_XDECREF(result); 1828 Py_DECREF(it); 1829 return NULL; 1830} 1831 1832PyDoc_STRVAR(reduce_doc, 1833"reduce(function, sequence[, initial]) -> value\n\ 1834\n\ 1835Apply a function of two arguments cumulatively to the items of a sequence,\n\ 1836from left to right, so as to reduce the sequence to a single value.\n\ 1837For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\ 1838((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\ 1839of the sequence in the calculation, and serves as a default when the\n\ 1840sequence is empty."); 1841 1842 1843static PyObject * 1844builtin_reload(PyObject *self, PyObject *v) 1845{ 1846 return PyImport_ReloadModule(v); 1847} 1848 1849PyDoc_STRVAR(reload_doc, 1850"reload(module) -> module\n\ 1851\n\ 1852Reload the module. The module must have been successfully imported before."); 1853 1854 1855static PyObject * 1856builtin_repr(PyObject *self, PyObject *v) 1857{ 1858 return PyObject_Repr(v); 1859} 1860 1861PyDoc_STRVAR(repr_doc, 1862"repr(object) -> string\n\ 1863\n\ 1864Return the canonical string representation of the object.\n\ 1865For most object types, eval(repr(object)) == object."); 1866 1867 1868static PyObject * 1869builtin_round(PyObject *self, PyObject *args) 1870{ 1871 double x; 1872 double f; 1873 int ndigits = 0; 1874 int i; 1875 1876 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits)) 1877 return NULL; 1878 f = 1.0; 1879 i = abs(ndigits); 1880 while (--i >= 0) 1881 f = f*10.0; 1882 if (ndigits < 0) 1883 x /= f; 1884 else 1885 x *= f; 1886 if (x >= 0.0) 1887 x = floor(x + 0.5); 1888 else 1889 x = ceil(x - 0.5); 1890 if (ndigits < 0) 1891 x *= f; 1892 else 1893 x /= f; 1894 return PyFloat_FromDouble(x); 1895} 1896 1897PyDoc_STRVAR(round_doc, 1898"round(number[, ndigits]) -> floating point number\n\ 1899\n\ 1900Round a number to a given precision in decimal digits (default 0 digits).\n\ 1901This always returns a floating point number. Precision may be negative."); 1902 1903static PyObject * 1904builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds) 1905{ 1906 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs; 1907 PyObject *callable; 1908 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0}; 1909 long reverse; 1910 1911 if (args != NULL) { 1912 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted", 1913 kwlist, &seq, &compare, &keyfunc, &reverse)) 1914 return NULL; 1915 } 1916 1917 newlist = PySequence_List(seq); 1918 if (newlist == NULL) 1919 return NULL; 1920 1921 callable = PyObject_GetAttrString(newlist, "sort"); 1922 if (callable == NULL) { 1923 Py_DECREF(newlist); 1924 return NULL; 1925 } 1926 1927 newargs = PyTuple_GetSlice(args, 1, 4); 1928 if (newargs == NULL) { 1929 Py_DECREF(newlist); 1930 Py_DECREF(callable); 1931 return NULL; 1932 } 1933 1934 v = PyObject_Call(callable, newargs, kwds); 1935 Py_DECREF(newargs); 1936 Py_DECREF(callable); 1937 if (v == NULL) { 1938 Py_DECREF(newlist); 1939 return NULL; 1940 } 1941 Py_DECREF(v); 1942 return newlist; 1943} 1944 1945PyDoc_STRVAR(sorted_doc, 1946"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list"); 1947 1948static PyObject * 1949builtin_vars(PyObject *self, PyObject *args) 1950{ 1951 PyObject *v = NULL; 1952 PyObject *d; 1953 1954 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v)) 1955 return NULL; 1956 if (v == NULL) { 1957 d = PyEval_GetLocals(); 1958 if (d == NULL) { 1959 if (!PyErr_Occurred()) 1960 PyErr_SetString(PyExc_SystemError, 1961 "vars(): no locals!?"); 1962 } 1963 else 1964 Py_INCREF(d); 1965 } 1966 else { 1967 d = PyObject_GetAttrString(v, "__dict__"); 1968 if (d == NULL) { 1969 PyErr_SetString(PyExc_TypeError, 1970 "vars() argument must have __dict__ attribute"); 1971 return NULL; 1972 } 1973 } 1974 return d; 1975} 1976 1977PyDoc_STRVAR(vars_doc, 1978"vars([object]) -> dictionary\n\ 1979\n\ 1980Without arguments, equivalent to locals().\n\ 1981With an argument, equivalent to object.__dict__."); 1982 1983 1984static PyObject* 1985builtin_sum(PyObject *self, PyObject *args) 1986{ 1987 PyObject *seq; 1988 PyObject *result = NULL; 1989 PyObject *temp, *item, *iter; 1990 1991 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result)) 1992 return NULL; 1993 1994 iter = PyObject_GetIter(seq); 1995 if (iter == NULL) 1996 return NULL; 1997 1998 if (result == NULL) { 1999 result = PyInt_FromLong(0); 2000 if (result == NULL) { 2001 Py_DECREF(iter); 2002 return NULL; 2003 } 2004 } else { 2005 /* reject string values for 'start' parameter */ 2006 if (PyObject_TypeCheck(result, &PyBaseString_Type)) { 2007 PyErr_SetString(PyExc_TypeError, 2008 "sum() can't sum strings [use ''.join(seq) instead]"); 2009 Py_DECREF(iter); 2010 return NULL; 2011 } 2012 Py_INCREF(result); 2013 } 2014 2015 for(;;) { 2016 item = PyIter_Next(iter); 2017 if (item == NULL) { 2018 /* error, or end-of-sequence */ 2019 if (PyErr_Occurred()) { 2020 Py_DECREF(result); 2021 result = NULL; 2022 } 2023 break; 2024 } 2025 temp = PyNumber_Add(result, item); 2026 Py_DECREF(result); 2027 Py_DECREF(item); 2028 result = temp; 2029 if (result == NULL) 2030 break; 2031 } 2032 Py_DECREF(iter); 2033 return result; 2034} 2035 2036PyDoc_STRVAR(sum_doc, 2037"sum(sequence, start=0) -> value\n\ 2038\n\ 2039Returns the sum of a sequence of numbers (NOT strings) plus the value\n\ 2040of parameter 'start'. When the sequence is empty, returns start."); 2041 2042 2043static PyObject * 2044builtin_isinstance(PyObject *self, PyObject *args) 2045{ 2046 PyObject *inst; 2047 PyObject *cls; 2048 int retval; 2049 2050 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls)) 2051 return NULL; 2052 2053 retval = PyObject_IsInstance(inst, cls); 2054 if (retval < 0) 2055 return NULL; 2056 return PyBool_FromLong(retval); 2057} 2058 2059PyDoc_STRVAR(isinstance_doc, 2060"isinstance(object, class-or-type-or-tuple) -> bool\n\ 2061\n\ 2062Return whether an object is an instance of a class or of a subclass thereof.\n\ 2063With a type as second argument, return whether that is the object's type.\n\ 2064The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\ 2065isinstance(x, A) or isinstance(x, B) or ... (etc.)."); 2066 2067 2068static PyObject * 2069builtin_issubclass(PyObject *self, PyObject *args) 2070{ 2071 PyObject *derived; 2072 PyObject *cls; 2073 int retval; 2074 2075 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls)) 2076 return NULL; 2077 2078 retval = PyObject_IsSubclass(derived, cls); 2079 if (retval < 0) 2080 return NULL; 2081 return PyBool_FromLong(retval); 2082} 2083 2084PyDoc_STRVAR(issubclass_doc, 2085"issubclass(C, B) -> bool\n\ 2086\n\ 2087Return whether class C is a subclass (i.e., a derived class) of class B.\n\ 2088When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\ 2089is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.)."); 2090 2091 2092static PyObject* 2093builtin_zip(PyObject *self, PyObject *args) 2094{ 2095 PyObject *ret; 2096 const int itemsize = PySequence_Length(args); 2097 int i; 2098 PyObject *itlist; /* tuple of iterators */ 2099 int len; /* guess at result length */ 2100 2101 if (itemsize == 0) 2102 return PyList_New(0); 2103 2104 /* args must be a tuple */ 2105 assert(PyTuple_Check(args)); 2106 2107 /* Guess at result length: the shortest of the input lengths. 2108 If some argument refuses to say, we refuse to guess too, lest 2109 an argument like xrange(sys.maxint) lead us astray.*/ 2110 len = -1; /* unknown */ 2111 for (i = 0; i < itemsize; ++i) { 2112 PyObject *item = PyTuple_GET_ITEM(args, i); 2113 int thislen = PyObject_Size(item); 2114 if (thislen < 0) { 2115 if (!PyErr_ExceptionMatches(PyExc_TypeError) && 2116 !PyErr_ExceptionMatches(PyExc_AttributeError)) { 2117 return NULL; 2118 } 2119 PyErr_Clear(); 2120 len = -1; 2121 break; 2122 } 2123 else if (len < 0 || thislen < len) 2124 len = thislen; 2125 } 2126 2127 /* allocate result list */ 2128 if (len < 0) 2129 len = 10; /* arbitrary */ 2130 if ((ret = PyList_New(len)) == NULL) 2131 return NULL; 2132 2133 /* obtain iterators */ 2134 itlist = PyTuple_New(itemsize); 2135 if (itlist == NULL) 2136 goto Fail_ret; 2137 for (i = 0; i < itemsize; ++i) { 2138 PyObject *item = PyTuple_GET_ITEM(args, i); 2139 PyObject *it = PyObject_GetIter(item); 2140 if (it == NULL) { 2141 if (PyErr_ExceptionMatches(PyExc_TypeError)) 2142 PyErr_Format(PyExc_TypeError, 2143 "zip argument #%d must support iteration", 2144 i+1); 2145 goto Fail_ret_itlist; 2146 } 2147 PyTuple_SET_ITEM(itlist, i, it); 2148 } 2149 2150 /* build result into ret list */ 2151 for (i = 0; ; ++i) { 2152 int j; 2153 PyObject *next = PyTuple_New(itemsize); 2154 if (!next) 2155 goto Fail_ret_itlist; 2156 2157 for (j = 0; j < itemsize; j++) { 2158 PyObject *it = PyTuple_GET_ITEM(itlist, j); 2159 PyObject *item = PyIter_Next(it); 2160 if (!item) { 2161 if (PyErr_Occurred()) { 2162 Py_DECREF(ret); 2163 ret = NULL; 2164 } 2165 Py_DECREF(next); 2166 Py_DECREF(itlist); 2167 goto Done; 2168 } 2169 PyTuple_SET_ITEM(next, j, item); 2170 } 2171 2172 if (i < len) 2173 PyList_SET_ITEM(ret, i, next); 2174 else { 2175 int status = PyList_Append(ret, next); 2176 Py_DECREF(next); 2177 ++len; 2178 if (status < 0) 2179 goto Fail_ret_itlist; 2180 } 2181 } 2182 2183Done: 2184 if (ret != NULL && i < len) { 2185 /* The list is too big. */ 2186 if (PyList_SetSlice(ret, i, len, NULL) < 0) 2187 return NULL; 2188 } 2189 return ret; 2190 2191Fail_ret_itlist: 2192 Py_DECREF(itlist); 2193Fail_ret: 2194 Py_DECREF(ret); 2195 return NULL; 2196} 2197 2198 2199PyDoc_STRVAR(zip_doc, 2200"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\ 2201\n\ 2202Return a list of tuples, where each tuple contains the i-th element\n\ 2203from each of the argument sequences. The returned list is truncated\n\ 2204in length to the length of the shortest argument sequence."); 2205 2206 2207static PyMethodDef builtin_methods[] = { 2208 {"__import__", builtin___import__, METH_VARARGS, import_doc}, 2209 {"abs", builtin_abs, METH_O, abs_doc}, 2210 {"all", builtin_all, METH_O, all_doc}, 2211 {"any", builtin_any, METH_O, any_doc}, 2212 {"apply", builtin_apply, METH_VARARGS, apply_doc}, 2213 {"callable", builtin_callable, METH_O, callable_doc}, 2214 {"chr", builtin_chr, METH_VARARGS, chr_doc}, 2215 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc}, 2216 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc}, 2217 {"compile", builtin_compile, METH_VARARGS, compile_doc}, 2218 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc}, 2219 {"dir", builtin_dir, METH_VARARGS, dir_doc}, 2220 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc}, 2221 {"eval", builtin_eval, METH_VARARGS, eval_doc}, 2222 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc}, 2223 {"filter", builtin_filter, METH_VARARGS, filter_doc}, 2224 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc}, 2225 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc}, 2226 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc}, 2227 {"hash", builtin_hash, METH_O, hash_doc}, 2228 {"hex", builtin_hex, METH_O, hex_doc}, 2229 {"id", builtin_id, METH_O, id_doc}, 2230 {"input", builtin_input, METH_VARARGS, input_doc}, 2231 {"intern", builtin_intern, METH_VARARGS, intern_doc}, 2232 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, 2233 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, 2234 {"iter", builtin_iter, METH_VARARGS, iter_doc}, 2235 {"len", builtin_len, METH_O, len_doc}, 2236 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc}, 2237 {"map", builtin_map, METH_VARARGS, map_doc}, 2238 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, 2239 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, 2240 {"oct", builtin_oct, METH_O, oct_doc}, 2241 {"ord", builtin_ord, METH_O, ord_doc}, 2242 {"pow", builtin_pow, METH_VARARGS, pow_doc}, 2243 {"range", builtin_range, METH_VARARGS, range_doc}, 2244 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc}, 2245 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc}, 2246 {"reload", builtin_reload, METH_O, reload_doc}, 2247 {"repr", builtin_repr, METH_O, repr_doc}, 2248 {"round", builtin_round, METH_VARARGS, round_doc}, 2249 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc}, 2250 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc}, 2251 {"sum", builtin_sum, METH_VARARGS, sum_doc}, 2252#ifdef Py_USING_UNICODE 2253 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc}, 2254#endif 2255 {"vars", builtin_vars, METH_VARARGS, vars_doc}, 2256 {"zip", builtin_zip, METH_VARARGS, zip_doc}, 2257 {NULL, NULL}, 2258}; 2259 2260PyDoc_STRVAR(builtin_doc, 2261"Built-in functions, exceptions, and other objects.\n\ 2262\n\ 2263Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices."); 2264 2265PyObject * 2266_PyBuiltin_Init(void) 2267{ 2268 PyObject *mod, *dict, *debug; 2269 mod = Py_InitModule4("__builtin__", builtin_methods, 2270 builtin_doc, (PyObject *)NULL, 2271 PYTHON_API_VERSION); 2272 if (mod == NULL) 2273 return NULL; 2274 dict = PyModule_GetDict(mod); 2275 2276#ifdef Py_TRACE_REFS 2277 /* __builtin__ exposes a number of statically allocated objects 2278 * that, before this code was added in 2.3, never showed up in 2279 * the list of "all objects" maintained by Py_TRACE_REFS. As a 2280 * result, programs leaking references to None and False (etc) 2281 * couldn't be diagnosed by examining sys.getobjects(0). 2282 */ 2283#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0) 2284#else 2285#define ADD_TO_ALL(OBJECT) (void)0 2286#endif 2287 2288#define SETBUILTIN(NAME, OBJECT) \ 2289 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \ 2290 return NULL; \ 2291 ADD_TO_ALL(OBJECT) 2292 2293 SETBUILTIN("None", Py_None); 2294 SETBUILTIN("Ellipsis", Py_Ellipsis); 2295 SETBUILTIN("NotImplemented", Py_NotImplemented); 2296 SETBUILTIN("False", Py_False); 2297 SETBUILTIN("True", Py_True); 2298 SETBUILTIN("basestring", &PyBaseString_Type); 2299 SETBUILTIN("bool", &PyBool_Type); 2300 SETBUILTIN("buffer", &PyBuffer_Type); 2301 SETBUILTIN("classmethod", &PyClassMethod_Type); 2302#ifndef WITHOUT_COMPLEX 2303 SETBUILTIN("complex", &PyComplex_Type); 2304#endif 2305 SETBUILTIN("dict", &PyDict_Type); 2306 SETBUILTIN("enumerate", &PyEnum_Type); 2307 SETBUILTIN("float", &PyFloat_Type); 2308 SETBUILTIN("frozenset", &PyFrozenSet_Type); 2309 SETBUILTIN("property", &PyProperty_Type); 2310 SETBUILTIN("int", &PyInt_Type); 2311 SETBUILTIN("list", &PyList_Type); 2312 SETBUILTIN("long", &PyLong_Type); 2313 SETBUILTIN("object", &PyBaseObject_Type); 2314 SETBUILTIN("reversed", &PyReversed_Type); 2315 SETBUILTIN("set", &PySet_Type); 2316 SETBUILTIN("slice", &PySlice_Type); 2317 SETBUILTIN("staticmethod", &PyStaticMethod_Type); 2318 SETBUILTIN("str", &PyString_Type); 2319 SETBUILTIN("super", &PySuper_Type); 2320 SETBUILTIN("tuple", &PyTuple_Type); 2321 SETBUILTIN("type", &PyType_Type); 2322 SETBUILTIN("xrange", &PyRange_Type); 2323 2324 /* Note that open() is just an alias of file(). */ 2325 SETBUILTIN("open", &PyFile_Type); 2326 SETBUILTIN("file", &PyFile_Type); 2327#ifdef Py_USING_UNICODE 2328 SETBUILTIN("unicode", &PyUnicode_Type); 2329#endif 2330 debug = PyBool_FromLong(Py_OptimizeFlag == 0); 2331 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { 2332 Py_XDECREF(debug); 2333 return NULL; 2334 } 2335 Py_XDECREF(debug); 2336 2337 return mod; 2338#undef ADD_TO_ALL 2339#undef SETBUILTIN 2340} 2341 2342/* Helper for filter(): filter a tuple through a function */ 2343 2344static PyObject * 2345filtertuple(PyObject *func, PyObject *tuple) 2346{ 2347 PyObject *result; 2348 register int i, j; 2349 int len = PyTuple_Size(tuple); 2350 2351 if (len == 0) { 2352 if (PyTuple_CheckExact(tuple)) 2353 Py_INCREF(tuple); 2354 else 2355 tuple = PyTuple_New(0); 2356 return tuple; 2357 } 2358 2359 if ((result = PyTuple_New(len)) == NULL) 2360 return NULL; 2361 2362 for (i = j = 0; i < len; ++i) { 2363 PyObject *item, *good; 2364 int ok; 2365 2366 if (tuple->ob_type->tp_as_sequence && 2367 tuple->ob_type->tp_as_sequence->sq_item) { 2368 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i); 2369 if (item == NULL) 2370 goto Fail_1; 2371 } else { 2372 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple"); 2373 goto Fail_1; 2374 } 2375 if (func == Py_None) { 2376 Py_INCREF(item); 2377 good = item; 2378 } 2379 else { 2380 PyObject *arg = PyTuple_Pack(1, item); 2381 if (arg == NULL) { 2382 Py_DECREF(item); 2383 goto Fail_1; 2384 } 2385 good = PyEval_CallObject(func, arg); 2386 Py_DECREF(arg); 2387 if (good == NULL) { 2388 Py_DECREF(item); 2389 goto Fail_1; 2390 } 2391 } 2392 ok = PyObject_IsTrue(good); 2393 Py_DECREF(good); 2394 if (ok) { 2395 if (PyTuple_SetItem(result, j++, item) < 0) 2396 goto Fail_1; 2397 } 2398 else 2399 Py_DECREF(item); 2400 } 2401 2402 if (_PyTuple_Resize(&result, j) < 0) 2403 return NULL; 2404 2405 return result; 2406 2407Fail_1: 2408 Py_DECREF(result); 2409 return NULL; 2410} 2411 2412 2413/* Helper for filter(): filter a string through a function */ 2414 2415static PyObject * 2416filterstring(PyObject *func, PyObject *strobj) 2417{ 2418 PyObject *result; 2419 register int i, j; 2420 int len = PyString_Size(strobj); 2421 int outlen = len; 2422 2423 if (func == Py_None) { 2424 /* If it's a real string we can return the original, 2425 * as no character is ever false and __getitem__ 2426 * does return this character. If it's a subclass 2427 * we must go through the __getitem__ loop */ 2428 if (PyString_CheckExact(strobj)) { 2429 Py_INCREF(strobj); 2430 return strobj; 2431 } 2432 } 2433 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL) 2434 return NULL; 2435 2436 for (i = j = 0; i < len; ++i) { 2437 PyObject *item; 2438 int ok; 2439 2440 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i); 2441 if (item == NULL) 2442 goto Fail_1; 2443 if (func==Py_None) { 2444 ok = 1; 2445 } else { 2446 PyObject *arg, *good; 2447 arg = PyTuple_Pack(1, item); 2448 if (arg == NULL) { 2449 Py_DECREF(item); 2450 goto Fail_1; 2451 } 2452 good = PyEval_CallObject(func, arg); 2453 Py_DECREF(arg); 2454 if (good == NULL) { 2455 Py_DECREF(item); 2456 goto Fail_1; 2457 } 2458 ok = PyObject_IsTrue(good); 2459 Py_DECREF(good); 2460 } 2461 if (ok) { 2462 int reslen; 2463 if (!PyString_Check(item)) { 2464 PyErr_SetString(PyExc_TypeError, "can't filter str to str:" 2465 " __getitem__ returned different type"); 2466 Py_DECREF(item); 2467 goto Fail_1; 2468 } 2469 reslen = PyString_GET_SIZE(item); 2470 if (reslen == 1) { 2471 PyString_AS_STRING(result)[j++] = 2472 PyString_AS_STRING(item)[0]; 2473 } else { 2474 /* do we need more space? */ 2475 int need = j + reslen + len-i-1; 2476 if (need > outlen) { 2477 /* overallocate, to avoid reallocations */ 2478 if (need<2*outlen) 2479 need = 2*outlen; 2480 if (_PyString_Resize(&result, need)) { 2481 Py_DECREF(item); 2482 return NULL; 2483 } 2484 outlen = need; 2485 } 2486 memcpy( 2487 PyString_AS_STRING(result) + j, 2488 PyString_AS_STRING(item), 2489 reslen 2490 ); 2491 j += reslen; 2492 } 2493 } 2494 Py_DECREF(item); 2495 } 2496 2497 if (j < outlen) 2498 _PyString_Resize(&result, j); 2499 2500 return result; 2501 2502Fail_1: 2503 Py_DECREF(result); 2504 return NULL; 2505} 2506 2507#ifdef Py_USING_UNICODE 2508/* Helper for filter(): filter a Unicode object through a function */ 2509 2510static PyObject * 2511filterunicode(PyObject *func, PyObject *strobj) 2512{ 2513 PyObject *result; 2514 register int i, j; 2515 int len = PyUnicode_GetSize(strobj); 2516 int outlen = len; 2517 2518 if (func == Py_None) { 2519 /* If it's a real string we can return the original, 2520 * as no character is ever false and __getitem__ 2521 * does return this character. If it's a subclass 2522 * we must go through the __getitem__ loop */ 2523 if (PyUnicode_CheckExact(strobj)) { 2524 Py_INCREF(strobj); 2525 return strobj; 2526 } 2527 } 2528 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL) 2529 return NULL; 2530 2531 for (i = j = 0; i < len; ++i) { 2532 PyObject *item, *arg, *good; 2533 int ok; 2534 2535 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i); 2536 if (item == NULL) 2537 goto Fail_1; 2538 if (func == Py_None) { 2539 ok = 1; 2540 } else { 2541 arg = PyTuple_Pack(1, item); 2542 if (arg == NULL) { 2543 Py_DECREF(item); 2544 goto Fail_1; 2545 } 2546 good = PyEval_CallObject(func, arg); 2547 Py_DECREF(arg); 2548 if (good == NULL) { 2549 Py_DECREF(item); 2550 goto Fail_1; 2551 } 2552 ok = PyObject_IsTrue(good); 2553 Py_DECREF(good); 2554 } 2555 if (ok) { 2556 int reslen; 2557 if (!PyUnicode_Check(item)) { 2558 PyErr_SetString(PyExc_TypeError, 2559 "can't filter unicode to unicode:" 2560 " __getitem__ returned different type"); 2561 Py_DECREF(item); 2562 goto Fail_1; 2563 } 2564 reslen = PyUnicode_GET_SIZE(item); 2565 if (reslen == 1) 2566 PyUnicode_AS_UNICODE(result)[j++] = 2567 PyUnicode_AS_UNICODE(item)[0]; 2568 else { 2569 /* do we need more space? */ 2570 int need = j + reslen + len - i - 1; 2571 if (need > outlen) { 2572 /* overallocate, 2573 to avoid reallocations */ 2574 if (need < 2 * outlen) 2575 need = 2 * outlen; 2576 if (PyUnicode_Resize( 2577 &result, need) < 0) { 2578 Py_DECREF(item); 2579 goto Fail_1; 2580 } 2581 outlen = need; 2582 } 2583 memcpy(PyUnicode_AS_UNICODE(result) + j, 2584 PyUnicode_AS_UNICODE(item), 2585 reslen*sizeof(Py_UNICODE)); 2586 j += reslen; 2587 } 2588 } 2589 Py_DECREF(item); 2590 } 2591 2592 if (j < outlen) 2593 PyUnicode_Resize(&result, j); 2594 2595 return result; 2596 2597Fail_1: 2598 Py_DECREF(result); 2599 return NULL; 2600} 2601#endif 2602