1 /* Built-in functions */
4 #include "Python-ast.h"
11 #include <float.h> /* for DBL_MANT_DIG and friends */
14 #include "unixstuff.h"
17 /* The default encoding used by the platform file system APIs
18 Can remain NULL for all platforms that don't have such a concept
20 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
21 const char *Py_FileSystemDefaultEncoding
= "mbcs";
22 #elif defined(__APPLE__)
23 const char *Py_FileSystemDefaultEncoding
= "utf-8";
25 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
29 static PyObject
*filterstring(PyObject
*, PyObject
*);
30 #ifdef Py_USING_UNICODE
31 static PyObject
*filterunicode(PyObject
*, PyObject
*);
33 static PyObject
*filtertuple (PyObject
*, PyObject
*);
36 builtin___import__(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
38 static char *kwlist
[] = {"name", "globals", "locals", "fromlist",
41 PyObject
*globals
= NULL
;
42 PyObject
*locals
= NULL
;
43 PyObject
*fromlist
= NULL
;
46 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "s|OOOi:__import__",
47 kwlist
, &name
, &globals
, &locals
, &fromlist
, &level
))
49 return PyImport_ImportModuleLevel(name
, globals
, locals
,
53 PyDoc_STRVAR(import_doc
,
54 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
56 Import a module. The globals are only used to determine the context;\n\
57 they are not modified. The locals are currently unused. The fromlist\n\
58 should be a list of names to emulate ``from name import ...'', or an\n\
59 empty list to emulate ``import name''.\n\
60 When importing a module from a package, note that __import__('A.B', ...)\n\
61 returns package A when fromlist is empty, but its submodule B when\n\
62 fromlist is not empty. Level is used to determine whether to perform \n\
63 absolute or relative imports. -1 is the original strategy of attempting\n\
64 both absolute and relative imports, 0 is absolute, a positive number\n\
65 is the number of parent directories to search relative to the current module.");
69 builtin_abs(PyObject
*self
, PyObject
*v
)
71 return PyNumber_Absolute(v
);
75 "abs(number) -> number\n\
77 Return the absolute value of the argument.");
80 builtin_all(PyObject
*self
, PyObject
*v
)
83 PyObject
*(*iternext
)(PyObject
*);
86 it
= PyObject_GetIter(v
);
89 iternext
= *Py_TYPE(it
)->tp_iternext
;
95 cmp
= PyObject_IsTrue(item
);
107 if (PyErr_Occurred()) {
108 if (PyErr_ExceptionMatches(PyExc_StopIteration
))
116 PyDoc_STRVAR(all_doc
,
117 "all(iterable) -> bool\n\
119 Return True if bool(x) is True for all values x in the iterable.");
122 builtin_any(PyObject
*self
, PyObject
*v
)
125 PyObject
*(*iternext
)(PyObject
*);
128 it
= PyObject_GetIter(v
);
131 iternext
= *Py_TYPE(it
)->tp_iternext
;
137 cmp
= PyObject_IsTrue(item
);
149 if (PyErr_Occurred()) {
150 if (PyErr_ExceptionMatches(PyExc_StopIteration
))
158 PyDoc_STRVAR(any_doc
,
159 "any(iterable) -> bool\n\
161 Return True if bool(x) is True for any x in the iterable.");
164 builtin_apply(PyObject
*self
, PyObject
*args
)
166 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
167 PyObject
*t
= NULL
, *retval
= NULL
;
169 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
170 "use func(*args, **kwargs)", 1) < 0)
173 if (!PyArg_UnpackTuple(args
, "apply", 1, 3, &func
, &alist
, &kwdict
))
176 if (!PyTuple_Check(alist
)) {
177 if (!PySequence_Check(alist
)) {
178 PyErr_Format(PyExc_TypeError
,
179 "apply() arg 2 expected sequence, found %s",
180 alist
->ob_type
->tp_name
);
183 t
= PySequence_Tuple(alist
);
189 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
190 PyErr_Format(PyExc_TypeError
,
191 "apply() arg 3 expected dictionary, found %s",
192 kwdict
->ob_type
->tp_name
);
195 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
201 PyDoc_STRVAR(apply_doc
,
202 "apply(object[, args[, kwargs]]) -> value\n\
204 Call a callable object with positional arguments taken from the tuple args,\n\
205 and keyword arguments taken from the optional dictionary kwargs.\n\
206 Note that classes are callable, as are instances with a __call__() method.\n\
208 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
209 function(*args, **keywords).");
213 builtin_bin(PyObject
*self
, PyObject
*v
)
215 return PyNumber_ToBase(v
, 2);
218 PyDoc_STRVAR(bin_doc
,
219 "bin(number) -> string\n\
221 Return the binary representation of an integer or long integer.");
225 builtin_callable(PyObject
*self
, PyObject
*v
)
227 if (PyErr_WarnPy3k("callable() not supported in 3.x; "
228 "use isinstance(x, collections.Callable)", 1) < 0)
230 return PyBool_FromLong((long)PyCallable_Check(v
));
233 PyDoc_STRVAR(callable_doc
,
234 "callable(object) -> bool\n\
236 Return whether the object is callable (i.e., some kind of function).\n\
237 Note that classes are callable, as are instances with a __call__() method.");
241 builtin_filter(PyObject
*self
, PyObject
*args
)
243 PyObject
*func
, *seq
, *result
, *it
, *arg
;
244 Py_ssize_t len
; /* guess for result list size */
245 register Py_ssize_t j
;
247 if (!PyArg_UnpackTuple(args
, "filter", 2, 2, &func
, &seq
))
250 /* Strings and tuples return a result of the same type. */
251 if (PyString_Check(seq
))
252 return filterstring(func
, seq
);
253 #ifdef Py_USING_UNICODE
254 if (PyUnicode_Check(seq
))
255 return filterunicode(func
, seq
);
257 if (PyTuple_Check(seq
))
258 return filtertuple(func
, seq
);
260 /* Pre-allocate argument list tuple. */
261 arg
= PyTuple_New(1);
266 it
= PyObject_GetIter(seq
);
270 /* Guess a result list size. */
271 len
= _PyObject_LengthHint(seq
, 8);
275 /* Get a result list. */
276 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
277 /* Eww - can modify the list in-place. */
282 result
= PyList_New(len
);
287 /* Build the result list. */
293 item
= PyIter_Next(it
);
295 if (PyErr_Occurred())
300 if (func
== (PyObject
*)&PyBool_Type
|| func
== Py_None
) {
301 ok
= PyObject_IsTrue(item
);
305 PyTuple_SET_ITEM(arg
, 0, item
);
306 good
= PyObject_Call(func
, arg
, NULL
);
307 PyTuple_SET_ITEM(arg
, 0, NULL
);
312 ok
= PyObject_IsTrue(good
);
317 PyList_SET_ITEM(result
, j
, item
);
319 int status
= PyList_Append(result
, item
);
331 /* Cut back result list if len is too big. */
332 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
348 PyDoc_STRVAR(filter_doc
,
349 "filter(function or None, sequence) -> list, tuple, or string\n"
351 "Return those items of sequence for which function(item) is true. If\n"
352 "function is None, return the items that are true. If sequence is a tuple\n"
353 "or string, return the same type, else return a list.");
356 builtin_format(PyObject
*self
, PyObject
*args
)
359 PyObject
*format_spec
= NULL
;
361 if (!PyArg_ParseTuple(args
, "O|O:format", &value
, &format_spec
))
364 return PyObject_Format(value
, format_spec
);
367 PyDoc_STRVAR(format_doc
,
368 "format(value[, format_spec]) -> string\n\
370 Returns value.__format__(format_spec)\n\
371 format_spec defaults to \"\"");
374 builtin_chr(PyObject
*self
, PyObject
*args
)
379 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
381 if (x
< 0 || x
>= 256) {
382 PyErr_SetString(PyExc_ValueError
,
383 "chr() arg not in range(256)");
387 return PyString_FromStringAndSize(s
, 1);
390 PyDoc_STRVAR(chr_doc
,
391 "chr(i) -> character\n\
393 Return a string of one character with ordinal i; 0 <= i < 256.");
396 #ifdef Py_USING_UNICODE
398 builtin_unichr(PyObject
*self
, PyObject
*args
)
402 if (!PyArg_ParseTuple(args
, "i:unichr", &x
))
405 return PyUnicode_FromOrdinal(x
);
408 PyDoc_STRVAR(unichr_doc
,
409 "unichr(i) -> Unicode character\n\
411 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
416 builtin_cmp(PyObject
*self
, PyObject
*args
)
421 if (!PyArg_UnpackTuple(args
, "cmp", 2, 2, &a
, &b
))
423 if (PyObject_Cmp(a
, b
, &c
) < 0)
425 return PyInt_FromLong((long)c
);
428 PyDoc_STRVAR(cmp_doc
,
429 "cmp(x, y) -> integer\n\
431 Return negative if x<y, zero if x==y, positive if x>y.");
435 builtin_coerce(PyObject
*self
, PyObject
*args
)
440 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
443 if (!PyArg_UnpackTuple(args
, "coerce", 2, 2, &v
, &w
))
445 if (PyNumber_Coerce(&v
, &w
) < 0)
447 res
= PyTuple_Pack(2, v
, w
);
453 PyDoc_STRVAR(coerce_doc
,
454 "coerce(x, y) -> (x1, y1)\n\
456 Return a tuple consisting of the two numeric arguments converted to\n\
457 a common type, using the same rules as used by arithmetic operations.\n\
458 If coercion is not possible, raise TypeError.");
461 builtin_compile(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
467 int dont_inherit
= 0;
468 int supplied_flags
= 0;
470 PyObject
*result
= NULL
, *cmd
, *tmp
= NULL
;
472 static char *kwlist
[] = {"source", "filename", "mode", "flags",
473 "dont_inherit", NULL
};
474 int start
[] = {Py_file_input
, Py_eval_input
, Py_single_input
};
476 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "Oss|ii:compile",
477 kwlist
, &cmd
, &filename
, &startstr
,
478 &supplied_flags
, &dont_inherit
))
481 cf
.cf_flags
= supplied_flags
;
484 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
| PyCF_ONLY_AST
))
486 PyErr_SetString(PyExc_ValueError
,
487 "compile(): unrecognised flags");
490 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
493 PyEval_MergeCompilerFlags(&cf
);
496 if (strcmp(startstr
, "exec") == 0)
498 else if (strcmp(startstr
, "eval") == 0)
500 else if (strcmp(startstr
, "single") == 0)
503 PyErr_SetString(PyExc_ValueError
,
504 "compile() arg 3 must be 'exec', 'eval' or 'single'");
508 if (PyAST_Check(cmd
)) {
509 if (supplied_flags
& PyCF_ONLY_AST
) {
517 arena
= PyArena_New();
518 mod
= PyAST_obj2mod(cmd
, arena
, mode
);
523 result
= (PyObject
*)PyAST_Compile(mod
, filename
,
530 #ifdef Py_USING_UNICODE
531 if (PyUnicode_Check(cmd
)) {
532 tmp
= PyUnicode_AsUTF8String(cmd
);
536 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
540 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &length
))
542 if ((size_t)length
!= strlen(str
)) {
543 PyErr_SetString(PyExc_TypeError
,
544 "compile() expected string without null bytes");
547 result
= Py_CompileStringFlags(str
, filename
, start
[mode
], &cf
);
553 PyDoc_STRVAR(compile_doc
,
554 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
556 Compile the source string (a Python module, statement or expression)\n\
557 into a code object that can be executed by the exec statement or eval().\n\
558 The filename will be used for run-time error messages.\n\
559 The mode must be 'exec' to compile a module, 'single' to compile a\n\
560 single (interactive) statement, or 'eval' to compile an expression.\n\
561 The flags argument, if present, controls which future statements influence\n\
562 the compilation of the code.\n\
563 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
564 the effects of any future statements in effect in the code calling\n\
565 compile; if absent or zero these statements do influence the compilation,\n\
566 in addition to any features explicitly specified.");
569 builtin_dir(PyObject
*self
, PyObject
*args
)
571 PyObject
*arg
= NULL
;
573 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
575 return PyObject_Dir(arg
);
578 PyDoc_STRVAR(dir_doc
,
579 "dir([object]) -> list of strings\n"
581 "If called without an argument, return the names in the current scope.\n"
582 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
583 "of the given object, and of attributes reachable from it.\n"
584 "If the object supplies a method named __dir__, it will be used; otherwise\n"
585 "the default dir() logic is used and returns:\n"
586 " for a module object: the module's attributes.\n"
587 " for a class object: its attributes, and recursively the attributes\n"
589 " for any other object: its attributes, its class's attributes, and\n"
590 " recursively the attributes of its class's base classes.");
593 builtin_divmod(PyObject
*self
, PyObject
*args
)
597 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
599 return PyNumber_Divmod(v
, w
);
602 PyDoc_STRVAR(divmod_doc
,
603 "divmod(x, y) -> (div, mod)\n\
605 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
609 builtin_eval(PyObject
*self
, PyObject
*args
)
611 PyObject
*cmd
, *result
, *tmp
= NULL
;
612 PyObject
*globals
= Py_None
, *locals
= Py_None
;
616 if (!PyArg_UnpackTuple(args
, "eval", 1, 3, &cmd
, &globals
, &locals
))
618 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
619 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
622 if (globals
!= Py_None
&& !PyDict_Check(globals
)) {
623 PyErr_SetString(PyExc_TypeError
, PyMapping_Check(globals
) ?
624 "globals must be a real dict; try eval(expr, {}, mapping)"
625 : "globals must be a dict");
628 if (globals
== Py_None
) {
629 globals
= PyEval_GetGlobals();
630 if (locals
== Py_None
)
631 locals
= PyEval_GetLocals();
633 else if (locals
== Py_None
)
636 if (globals
== NULL
|| locals
== NULL
) {
637 PyErr_SetString(PyExc_TypeError
,
638 "eval must be given globals and locals "
639 "when called without a frame");
643 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
644 if (PyDict_SetItemString(globals
, "__builtins__",
645 PyEval_GetBuiltins()) != 0)
649 if (PyCode_Check(cmd
)) {
650 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
651 PyErr_SetString(PyExc_TypeError
,
652 "code object passed to eval() may not contain free variables");
655 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
658 if (!PyString_Check(cmd
) &&
659 !PyUnicode_Check(cmd
)) {
660 PyErr_SetString(PyExc_TypeError
,
661 "eval() arg 1 must be a string or code object");
666 #ifdef Py_USING_UNICODE
667 if (PyUnicode_Check(cmd
)) {
668 tmp
= PyUnicode_AsUTF8String(cmd
);
672 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
675 if (PyString_AsStringAndSize(cmd
, &str
, NULL
)) {
679 while (*str
== ' ' || *str
== '\t')
682 (void)PyEval_MergeCompilerFlags(&cf
);
683 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
688 PyDoc_STRVAR(eval_doc
,
689 "eval(source[, globals[, locals]]) -> value\n\
691 Evaluate the source in the context of globals and locals.\n\
692 The source may be a string representing a Python expression\n\
693 or a code object as returned by compile().\n\
694 The globals must be a dictionary and locals can be any mapping,\n\
695 defaulting to the current globals and locals.\n\
696 If only globals is given, locals defaults to it.\n");
700 builtin_execfile(PyObject
*self
, PyObject
*args
)
703 PyObject
*globals
= Py_None
, *locals
= Py_None
;
709 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
713 if (!PyArg_ParseTuple(args
, "s|O!O:execfile",
715 &PyDict_Type
, &globals
,
718 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
719 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
722 if (globals
== Py_None
) {
723 globals
= PyEval_GetGlobals();
724 if (locals
== Py_None
)
725 locals
= PyEval_GetLocals();
727 else if (locals
== Py_None
)
729 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
730 if (PyDict_SetItemString(globals
, "__builtins__",
731 PyEval_GetBuiltins()) != 0)
736 /* Test for existence or directory. */
741 if ((d
= dirstat(filename
))!=nil
) {
743 werrstr("is a directory");
749 #elif defined(RISCOS)
750 if (object_exists(filename
)) {
756 #else /* standard Posix */
759 if (stat(filename
, &s
) == 0) {
760 if (S_ISDIR(s
.st_mode
))
761 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
773 Py_BEGIN_ALLOW_THREADS
774 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
783 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
787 if (PyEval_MergeCompilerFlags(&cf
))
788 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
791 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
796 PyDoc_STRVAR(execfile_doc
,
797 "execfile(filename[, globals[, locals]])\n\
799 Read and execute a Python script from a file.\n\
800 The globals and locals are dictionaries, defaulting to the current\n\
801 globals and locals. If only globals is given, locals defaults to it.");
805 builtin_getattr(PyObject
*self
, PyObject
*args
)
807 PyObject
*v
, *result
, *dflt
= NULL
;
810 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
812 #ifdef Py_USING_UNICODE
813 if (PyUnicode_Check(name
)) {
814 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
820 if (!PyString_Check(name
)) {
821 PyErr_SetString(PyExc_TypeError
,
822 "getattr(): attribute name must be string");
825 result
= PyObject_GetAttr(v
, name
);
826 if (result
== NULL
&& dflt
!= NULL
&&
827 PyErr_ExceptionMatches(PyExc_AttributeError
))
836 PyDoc_STRVAR(getattr_doc
,
837 "getattr(object, name[, default]) -> value\n\
839 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
840 When a default argument is given, it is returned when the attribute doesn't\n\
841 exist; without it, an exception is raised in that case.");
845 builtin_globals(PyObject
*self
)
849 d
= PyEval_GetGlobals();
854 PyDoc_STRVAR(globals_doc
,
855 "globals() -> dictionary\n\
857 Return the dictionary containing the current scope's global variables.");
861 builtin_hasattr(PyObject
*self
, PyObject
*args
)
866 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
868 #ifdef Py_USING_UNICODE
869 if (PyUnicode_Check(name
)) {
870 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
876 if (!PyString_Check(name
)) {
877 PyErr_SetString(PyExc_TypeError
,
878 "hasattr(): attribute name must be string");
881 v
= PyObject_GetAttr(v
, name
);
883 if (!PyErr_ExceptionMatches(PyExc_Exception
))
896 PyDoc_STRVAR(hasattr_doc
,
897 "hasattr(object, name) -> bool\n\
899 Return whether the object has an attribute with the given name.\n\
900 (This is done by calling getattr(object, name) and catching exceptions.)");
904 builtin_id(PyObject
*self
, PyObject
*v
)
906 return PyLong_FromVoidPtr(v
);
910 "id(object) -> integer\n\
912 Return the identity of an object. This is guaranteed to be unique among\n\
913 simultaneously existing objects. (Hint: it's the object's memory address.)");
917 builtin_map(PyObject
*self
, PyObject
*args
)
920 PyObject
*it
; /* the iterator object */
921 int saw_StopIteration
; /* bool: did the iterator end? */
924 PyObject
*func
, *result
;
925 sequence
*seqs
= NULL
, *sqp
;
929 n
= PyTuple_Size(args
);
931 PyErr_SetString(PyExc_TypeError
,
932 "map() requires at least two args");
936 func
= PyTuple_GetItem(args
, 0);
939 if (func
== Py_None
) {
940 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
941 "use list(...)", 1) < 0)
944 /* map(None, S) is the same as list(S). */
945 return PySequence_List(PyTuple_GetItem(args
, 1));
949 /* Get space for sequence descriptors. Must NULL out the iterator
950 * pointers so that jumping to Fail_2 later doesn't see trash.
952 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
956 for (i
= 0; i
< n
; ++i
) {
957 seqs
[i
].it
= (PyObject
*)NULL
;
958 seqs
[i
].saw_StopIteration
= 0;
961 /* Do a first pass to obtain iterators for the arguments, and set len
962 * to the largest of their lengths.
965 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
970 curseq
= PyTuple_GetItem(args
, i
+1);
971 sqp
->it
= PyObject_GetIter(curseq
);
972 if (sqp
->it
== NULL
) {
973 static char errmsg
[] =
974 "argument %d to map() must support iteration";
975 char errbuf
[sizeof(errmsg
) + 25];
976 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
977 PyErr_SetString(PyExc_TypeError
, errbuf
);
982 curlen
= _PyObject_LengthHint(curseq
, 8);
987 /* Get space for the result list. */
988 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
991 /* Iterate over the sequences until all have stopped. */
993 PyObject
*alist
, *item
=NULL
, *value
;
996 if (func
== Py_None
&& n
== 1)
998 else if ((alist
= PyTuple_New(n
)) == NULL
)
1001 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
1002 if (sqp
->saw_StopIteration
) {
1007 item
= PyIter_Next(sqp
->it
);
1011 if (PyErr_Occurred()) {
1017 sqp
->saw_StopIteration
= 1;
1021 PyTuple_SET_ITEM(alist
, j
, item
);
1029 if (numactive
== 0) {
1034 if (func
== Py_None
)
1037 value
= PyEval_CallObject(func
, alist
);
1043 int status
= PyList_Append(result
, value
);
1048 else if (PyList_SetItem(result
, i
, value
) < 0)
1052 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
1063 for (i
= 0; i
< n
; ++i
)
1064 Py_XDECREF(seqs
[i
].it
);
1069 PyDoc_STRVAR(map_doc
,
1070 "map(function, sequence[, sequence, ...]) -> list\n\
1072 Return a list of the results of applying the function to the items of\n\
1073 the argument sequence(s). If more than one sequence is given, the\n\
1074 function is called with an argument list consisting of the corresponding\n\
1075 item of each sequence, substituting None for missing values when not all\n\
1076 sequences have the same length. If the function is None, return a list of\n\
1077 the items of the sequence (or a list of tuples if more than one sequence).");
1081 builtin_next(PyObject
*self
, PyObject
*args
)
1084 PyObject
*def
= NULL
;
1086 if (!PyArg_UnpackTuple(args
, "next", 1, 2, &it
, &def
))
1088 if (!PyIter_Check(it
)) {
1089 PyErr_Format(PyExc_TypeError
,
1090 "%.200s object is not an iterator",
1091 it
->ob_type
->tp_name
);
1095 res
= (*it
->ob_type
->tp_iternext
)(it
);
1098 } else if (def
!= NULL
) {
1099 if (PyErr_Occurred()) {
1100 if (!PyErr_ExceptionMatches(PyExc_StopIteration
))
1106 } else if (PyErr_Occurred()) {
1109 PyErr_SetNone(PyExc_StopIteration
);
1114 PyDoc_STRVAR(next_doc
,
1115 "next(iterator[, default])\n\
1117 Return the next item from the iterator. If default is given and the iterator\n\
1118 is exhausted, it is returned instead of raising StopIteration.");
1122 builtin_setattr(PyObject
*self
, PyObject
*args
)
1128 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
1130 if (PyObject_SetAttr(v
, name
, value
) != 0)
1136 PyDoc_STRVAR(setattr_doc
,
1137 "setattr(object, name, value)\n\
1139 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1144 builtin_delattr(PyObject
*self
, PyObject
*args
)
1149 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
1151 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1157 PyDoc_STRVAR(delattr_doc
,
1158 "delattr(object, name)\n\
1160 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1165 builtin_hash(PyObject
*self
, PyObject
*v
)
1169 x
= PyObject_Hash(v
);
1172 return PyInt_FromLong(x
);
1175 PyDoc_STRVAR(hash_doc
,
1176 "hash(object) -> integer\n\
1178 Return a hash value for the object. Two objects with the same value have\n\
1179 the same hash value. The reverse is not necessarily true, but likely.");
1183 builtin_hex(PyObject
*self
, PyObject
*v
)
1185 PyNumberMethods
*nb
;
1188 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1189 nb
->nb_hex
== NULL
) {
1190 PyErr_SetString(PyExc_TypeError
,
1191 "hex() argument can't be converted to hex");
1194 res
= (*nb
->nb_hex
)(v
);
1195 if (res
&& !PyString_Check(res
)) {
1196 PyErr_Format(PyExc_TypeError
,
1197 "__hex__ returned non-string (type %.200s)",
1198 res
->ob_type
->tp_name
);
1205 PyDoc_STRVAR(hex_doc
,
1206 "hex(number) -> string\n\
1208 Return the hexadecimal representation of an integer or long integer.");
1211 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
1214 builtin_input(PyObject
*self
, PyObject
*args
)
1219 PyObject
*globals
, *locals
;
1222 line
= builtin_raw_input(self
, args
);
1225 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1227 while (*str
== ' ' || *str
== '\t')
1229 globals
= PyEval_GetGlobals();
1230 locals
= PyEval_GetLocals();
1231 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1232 if (PyDict_SetItemString(globals
, "__builtins__",
1233 PyEval_GetBuiltins()) != 0)
1237 PyEval_MergeCompilerFlags(&cf
);
1238 res
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
1243 PyDoc_STRVAR(input_doc
,
1244 "input([prompt]) -> value\n\
1246 Equivalent to eval(raw_input(prompt)).");
1250 builtin_intern(PyObject
*self
, PyObject
*args
)
1253 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1255 if (!PyString_CheckExact(s
)) {
1256 PyErr_SetString(PyExc_TypeError
,
1257 "can't intern subclass of string");
1261 PyString_InternInPlace(&s
);
1265 PyDoc_STRVAR(intern_doc
,
1266 "intern(string) -> string\n\
1268 ``Intern'' the given string. This enters the string in the (global)\n\
1269 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1270 Return the string itself or the previously interned string object with the\n\
1275 builtin_iter(PyObject
*self
, PyObject
*args
)
1277 PyObject
*v
, *w
= NULL
;
1279 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1282 return PyObject_GetIter(v
);
1283 if (!PyCallable_Check(v
)) {
1284 PyErr_SetString(PyExc_TypeError
,
1285 "iter(v, w): v must be callable");
1288 return PyCallIter_New(v
, w
);
1291 PyDoc_STRVAR(iter_doc
,
1292 "iter(collection) -> iterator\n\
1293 iter(callable, sentinel) -> iterator\n\
1295 Get an iterator from an object. In the first form, the argument must\n\
1296 supply its own iterator, or be a sequence.\n\
1297 In the second form, the callable is called until it returns the sentinel.");
1301 builtin_len(PyObject
*self
, PyObject
*v
)
1305 res
= PyObject_Size(v
);
1306 if (res
< 0 && PyErr_Occurred())
1308 return PyInt_FromSsize_t(res
);
1311 PyDoc_STRVAR(len_doc
,
1312 "len(object) -> integer\n\
1314 Return the number of items of a sequence or mapping.");
1318 builtin_locals(PyObject
*self
)
1322 d
= PyEval_GetLocals();
1327 PyDoc_STRVAR(locals_doc
,
1328 "locals() -> dictionary\n\
1330 Update and return a dictionary containing the current scope's local variables.");
1334 min_max(PyObject
*args
, PyObject
*kwds
, int op
)
1336 PyObject
*v
, *it
, *item
, *val
, *maxitem
, *maxval
, *keyfunc
=NULL
;
1337 const char *name
= op
== Py_LT
? "min" : "max";
1339 if (PyTuple_Size(args
) > 1)
1341 else if (!PyArg_UnpackTuple(args
, (char *)name
, 1, 1, &v
))
1344 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
)) {
1345 keyfunc
= PyDict_GetItemString(kwds
, "key");
1346 if (PyDict_Size(kwds
)!=1 || keyfunc
== NULL
) {
1347 PyErr_Format(PyExc_TypeError
,
1348 "%s() got an unexpected keyword argument", name
);
1354 it
= PyObject_GetIter(v
);
1356 Py_XDECREF(keyfunc
);
1360 maxitem
= NULL
; /* the result */
1361 maxval
= NULL
; /* the value associated with the result */
1362 while (( item
= PyIter_Next(it
) )) {
1363 /* get the value from the key function */
1364 if (keyfunc
!= NULL
) {
1365 val
= PyObject_CallFunctionObjArgs(keyfunc
, item
, NULL
);
1369 /* no key function; the value is the item */
1375 /* maximum value and item are unset; set them */
1376 if (maxval
== NULL
) {
1380 /* maximum value and item are set; update them as necessary */
1382 int cmp
= PyObject_RichCompareBool(val
, maxval
, op
);
1384 goto Fail_it_item_and_val
;
1397 if (PyErr_Occurred())
1399 if (maxval
== NULL
) {
1400 PyErr_Format(PyExc_ValueError
,
1401 "%s() arg is an empty sequence", name
);
1402 assert(maxitem
== NULL
);
1407 Py_XDECREF(keyfunc
);
1410 Fail_it_item_and_val
:
1416 Py_XDECREF(maxitem
);
1418 Py_XDECREF(keyfunc
);
1423 builtin_min(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1425 return min_max(args
, kwds
, Py_LT
);
1428 PyDoc_STRVAR(min_doc
,
1429 "min(iterable[, key=func]) -> value\n\
1430 min(a, b, c, ...[, key=func]) -> value\n\
1432 With a single iterable argument, return its smallest item.\n\
1433 With two or more arguments, return the smallest argument.");
1437 builtin_max(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1439 return min_max(args
, kwds
, Py_GT
);
1442 PyDoc_STRVAR(max_doc
,
1443 "max(iterable[, key=func]) -> value\n\
1444 max(a, b, c, ...[, key=func]) -> value\n\
1446 With a single iterable argument, return its largest item.\n\
1447 With two or more arguments, return the largest argument.");
1451 builtin_oct(PyObject
*self
, PyObject
*v
)
1453 PyNumberMethods
*nb
;
1456 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1457 nb
->nb_oct
== NULL
) {
1458 PyErr_SetString(PyExc_TypeError
,
1459 "oct() argument can't be converted to oct");
1462 res
= (*nb
->nb_oct
)(v
);
1463 if (res
&& !PyString_Check(res
)) {
1464 PyErr_Format(PyExc_TypeError
,
1465 "__oct__ returned non-string (type %.200s)",
1466 res
->ob_type
->tp_name
);
1473 PyDoc_STRVAR(oct_doc
,
1474 "oct(number) -> string\n\
1476 Return the octal representation of an integer or long integer.");
1480 builtin_open(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1482 return PyObject_Call((PyObject
*)&PyFile_Type
, args
, kwds
);
1485 PyDoc_STRVAR(open_doc
,
1486 "open(name[, mode[, buffering]]) -> file object\n\
1488 Open a file using the file() type, returns a file object. This is the\n\
1489 preferred way to open a file. See file.__doc__ for further information.");
1493 builtin_ord(PyObject
*self
, PyObject
* obj
)
1498 if (PyString_Check(obj
)) {
1499 size
= PyString_GET_SIZE(obj
);
1501 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1502 return PyInt_FromLong(ord
);
1504 } else if (PyByteArray_Check(obj
)) {
1505 size
= PyByteArray_GET_SIZE(obj
);
1507 ord
= (long)((unsigned char)*PyByteArray_AS_STRING(obj
));
1508 return PyInt_FromLong(ord
);
1511 #ifdef Py_USING_UNICODE
1512 } else if (PyUnicode_Check(obj
)) {
1513 size
= PyUnicode_GET_SIZE(obj
);
1515 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1516 return PyInt_FromLong(ord
);
1520 PyErr_Format(PyExc_TypeError
,
1521 "ord() expected string of length 1, but " \
1522 "%.200s found", obj
->ob_type
->tp_name
);
1526 PyErr_Format(PyExc_TypeError
,
1527 "ord() expected a character, "
1528 "but string of length %zd found",
1533 PyDoc_STRVAR(ord_doc
,
1534 "ord(c) -> integer\n\
1536 Return the integer ordinal of a one-character string.");
1540 builtin_pow(PyObject
*self
, PyObject
*args
)
1542 PyObject
*v
, *w
, *z
= Py_None
;
1544 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1546 return PyNumber_Power(v
, w
, z
);
1549 PyDoc_STRVAR(pow_doc
,
1550 "pow(x, y[, z]) -> number\n\
1552 With two arguments, equivalent to x**y. With three arguments,\n\
1553 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1557 builtin_print(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1559 static char *kwlist
[] = {"sep", "end", "file", 0};
1560 static PyObject
*dummy_args
= NULL
;
1561 static PyObject
*unicode_newline
= NULL
, *unicode_space
= NULL
;
1562 static PyObject
*str_newline
= NULL
, *str_space
= NULL
;
1563 PyObject
*newline
, *space
;
1564 PyObject
*sep
= NULL
, *end
= NULL
, *file
= NULL
;
1565 int i
, err
, use_unicode
= 0;
1567 if (dummy_args
== NULL
) {
1568 if (!(dummy_args
= PyTuple_New(0)))
1571 if (str_newline
== NULL
) {
1572 str_newline
= PyString_FromString("\n");
1573 if (str_newline
== NULL
)
1575 str_space
= PyString_FromString(" ");
1576 if (str_space
== NULL
) {
1577 Py_CLEAR(str_newline
);
1580 unicode_newline
= PyUnicode_FromString("\n");
1581 if (unicode_newline
== NULL
) {
1582 Py_CLEAR(str_newline
);
1583 Py_CLEAR(str_space
);
1586 unicode_space
= PyUnicode_FromString(" ");
1587 if (unicode_space
== NULL
) {
1588 Py_CLEAR(str_newline
);
1589 Py_CLEAR(str_space
);
1590 Py_CLEAR(unicode_space
);
1594 if (!PyArg_ParseTupleAndKeywords(dummy_args
, kwds
, "|OOO:print",
1595 kwlist
, &sep
, &end
, &file
))
1597 if (file
== NULL
|| file
== Py_None
) {
1598 file
= PySys_GetObject("stdout");
1599 /* sys.stdout may be None when FILE* stdout isn't connected */
1600 if (file
== Py_None
)
1603 if (sep
== Py_None
) {
1607 if (PyUnicode_Check(sep
)) {
1610 else if (!PyString_Check(sep
)) {
1611 PyErr_Format(PyExc_TypeError
,
1612 "sep must be None, str or unicode, not %.200s",
1613 sep
->ob_type
->tp_name
);
1620 if (PyUnicode_Check(end
)) {
1623 else if (!PyString_Check(end
)) {
1624 PyErr_Format(PyExc_TypeError
,
1625 "end must be None, str or unicode, not %.200s",
1626 end
->ob_type
->tp_name
);
1632 for (i
= 0; i
< PyTuple_Size(args
); i
++) {
1633 if (PyUnicode_Check(PyTuple_GET_ITEM(args
, i
))) {
1640 newline
= unicode_newline
;
1641 space
= unicode_space
;
1644 newline
= str_newline
;
1648 for (i
= 0; i
< PyTuple_Size(args
); i
++) {
1651 err
= PyFile_WriteObject(space
, file
,
1654 err
= PyFile_WriteObject(sep
, file
,
1659 err
= PyFile_WriteObject(PyTuple_GetItem(args
, i
), file
,
1666 err
= PyFile_WriteObject(newline
, file
, Py_PRINT_RAW
);
1668 err
= PyFile_WriteObject(end
, file
, Py_PRINT_RAW
);
1675 PyDoc_STRVAR(print_doc
,
1676 "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1678 Prints the values to a stream, or to sys.stdout by default.\n\
1679 Optional keyword arguments:\n\
1680 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1681 sep: string inserted between values, default a space.\n\
1682 end: string appended after the last value, default a newline.");
1685 /* Return number of items in range (lo, hi, step), when arguments are
1686 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1687 * & only if the true value is too large to fit in a signed long.
1688 * Arguments MUST return 1 with either PyInt_Check() or
1689 * PyLong_Check(). Return -1 when there is an error.
1692 get_len_of_range_longs(PyObject
*lo
, PyObject
*hi
, PyObject
*step
)
1694 /* -------------------------------------------------------------
1695 Algorithm is equal to that of get_len_of_range(), but it operates
1696 on PyObjects (which are assumed to be PyLong or PyInt objects).
1697 ---------------------------------------------------------------*/
1699 PyObject
*diff
= NULL
;
1700 PyObject
*one
= NULL
;
1701 PyObject
*tmp1
= NULL
, *tmp2
= NULL
, *tmp3
= NULL
;
1702 /* holds sub-expression evaluations */
1704 /* if (lo >= hi), return length of 0. */
1705 if (PyObject_Compare(lo
, hi
) >= 0)
1708 if ((one
= PyLong_FromLong(1L)) == NULL
)
1711 if ((tmp1
= PyNumber_Subtract(hi
, lo
)) == NULL
)
1714 if ((diff
= PyNumber_Subtract(tmp1
, one
)) == NULL
)
1717 if ((tmp2
= PyNumber_FloorDivide(diff
, step
)) == NULL
)
1720 if ((tmp3
= PyNumber_Add(tmp2
, one
)) == NULL
)
1723 n
= PyLong_AsLong(tmp3
);
1724 if (PyErr_Occurred()) { /* Check for Overflow */
1745 /* An extension of builtin_range() that handles the case when PyLong
1746 * arguments are given. */
1748 handle_range_longs(PyObject
*self
, PyObject
*args
)
1751 PyObject
*ihigh
= NULL
;
1752 PyObject
*istep
= NULL
;
1754 PyObject
*curnum
= NULL
;
1760 PyObject
*zero
= PyLong_FromLong(0);
1765 if (!PyArg_UnpackTuple(args
, "range", 1, 3, &ilow
, &ihigh
, &istep
)) {
1770 /* Figure out which way we were called, supply defaults, and be
1771 * sure to incref everything so that the decrefs at the end
1774 assert(ilow
!= NULL
);
1775 if (ihigh
== NULL
) {
1776 /* only 1 arg -- it's the upper limit */
1780 assert(ihigh
!= NULL
);
1783 /* ihigh correct now; do ilow */
1788 /* ilow and ihigh correct now; do istep */
1789 if (istep
== NULL
) {
1790 istep
= PyLong_FromLong(1L);
1798 if (!PyInt_Check(ilow
) && !PyLong_Check(ilow
)) {
1799 PyErr_Format(PyExc_TypeError
,
1800 "range() integer start argument expected, got %s.",
1801 ilow
->ob_type
->tp_name
);
1805 if (!PyInt_Check(ihigh
) && !PyLong_Check(ihigh
)) {
1806 PyErr_Format(PyExc_TypeError
,
1807 "range() integer end argument expected, got %s.",
1808 ihigh
->ob_type
->tp_name
);
1812 if (!PyInt_Check(istep
) && !PyLong_Check(istep
)) {
1813 PyErr_Format(PyExc_TypeError
,
1814 "range() integer step argument expected, got %s.",
1815 istep
->ob_type
->tp_name
);
1819 if (PyObject_Cmp(istep
, zero
, &cmp_result
) == -1)
1821 if (cmp_result
== 0) {
1822 PyErr_SetString(PyExc_ValueError
,
1823 "range() step argument must not be zero");
1828 bign
= get_len_of_range_longs(ilow
, ihigh
, istep
);
1830 PyObject
*neg_istep
= PyNumber_Negative(istep
);
1831 if (neg_istep
== NULL
)
1833 bign
= get_len_of_range_longs(ihigh
, ilow
, neg_istep
);
1834 Py_DECREF(neg_istep
);
1838 if (bign
< 0 || (long)n
!= bign
) {
1839 PyErr_SetString(PyExc_OverflowError
,
1840 "range() result has too many items");
1851 for (i
= 0; i
< n
; i
++) {
1852 PyObject
*w
= PyNumber_Long(curnum
);
1857 PyList_SET_ITEM(v
, i
, w
);
1859 tmp_num
= PyNumber_Add(curnum
, istep
);
1860 if (tmp_num
== NULL
)
1883 /* Return number of items in range/xrange (lo, hi, step). step > 0
1884 * required. Return a value < 0 if & only if the true value is too
1885 * large to fit in a signed long.
1888 get_len_of_range(long lo
, long hi
, long step
)
1890 /* -------------------------------------------------------------
1891 If lo >= hi, the range is empty.
1892 Else if n values are in the range, the last one is
1893 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1894 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1895 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1896 the RHS is non-negative and so truncation is the same as the
1897 floor. Letting M be the largest positive long, the worst case
1898 for the RHS numerator is hi=M, lo=-M-1, and then
1899 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1900 precision to compute the RHS exactly.
1901 ---------------------------------------------------------------*/
1904 unsigned long uhi
= (unsigned long)hi
;
1905 unsigned long ulo
= (unsigned long)lo
;
1906 unsigned long diff
= uhi
- ulo
- 1;
1907 n
= (long)(diff
/ (unsigned long)step
+ 1);
1913 builtin_range(PyObject
*self
, PyObject
*args
)
1915 long ilow
= 0, ihigh
= 0, istep
= 1;
1921 if (PyTuple_Size(args
) <= 1) {
1922 if (!PyArg_ParseTuple(args
,
1923 "l;range() requires 1-3 int arguments",
1926 return handle_range_longs(self
, args
);
1930 if (!PyArg_ParseTuple(args
,
1931 "ll|l;range() requires 1-3 int arguments",
1932 &ilow
, &ihigh
, &istep
)) {
1934 return handle_range_longs(self
, args
);
1938 PyErr_SetString(PyExc_ValueError
,
1939 "range() step argument must not be zero");
1943 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1945 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1947 if (bign
< 0 || (long)n
!= bign
) {
1948 PyErr_SetString(PyExc_OverflowError
,
1949 "range() result has too many items");
1955 for (i
= 0; i
< n
; i
++) {
1956 PyObject
*w
= PyInt_FromLong(ilow
);
1961 PyList_SET_ITEM(v
, i
, w
);
1967 PyDoc_STRVAR(range_doc
,
1968 "range([start,] stop[, step]) -> list of integers\n\
1970 Return a list containing an arithmetic progression of integers.\n\
1971 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1972 When step is given, it specifies the increment (or decrement).\n\
1973 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1974 These are exactly the valid indices for a list of 4 elements.");
1978 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1981 PyObject
*fin
= PySys_GetObject("stdin");
1982 PyObject
*fout
= PySys_GetObject("stdout");
1984 if (!PyArg_UnpackTuple(args
, "[raw_]input", 0, 1, &v
))
1988 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdin");
1992 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdout");
1995 if (PyFile_SoftSpace(fout
, 0)) {
1996 if (PyFile_WriteString(" ", fout
) != 0)
1999 if (PyFile_AsFile(fin
) && PyFile_AsFile(fout
)
2000 && isatty(fileno(PyFile_AsFile(fin
)))
2001 && isatty(fileno(PyFile_AsFile(fout
)))) {
2007 po
= PyObject_Str(v
);
2010 prompt
= PyString_AsString(po
);
2018 s
= PyOS_Readline(PyFile_AsFile(fin
), PyFile_AsFile(fout
),
2022 if (!PyErr_Occurred())
2023 PyErr_SetNone(PyExc_KeyboardInterrupt
);
2027 PyErr_SetNone(PyExc_EOFError
);
2030 else { /* strip trailing '\n' */
2031 size_t len
= strlen(s
);
2032 if (len
> PY_SSIZE_T_MAX
) {
2033 PyErr_SetString(PyExc_OverflowError
,
2034 "[raw_]input: input too long");
2038 result
= PyString_FromStringAndSize(s
, len
-1);
2045 if (PyFile_WriteObject(v
, fout
, Py_PRINT_RAW
) != 0)
2048 return PyFile_GetLine(fin
, -1);
2051 PyDoc_STRVAR(raw_input_doc
,
2052 "raw_input([prompt]) -> string\n\
2054 Read a string from standard input. The trailing newline is stripped.\n\
2055 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2056 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
2057 is printed without a trailing newline before reading.");
2061 builtin_reduce(PyObject
*self
, PyObject
*args
)
2063 static PyObject
*functools_reduce
= NULL
;
2065 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2066 "use functools.reduce()", 1) < 0)
2069 if (functools_reduce
== NULL
) {
2070 PyObject
*functools
= PyImport_ImportModule("functools");
2071 if (functools
== NULL
)
2073 functools_reduce
= PyObject_GetAttrString(functools
, "reduce");
2074 Py_DECREF(functools
);
2075 if (functools_reduce
== NULL
)
2078 return PyObject_Call(functools_reduce
, args
, NULL
);
2081 PyDoc_STRVAR(reduce_doc
,
2082 "reduce(function, sequence[, initial]) -> value\n\
2084 Apply a function of two arguments cumulatively to the items of a sequence,\n\
2085 from left to right, so as to reduce the sequence to a single value.\n\
2086 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2087 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2088 of the sequence in the calculation, and serves as a default when the\n\
2089 sequence is empty.");
2093 builtin_reload(PyObject
*self
, PyObject
*v
)
2095 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2099 return PyImport_ReloadModule(v
);
2102 PyDoc_STRVAR(reload_doc
,
2103 "reload(module) -> module\n\
2105 Reload the module. The module must have been successfully imported before.");
2109 builtin_repr(PyObject
*self
, PyObject
*v
)
2111 return PyObject_Repr(v
);
2114 PyDoc_STRVAR(repr_doc
,
2115 "repr(object) -> string\n\
2117 Return the canonical string representation of the object.\n\
2118 For most object types, eval(repr(object)) == object.");
2122 builtin_round(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2125 PyObject
*o_ndigits
= NULL
;
2127 static char *kwlist
[] = {"number", "ndigits", 0};
2129 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "d|O:round",
2130 kwlist
, &x
, &o_ndigits
))
2133 /* nans, infinities and zeros round to themselves */
2134 if (!Py_IS_FINITE(x
) || x
== 0.0)
2135 return PyFloat_FromDouble(x
);
2137 if (o_ndigits
== NULL
) {
2138 /* second argument defaults to 0 */
2142 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2143 ndigits
= PyNumber_AsSsize_t(o_ndigits
, NULL
);
2144 if (ndigits
== -1 && PyErr_Occurred())
2148 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2149 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2150 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
2151 #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2152 #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
2153 if (ndigits
> NDIGITS_MAX
)
2155 return PyFloat_FromDouble(x
);
2156 else if (ndigits
< NDIGITS_MIN
)
2157 /* return 0.0, but with sign of x */
2158 return PyFloat_FromDouble(0.0*x
);
2160 /* finite x, and ndigits is not unreasonably large */
2161 /* _Py_double_round is defined in floatobject.c */
2162 return _Py_double_round(x
, (int)ndigits
);
2167 PyDoc_STRVAR(round_doc
,
2168 "round(number[, ndigits]) -> floating point number\n\
2170 Round a number to a given precision in decimal digits (default 0 digits).\n\
2171 This always returns a floating point number. Precision may be negative.");
2174 builtin_sorted(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2176 PyObject
*newlist
, *v
, *seq
, *compare
=NULL
, *keyfunc
=NULL
, *newargs
;
2178 static char *kwlist
[] = {"iterable", "cmp", "key", "reverse", 0};
2181 /* args 1-4 should match listsort in Objects/listobject.c */
2182 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|OOi:sorted",
2183 kwlist
, &seq
, &compare
, &keyfunc
, &reverse
))
2186 newlist
= PySequence_List(seq
);
2187 if (newlist
== NULL
)
2190 callable
= PyObject_GetAttrString(newlist
, "sort");
2191 if (callable
== NULL
) {
2196 newargs
= PyTuple_GetSlice(args
, 1, 4);
2197 if (newargs
== NULL
) {
2199 Py_DECREF(callable
);
2203 v
= PyObject_Call(callable
, newargs
, kwds
);
2205 Py_DECREF(callable
);
2214 PyDoc_STRVAR(sorted_doc
,
2215 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2218 builtin_vars(PyObject
*self
, PyObject
*args
)
2223 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
2226 d
= PyEval_GetLocals();
2228 if (!PyErr_Occurred())
2229 PyErr_SetString(PyExc_SystemError
,
2230 "vars(): no locals!?");
2236 d
= PyObject_GetAttrString(v
, "__dict__");
2238 PyErr_SetString(PyExc_TypeError
,
2239 "vars() argument must have __dict__ attribute");
2246 PyDoc_STRVAR(vars_doc
,
2247 "vars([object]) -> dictionary\n\
2249 Without arguments, equivalent to locals().\n\
2250 With an argument, equivalent to object.__dict__.");
2254 builtin_sum(PyObject
*self
, PyObject
*args
)
2257 PyObject
*result
= NULL
;
2258 PyObject
*temp
, *item
, *iter
;
2260 if (!PyArg_UnpackTuple(args
, "sum", 1, 2, &seq
, &result
))
2263 iter
= PyObject_GetIter(seq
);
2267 if (result
== NULL
) {
2268 result
= PyInt_FromLong(0);
2269 if (result
== NULL
) {
2274 /* reject string values for 'start' parameter */
2275 if (PyObject_TypeCheck(result
, &PyBaseString_Type
)) {
2276 PyErr_SetString(PyExc_TypeError
,
2277 "sum() can't sum strings [use ''.join(seq) instead]");
2285 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2286 Assumes all inputs are the same type. If the assumption fails, default
2287 to the more general routine.
2289 if (PyInt_CheckExact(result
)) {
2290 long i_result
= PyInt_AS_LONG(result
);
2293 while(result
== NULL
) {
2294 item
= PyIter_Next(iter
);
2297 if (PyErr_Occurred())
2299 return PyInt_FromLong(i_result
);
2301 if (PyInt_CheckExact(item
)) {
2302 long b
= PyInt_AS_LONG(item
);
2303 long x
= i_result
+ b
;
2304 if ((x
^i_result
) >= 0 || (x
^b
) >= 0) {
2310 /* Either overflowed or is not an int. Restore real objects and process normally */
2311 result
= PyInt_FromLong(i_result
);
2312 temp
= PyNumber_Add(result
, item
);
2316 if (result
== NULL
) {
2323 if (PyFloat_CheckExact(result
)) {
2324 double f_result
= PyFloat_AS_DOUBLE(result
);
2327 while(result
== NULL
) {
2328 item
= PyIter_Next(iter
);
2331 if (PyErr_Occurred())
2333 return PyFloat_FromDouble(f_result
);
2335 if (PyFloat_CheckExact(item
)) {
2336 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
2337 f_result
+= PyFloat_AS_DOUBLE(item
);
2338 PyFPE_END_PROTECT(f_result
)
2342 if (PyInt_CheckExact(item
)) {
2343 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
2344 f_result
+= (double)PyInt_AS_LONG(item
);
2345 PyFPE_END_PROTECT(f_result
)
2349 result
= PyFloat_FromDouble(f_result
);
2350 temp
= PyNumber_Add(result
, item
);
2354 if (result
== NULL
) {
2363 item
= PyIter_Next(iter
);
2365 /* error, or end-of-sequence */
2366 if (PyErr_Occurred()) {
2372 /* It's tempting to use PyNumber_InPlaceAdd instead of
2373 PyNumber_Add here, to avoid quadratic running time
2374 when doing 'sum(list_of_lists, [])'. However, this
2375 would produce a change in behaviour: a snippet like
2378 sum([[x] for x in range(10)], empty)
2380 would change the value of empty. */
2381 temp
= PyNumber_Add(result
, item
);
2392 PyDoc_STRVAR(sum_doc
,
2393 "sum(sequence[, start]) -> value\n\
2395 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2396 of parameter 'start' (which defaults to 0). When the sequence is\n\
2397 empty, returns start.");
2401 builtin_isinstance(PyObject
*self
, PyObject
*args
)
2407 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
2410 retval
= PyObject_IsInstance(inst
, cls
);
2413 return PyBool_FromLong(retval
);
2416 PyDoc_STRVAR(isinstance_doc
,
2417 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2419 Return whether an object is an instance of a class or of a subclass thereof.\n\
2420 With a type as second argument, return whether that is the object's type.\n\
2421 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2422 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2426 builtin_issubclass(PyObject
*self
, PyObject
*args
)
2432 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
2435 retval
= PyObject_IsSubclass(derived
, cls
);
2438 return PyBool_FromLong(retval
);
2441 PyDoc_STRVAR(issubclass_doc
,
2442 "issubclass(C, B) -> bool\n\
2444 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2445 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2446 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2450 builtin_zip(PyObject
*self
, PyObject
*args
)
2453 const Py_ssize_t itemsize
= PySequence_Length(args
);
2455 PyObject
*itlist
; /* tuple of iterators */
2456 Py_ssize_t len
; /* guess at result length */
2459 return PyList_New(0);
2461 /* args must be a tuple */
2462 assert(PyTuple_Check(args
));
2464 /* Guess at result length: the shortest of the input lengths.
2465 If some argument refuses to say, we refuse to guess too, lest
2466 an argument like xrange(sys.maxint) lead us astray.*/
2467 len
= -1; /* unknown */
2468 for (i
= 0; i
< itemsize
; ++i
) {
2469 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2470 Py_ssize_t thislen
= _PyObject_LengthHint(item
, -2);
2477 else if (len
< 0 || thislen
< len
)
2481 /* allocate result list */
2483 len
= 10; /* arbitrary */
2484 if ((ret
= PyList_New(len
)) == NULL
)
2487 /* obtain iterators */
2488 itlist
= PyTuple_New(itemsize
);
2491 for (i
= 0; i
< itemsize
; ++i
) {
2492 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2493 PyObject
*it
= PyObject_GetIter(item
);
2495 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2496 PyErr_Format(PyExc_TypeError
,
2497 "zip argument #%zd must support iteration",
2499 goto Fail_ret_itlist
;
2501 PyTuple_SET_ITEM(itlist
, i
, it
);
2504 /* build result into ret list */
2505 for (i
= 0; ; ++i
) {
2507 PyObject
*next
= PyTuple_New(itemsize
);
2509 goto Fail_ret_itlist
;
2511 for (j
= 0; j
< itemsize
; j
++) {
2512 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
2513 PyObject
*item
= PyIter_Next(it
);
2515 if (PyErr_Occurred()) {
2523 PyTuple_SET_ITEM(next
, j
, item
);
2527 PyList_SET_ITEM(ret
, i
, next
);
2529 int status
= PyList_Append(ret
, next
);
2533 goto Fail_ret_itlist
;
2538 if (ret
!= NULL
&& i
< len
) {
2539 /* The list is too big. */
2540 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
2553 PyDoc_STRVAR(zip_doc
,
2554 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2556 Return a list of tuples, where each tuple contains the i-th element\n\
2557 from each of the argument sequences. The returned list is truncated\n\
2558 in length to the length of the shortest argument sequence.");
2561 static PyMethodDef builtin_methods
[] = {
2562 {"__import__", (PyCFunction
)builtin___import__
, METH_VARARGS
| METH_KEYWORDS
, import_doc
},
2563 {"abs", builtin_abs
, METH_O
, abs_doc
},
2564 {"all", builtin_all
, METH_O
, all_doc
},
2565 {"any", builtin_any
, METH_O
, any_doc
},
2566 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
2567 {"bin", builtin_bin
, METH_O
, bin_doc
},
2568 {"callable", builtin_callable
, METH_O
, callable_doc
},
2569 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2570 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
2571 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
2572 {"compile", (PyCFunction
)builtin_compile
, METH_VARARGS
| METH_KEYWORDS
, compile_doc
},
2573 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2574 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2575 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2576 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2577 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
2578 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
2579 {"format", builtin_format
, METH_VARARGS
, format_doc
},
2580 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2581 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2582 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2583 {"hash", builtin_hash
, METH_O
, hash_doc
},
2584 {"hex", builtin_hex
, METH_O
, hex_doc
},
2585 {"id", builtin_id
, METH_O
, id_doc
},
2586 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2587 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
2588 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2589 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2590 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2591 {"len", builtin_len
, METH_O
, len_doc
},
2592 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2593 {"map", builtin_map
, METH_VARARGS
, map_doc
},
2594 {"max", (PyCFunction
)builtin_max
, METH_VARARGS
| METH_KEYWORDS
, max_doc
},
2595 {"min", (PyCFunction
)builtin_min
, METH_VARARGS
| METH_KEYWORDS
, min_doc
},
2596 {"next", builtin_next
, METH_VARARGS
, next_doc
},
2597 {"oct", builtin_oct
, METH_O
, oct_doc
},
2598 {"open", (PyCFunction
)builtin_open
, METH_VARARGS
| METH_KEYWORDS
, open_doc
},
2599 {"ord", builtin_ord
, METH_O
, ord_doc
},
2600 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2601 {"print", (PyCFunction
)builtin_print
, METH_VARARGS
| METH_KEYWORDS
, print_doc
},
2602 {"range", builtin_range
, METH_VARARGS
, range_doc
},
2603 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
2604 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
2605 {"reload", builtin_reload
, METH_O
, reload_doc
},
2606 {"repr", builtin_repr
, METH_O
, repr_doc
},
2607 {"round", (PyCFunction
)builtin_round
, METH_VARARGS
| METH_KEYWORDS
, round_doc
},
2608 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2609 {"sorted", (PyCFunction
)builtin_sorted
, METH_VARARGS
| METH_KEYWORDS
, sorted_doc
},
2610 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2611 #ifdef Py_USING_UNICODE
2612 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
2614 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2615 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
2619 PyDoc_STRVAR(builtin_doc
,
2620 "Built-in functions, exceptions, and other objects.\n\
2622 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2625 _PyBuiltin_Init(void)
2627 PyObject
*mod
, *dict
, *debug
;
2628 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2629 builtin_doc
, (PyObject
*)NULL
,
2630 PYTHON_API_VERSION
);
2633 dict
= PyModule_GetDict(mod
);
2635 #ifdef Py_TRACE_REFS
2636 /* __builtin__ exposes a number of statically allocated objects
2637 * that, before this code was added in 2.3, never showed up in
2638 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2639 * result, programs leaking references to None and False (etc)
2640 * couldn't be diagnosed by examining sys.getobjects(0).
2642 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2644 #define ADD_TO_ALL(OBJECT) (void)0
2647 #define SETBUILTIN(NAME, OBJECT) \
2648 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2652 SETBUILTIN("None", Py_None
);
2653 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2654 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2655 SETBUILTIN("False", Py_False
);
2656 SETBUILTIN("True", Py_True
);
2657 SETBUILTIN("basestring", &PyBaseString_Type
);
2658 SETBUILTIN("bool", &PyBool_Type
);
2659 SETBUILTIN("memoryview", &PyMemoryView_Type
);
2660 SETBUILTIN("bytearray", &PyByteArray_Type
);
2661 SETBUILTIN("bytes", &PyString_Type
);
2662 SETBUILTIN("buffer", &PyBuffer_Type
);
2663 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2664 #ifndef WITHOUT_COMPLEX
2665 SETBUILTIN("complex", &PyComplex_Type
);
2667 SETBUILTIN("dict", &PyDict_Type
);
2668 SETBUILTIN("enumerate", &PyEnum_Type
);
2669 SETBUILTIN("file", &PyFile_Type
);
2670 SETBUILTIN("float", &PyFloat_Type
);
2671 SETBUILTIN("frozenset", &PyFrozenSet_Type
);
2672 SETBUILTIN("property", &PyProperty_Type
);
2673 SETBUILTIN("int", &PyInt_Type
);
2674 SETBUILTIN("list", &PyList_Type
);
2675 SETBUILTIN("long", &PyLong_Type
);
2676 SETBUILTIN("object", &PyBaseObject_Type
);
2677 SETBUILTIN("reversed", &PyReversed_Type
);
2678 SETBUILTIN("set", &PySet_Type
);
2679 SETBUILTIN("slice", &PySlice_Type
);
2680 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2681 SETBUILTIN("str", &PyString_Type
);
2682 SETBUILTIN("super", &PySuper_Type
);
2683 SETBUILTIN("tuple", &PyTuple_Type
);
2684 SETBUILTIN("type", &PyType_Type
);
2685 SETBUILTIN("xrange", &PyRange_Type
);
2686 #ifdef Py_USING_UNICODE
2687 SETBUILTIN("unicode", &PyUnicode_Type
);
2689 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2690 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2701 /* Helper for filter(): filter a tuple through a function */
2704 filtertuple(PyObject
*func
, PyObject
*tuple
)
2708 Py_ssize_t len
= PyTuple_Size(tuple
);
2711 if (PyTuple_CheckExact(tuple
))
2714 tuple
= PyTuple_New(0);
2718 if ((result
= PyTuple_New(len
)) == NULL
)
2721 for (i
= j
= 0; i
< len
; ++i
) {
2722 PyObject
*item
, *good
;
2725 if (tuple
->ob_type
->tp_as_sequence
&&
2726 tuple
->ob_type
->tp_as_sequence
->sq_item
) {
2727 item
= tuple
->ob_type
->tp_as_sequence
->sq_item(tuple
, i
);
2731 PyErr_SetString(PyExc_TypeError
, "filter(): unsubscriptable tuple");
2734 if (func
== Py_None
) {
2739 PyObject
*arg
= PyTuple_Pack(1, item
);
2744 good
= PyEval_CallObject(func
, arg
);
2751 ok
= PyObject_IsTrue(good
);
2754 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2761 if (_PyTuple_Resize(&result
, j
) < 0)
2772 /* Helper for filter(): filter a string through a function */
2775 filterstring(PyObject
*func
, PyObject
*strobj
)
2779 Py_ssize_t len
= PyString_Size(strobj
);
2780 Py_ssize_t outlen
= len
;
2782 if (func
== Py_None
) {
2783 /* If it's a real string we can return the original,
2784 * as no character is ever false and __getitem__
2785 * does return this character. If it's a subclass
2786 * we must go through the __getitem__ loop */
2787 if (PyString_CheckExact(strobj
)) {
2792 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2795 for (i
= j
= 0; i
< len
; ++i
) {
2799 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2802 if (func
==Py_None
) {
2805 PyObject
*arg
, *good
;
2806 arg
= PyTuple_Pack(1, item
);
2811 good
= PyEval_CallObject(func
, arg
);
2817 ok
= PyObject_IsTrue(good
);
2822 if (!PyString_Check(item
)) {
2823 PyErr_SetString(PyExc_TypeError
, "can't filter str to str:"
2824 " __getitem__ returned different type");
2828 reslen
= PyString_GET_SIZE(item
);
2830 PyString_AS_STRING(result
)[j
++] =
2831 PyString_AS_STRING(item
)[0];
2833 /* do we need more space? */
2834 Py_ssize_t need
= j
;
2836 /* calculate space requirements while checking for overflow */
2837 if (need
> PY_SSIZE_T_MAX
- reslen
) {
2844 if (need
> PY_SSIZE_T_MAX
- len
) {
2856 need
= need
- i
- 1;
2859 assert(outlen
>= 0);
2861 if (need
> outlen
) {
2862 /* overallocate, to avoid reallocations */
2863 if (outlen
> PY_SSIZE_T_MAX
/ 2) {
2868 if (need
<2*outlen
) {
2871 if (_PyString_Resize(&result
, need
)) {
2878 PyString_AS_STRING(result
) + j
,
2879 PyString_AS_STRING(item
),
2889 _PyString_Resize(&result
, j
);
2898 #ifdef Py_USING_UNICODE
2899 /* Helper for filter(): filter a Unicode object through a function */
2902 filterunicode(PyObject
*func
, PyObject
*strobj
)
2905 register Py_ssize_t i
, j
;
2906 Py_ssize_t len
= PyUnicode_GetSize(strobj
);
2907 Py_ssize_t outlen
= len
;
2909 if (func
== Py_None
) {
2910 /* If it's a real string we can return the original,
2911 * as no character is ever false and __getitem__
2912 * does return this character. If it's a subclass
2913 * we must go through the __getitem__ loop */
2914 if (PyUnicode_CheckExact(strobj
)) {
2919 if ((result
= PyUnicode_FromUnicode(NULL
, len
)) == NULL
)
2922 for (i
= j
= 0; i
< len
; ++i
) {
2923 PyObject
*item
, *arg
, *good
;
2926 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2929 if (func
== Py_None
) {
2932 arg
= PyTuple_Pack(1, item
);
2937 good
= PyEval_CallObject(func
, arg
);
2943 ok
= PyObject_IsTrue(good
);
2948 if (!PyUnicode_Check(item
)) {
2949 PyErr_SetString(PyExc_TypeError
,
2950 "can't filter unicode to unicode:"
2951 " __getitem__ returned different type");
2955 reslen
= PyUnicode_GET_SIZE(item
);
2957 PyUnicode_AS_UNICODE(result
)[j
++] =
2958 PyUnicode_AS_UNICODE(item
)[0];
2960 /* do we need more space? */
2961 Py_ssize_t need
= j
+ reslen
+ len
- i
- 1;
2963 /* check that didnt overflow */
2964 if ((j
> PY_SSIZE_T_MAX
- reslen
) ||
2965 ((j
+ reslen
) > PY_SSIZE_T_MAX
- len
) ||
2966 ((j
+ reslen
+ len
) < i
) ||
2967 ((j
+ reslen
+ len
- i
) <= 0)) {
2973 assert(outlen
>= 0);
2975 if (need
> outlen
) {
2977 to avoid reallocations */
2978 if (need
< 2 * outlen
) {
2979 if (outlen
> PY_SSIZE_T_MAX
/ 2) {
2987 if (PyUnicode_Resize(
2988 &result
, need
) < 0) {
2994 memcpy(PyUnicode_AS_UNICODE(result
) + j
,
2995 PyUnicode_AS_UNICODE(item
),
2996 reslen
*sizeof(Py_UNICODE
));
3004 PyUnicode_Resize(&result
, j
);