cinap_lenrekadd hg and python4bb9e2215 years agoHistory
2620 lines · 61.8 KB · C
RawDownload
/* Built-in functions */ #include "Python.h" #include "node.h"#include "code.h"#include "eval.h" #include <ctype.h> #ifdef RISCOS#include "unixstuff.h"#endif /* The default encoding used by the platform file system APIs   Can remain NULL for all platforms that don't have such a concept*/#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)const char *Py_FileSystemDefaultEncoding = "mbcs";#elif defined(__APPLE__)const char *Py_FileSystemDefaultEncoding = "utf-8";#elseconst char *Py_FileSystemDefaultEncoding = NULL; /* use default */#endif /* Forward */static PyObject *filterstring(PyObject *, PyObject *);#ifdef Py_USING_UNICODEstatic PyObject *filterunicode(PyObject *, PyObject *);#endifstatic PyObject *filtertuple (PyObject *, PyObject *); static PyObject *builtin___import__(PyObject *self, PyObject *args, PyObject *kwds){	static char *kwlist[] = {"name", "globals", "locals", "fromlist",				 "level", 0};	char *name;	PyObject *globals = NULL;	PyObject *locals = NULL;	PyObject *fromlist = NULL;	int level = -1; 	if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",			kwlist, &name, &globals, &locals, &fromlist, &level))		return NULL;	return PyImport_ImportModuleLevel(name, globals, locals,					  fromlist, level);} PyDoc_STRVAR(import_doc,"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\\n\Import a module.  The globals are only used to determine the context;\n\they are not modified.  The locals are currently unused.  The fromlist\n\should be a list of names to emulate ``from name import ...'', or an\n\empty list to emulate ``import name''.\n\When importing a module from a package, note that __import__('A.B', ...)\n\returns package A when fromlist is empty, but its submodule B when\n\fromlist is not empty.  Level is used to determine whether to perform \n\absolute or relative imports.  -1 is the original strategy of attempting\n\both absolute and relative imports, 0 is absolute, a positive number\n\is the number of parent directories to search relative to the current module.");  static PyObject *builtin_abs(PyObject *self, PyObject *v){	return PyNumber_Absolute(v);} PyDoc_STRVAR(abs_doc,"abs(number) -> number\n\\n\Return the absolute value of the argument."); static PyObject *builtin_all(PyObject *self, PyObject *v){	PyObject *it, *item; 	it = PyObject_GetIter(v);	if (it == NULL)		return NULL; 	while ((item = PyIter_Next(it)) != NULL) {		int cmp = PyObject_IsTrue(item);		Py_DECREF(item);		if (cmp < 0) {			Py_DECREF(it);			return NULL;		}		if (cmp == 0) {			Py_DECREF(it);			Py_RETURN_FALSE;		}	}	Py_DECREF(it);	if (PyErr_Occurred())		return NULL;	Py_RETURN_TRUE;} PyDoc_STRVAR(all_doc,"all(iterable) -> bool\n\\n\Return True if bool(x) is True for all values x in the iterable."); static PyObject *builtin_any(PyObject *self, PyObject *v){	PyObject *it, *item; 	it = PyObject_GetIter(v);	if (it == NULL)		return NULL; 	while ((item = PyIter_Next(it)) != NULL) {		int cmp = PyObject_IsTrue(item);		Py_DECREF(item);		if (cmp < 0) {			Py_DECREF(it);			return NULL;		}		if (cmp == 1) {			Py_DECREF(it);			Py_RETURN_TRUE;		}	}	Py_DECREF(it);	if (PyErr_Occurred())		return NULL;	Py_RETURN_FALSE;} PyDoc_STRVAR(any_doc,"any(iterable) -> bool\n\\n\Return True if bool(x) is True for any x in the iterable."); static PyObject *builtin_apply(PyObject *self, PyObject *args){	PyObject *func, *alist = NULL, *kwdict = NULL;	PyObject *t = NULL, *retval = NULL; 	if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))		return NULL;	if (alist != NULL) {		if (!PyTuple_Check(alist)) {			if (!PySequence_Check(alist)) {				PyErr_Format(PyExc_TypeError,				     "apply() arg 2 expected sequence, found %s",					     alist->ob_type->tp_name);				return NULL;			}			t = PySequence_Tuple(alist);			if (t == NULL)				return NULL;			alist = t;		}	}	if (kwdict != NULL && !PyDict_Check(kwdict)) {		PyErr_Format(PyExc_TypeError,			     "apply() arg 3 expected dictionary, found %s",			     kwdict->ob_type->tp_name);		goto finally;	}	retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);  finally:	Py_XDECREF(t);	return retval;} PyDoc_STRVAR(apply_doc,"apply(object[, args[, kwargs]]) -> value\n\\n\Call a callable object with positional arguments taken from the tuple args,\n\and keyword arguments taken from the optional dictionary kwargs.\n\Note that classes are callable, as are instances with a __call__() method.\n\\n\Deprecated since release 2.3. Instead, use the extended call syntax:\n\    function(*args, **keywords).");  static PyObject *builtin_callable(PyObject *self, PyObject *v){	return PyBool_FromLong((long)PyCallable_Check(v));} PyDoc_STRVAR(callable_doc,"callable(object) -> bool\n\\n\Return whether the object is callable (i.e., some kind of function).\n\Note that classes are callable, as are instances with a __call__() method.");  static PyObject *builtin_filter(PyObject *self, PyObject *args){	PyObject *func, *seq, *result, *it, *arg;	Py_ssize_t len;   /* guess for result list size */	register Py_ssize_t j; 	if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))		return NULL; 	/* Strings and tuples return a result of the same type. */	if (PyString_Check(seq))		return filterstring(func, seq);#ifdef Py_USING_UNICODE	if (PyUnicode_Check(seq))		return filterunicode(func, seq);#endif	if (PyTuple_Check(seq))		return filtertuple(func, seq); 	/* Pre-allocate argument list tuple. */	arg = PyTuple_New(1);	if (arg == NULL)		return NULL; 	/* Get iterator. */	it = PyObject_GetIter(seq);	if (it == NULL)		goto Fail_arg; 	/* Guess a result list size. */	len = _PyObject_LengthHint(seq);	if (len < 0) {		if (!PyErr_ExceptionMatches(PyExc_TypeError)  &&		    !PyErr_ExceptionMatches(PyExc_AttributeError)) {			goto Fail_it;		}		PyErr_Clear();		len = 8;	/* arbitrary */	} 	/* Get a result list. */	if (PyList_Check(seq) && seq->ob_refcnt == 1) {		/* Eww - can modify the list in-place. */		Py_INCREF(seq);		result = seq;	}	else {		result = PyList_New(len);		if (result == NULL)			goto Fail_it;	} 	/* Build the result list. */	j = 0;	for (;;) {		PyObject *item;		int ok; 		item = PyIter_Next(it);		if (item == NULL) {			if (PyErr_Occurred())				goto Fail_result_it;			break;		} 		if (func == (PyObject *)&PyBool_Type || func == Py_None) {			ok = PyObject_IsTrue(item);		}		else {			PyObject *good;			PyTuple_SET_ITEM(arg, 0, item);			good = PyObject_Call(func, arg, NULL);			PyTuple_SET_ITEM(arg, 0, NULL);			if (good == NULL) {				Py_DECREF(item);				goto Fail_result_it;			}			ok = PyObject_IsTrue(good);			Py_DECREF(good);		}		if (ok) {			if (j < len)				PyList_SET_ITEM(result, j, item);			else {				int status = PyList_Append(result, item);				Py_DECREF(item);				if (status < 0)					goto Fail_result_it;			}			++j;		}		else			Py_DECREF(item);	}  	/* Cut back result list if len is too big. */	if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)		goto Fail_result_it; 	Py_DECREF(it);	Py_DECREF(arg);	return result; Fail_result_it:	Py_DECREF(result);Fail_it:	Py_DECREF(it);Fail_arg:	Py_DECREF(arg);	return NULL;} PyDoc_STRVAR(filter_doc,"filter(function or None, sequence) -> list, tuple, or string\n""\n""Return those items of sequence for which function(item) is true.  If\n""function is None, return the items that are true.  If sequence is a tuple\n""or string, return the same type, else return a list."); static PyObject *builtin_chr(PyObject *self, PyObject *args){	long x;	char s[1]; 	if (!PyArg_ParseTuple(args, "l:chr", &x))		return NULL;	if (x < 0 || x >= 256) {		PyErr_SetString(PyExc_ValueError,				"chr() arg not in range(256)");		return NULL;	}	s[0] = (char)x;	return PyString_FromStringAndSize(s, 1);} PyDoc_STRVAR(chr_doc,"chr(i) -> character\n\\n\Return a string of one character with ordinal i; 0 <= i < 256.");  #ifdef Py_USING_UNICODEstatic PyObject *builtin_unichr(PyObject *self, PyObject *args){	long x; 	if (!PyArg_ParseTuple(args, "l:unichr", &x))		return NULL; 	return PyUnicode_FromOrdinal(x);} PyDoc_STRVAR(unichr_doc,"unichr(i) -> Unicode character\n\\n\Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");#endif  static PyObject *builtin_cmp(PyObject *self, PyObject *args){	PyObject *a, *b;	int c; 	if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))		return NULL;	if (PyObject_Cmp(a, b, &c) < 0)		return NULL;	return PyInt_FromLong((long)c);} PyDoc_STRVAR(cmp_doc,"cmp(x, y) -> integer\n\\n\Return negative if x<y, zero if x==y, positive if x>y.");  static PyObject *builtin_coerce(PyObject *self, PyObject *args){	PyObject *v, *w;	PyObject *res; 	if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))		return NULL;	if (PyNumber_Coerce(&v, &w) < 0)		return NULL;	res = PyTuple_Pack(2, v, w);	Py_DECREF(v);	Py_DECREF(w);	return res;} PyDoc_STRVAR(coerce_doc,"coerce(x, y) -> (x1, y1)\n\\n\Return a tuple consisting of the two numeric arguments converted to\n\a common type, using the same rules as used by arithmetic operations.\n\If coercion is not possible, raise TypeError."); static PyObject *builtin_compile(PyObject *self, PyObject *args){	char *str;	char *filename;	char *startstr;	int start;	int dont_inherit = 0;	int supplied_flags = 0;	PyCompilerFlags cf;	PyObject *result = NULL, *cmd, *tmp = NULL;	Py_ssize_t length; 	if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename,			      &startstr, &supplied_flags, &dont_inherit))		return NULL; 	cf.cf_flags = supplied_flags; #ifdef Py_USING_UNICODE	if (PyUnicode_Check(cmd)) {		tmp = PyUnicode_AsUTF8String(cmd);		if (tmp == NULL)			return NULL;		cmd = tmp;		cf.cf_flags |= PyCF_SOURCE_IS_UTF8;	}#endif	if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))		return NULL;	if ((size_t)length != strlen(str)) {		PyErr_SetString(PyExc_TypeError,				"compile() expected string without null bytes");		goto cleanup;	} 	if (strcmp(startstr, "exec") == 0)		start = Py_file_input;	else if (strcmp(startstr, "eval") == 0)		start = Py_eval_input;	else if (strcmp(startstr, "single") == 0)		start = Py_single_input;	else {		PyErr_SetString(PyExc_ValueError,		   "compile() arg 3 must be 'exec' or 'eval' or 'single'");		goto cleanup;	} 	if (supplied_flags &	    ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))	{		PyErr_SetString(PyExc_ValueError,				"compile(): unrecognised flags");		goto cleanup;	}	/* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ 	if (!dont_inherit) {		PyEval_MergeCompilerFlags(&cf);	}	result = Py_CompileStringFlags(str, filename, start, &cf);cleanup:	Py_XDECREF(tmp);	return result;} PyDoc_STRVAR(compile_doc,"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\\n\Compile the source string (a Python module, statement or expression)\n\into a code object that can be executed by the exec statement or eval().\n\The filename will be used for run-time error messages.\n\The mode must be 'exec' to compile a module, 'single' to compile a\n\single (interactive) statement, or 'eval' to compile an expression.\n\The flags argument, if present, controls which future statements influence\n\the compilation of the code.\n\The dont_inherit argument, if non-zero, stops the compilation inheriting\n\the effects of any future statements in effect in the code calling\n\compile; if absent or zero these statements do influence the compilation,\n\in addition to any features explicitly specified."); static PyObject *builtin_dir(PyObject *self, PyObject *args){	PyObject *arg = NULL; 	if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))		return NULL;	return PyObject_Dir(arg);} PyDoc_STRVAR(dir_doc,"dir([object]) -> list of strings\n""\n""Return an alphabetized list of names comprising (some of) the attributes\n""of the given object, and of attributes reachable from it:\n""\n"

Lines 1–500 of 2620.