1 /* Built-in functions */
4 #include "Python-ast.h"
13 #include "unixstuff.h"
16 /* The default encoding used by the platform file system APIs
17 Can remain NULL for all platforms that don't have such a concept
19 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
20 const char *Py_FileSystemDefaultEncoding
= "mbcs";
21 #elif defined(__APPLE__)
22 const char *Py_FileSystemDefaultEncoding
= "utf-8";
24 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
28 static PyObject
*filterstring(PyObject
*, PyObject
*);
29 #ifdef Py_USING_UNICODE
30 static PyObject
*filterunicode(PyObject
*, PyObject
*);
32 static PyObject
*filtertuple (PyObject
*, PyObject
*);
35 builtin___import__(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
37 static char *kwlist
[] = {"name", "globals", "locals", "fromlist",
40 PyObject
*globals
= NULL
;
41 PyObject
*locals
= NULL
;
42 PyObject
*fromlist
= NULL
;
45 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "s|OOOi:__import__",
46 kwlist
, &name
, &globals
, &locals
, &fromlist
, &level
))
48 return PyImport_ImportModuleLevel(name
, globals
, locals
,
52 PyDoc_STRVAR(import_doc
,
53 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
55 Import a module. The globals are only used to determine the context;\n\
56 they are not modified. The locals are currently unused. The fromlist\n\
57 should be a list of names to emulate ``from name import ...'', or an\n\
58 empty list to emulate ``import name''.\n\
59 When importing a module from a package, note that __import__('A.B', ...)\n\
60 returns package A when fromlist is empty, but its submodule B when\n\
61 fromlist is not empty. Level is used to determine whether to perform \n\
62 absolute or relative imports. -1 is the original strategy of attempting\n\
63 both absolute and relative imports, 0 is absolute, a positive number\n\
64 is the number of parent directories to search relative to the current module.");
68 builtin_abs(PyObject
*self
, PyObject
*v
)
70 return PyNumber_Absolute(v
);
74 "abs(number) -> number\n\
76 Return the absolute value of the argument.");
79 builtin_all(PyObject
*self
, PyObject
*v
)
82 PyObject
*(*iternext
)(PyObject
*);
85 it
= PyObject_GetIter(v
);
88 iternext
= *Py_TYPE(it
)->tp_iternext
;
94 cmp
= PyObject_IsTrue(item
);
106 if (PyErr_Occurred()) {
107 if (PyErr_ExceptionMatches(PyExc_StopIteration
))
115 PyDoc_STRVAR(all_doc
,
116 "all(iterable) -> bool\n\
118 Return True if bool(x) is True for all values x in the iterable.");
121 builtin_any(PyObject
*self
, PyObject
*v
)
124 PyObject
*(*iternext
)(PyObject
*);
127 it
= PyObject_GetIter(v
);
130 iternext
= *Py_TYPE(it
)->tp_iternext
;
136 cmp
= PyObject_IsTrue(item
);
148 if (PyErr_Occurred()) {
149 if (PyErr_ExceptionMatches(PyExc_StopIteration
))
157 PyDoc_STRVAR(any_doc
,
158 "any(iterable) -> bool\n\
160 Return True if bool(x) is True for any x in the iterable.");
163 builtin_apply(PyObject
*self
, PyObject
*args
)
165 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
166 PyObject
*t
= NULL
, *retval
= NULL
;
168 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
169 "use func(*args, **kwargs)", 1) < 0)
172 if (!PyArg_UnpackTuple(args
, "apply", 1, 3, &func
, &alist
, &kwdict
))
175 if (!PyTuple_Check(alist
)) {
176 if (!PySequence_Check(alist
)) {
177 PyErr_Format(PyExc_TypeError
,
178 "apply() arg 2 expected sequence, found %s",
179 alist
->ob_type
->tp_name
);
182 t
= PySequence_Tuple(alist
);
188 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
189 PyErr_Format(PyExc_TypeError
,
190 "apply() arg 3 expected dictionary, found %s",
191 kwdict
->ob_type
->tp_name
);
194 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
200 PyDoc_STRVAR(apply_doc
,
201 "apply(object[, args[, kwargs]]) -> value\n\
203 Call a callable object with positional arguments taken from the tuple args,\n\
204 and keyword arguments taken from the optional dictionary kwargs.\n\
205 Note that classes are callable, as are instances with a __call__() method.\n\
207 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
208 function(*args, **keywords).");
212 builtin_bin(PyObject
*self
, PyObject
*v
)
214 return PyNumber_ToBase(v
, 2);
217 PyDoc_STRVAR(bin_doc
,
218 "bin(number) -> string\n\
220 Return the binary representation of an integer or long integer.");
224 builtin_callable(PyObject
*self
, PyObject
*v
)
226 if (PyErr_WarnPy3k("callable() not supported in 3.x; "
227 "use hasattr(o, '__call__')", 1) < 0)
229 return PyBool_FromLong((long)PyCallable_Check(v
));
232 PyDoc_STRVAR(callable_doc
,
233 "callable(object) -> bool\n\
235 Return whether the object is callable (i.e., some kind of function).\n\
236 Note that classes are callable, as are instances with a __call__() method.");
240 builtin_filter(PyObject
*self
, PyObject
*args
)
242 PyObject
*func
, *seq
, *result
, *it
, *arg
;
243 Py_ssize_t len
; /* guess for result list size */
244 register Py_ssize_t j
;
246 if (!PyArg_UnpackTuple(args
, "filter", 2, 2, &func
, &seq
))
249 /* Strings and tuples return a result of the same type. */
250 if (PyString_Check(seq
))
251 return filterstring(func
, seq
);
252 #ifdef Py_USING_UNICODE
253 if (PyUnicode_Check(seq
))
254 return filterunicode(func
, seq
);
256 if (PyTuple_Check(seq
))
257 return filtertuple(func
, seq
);
259 /* Pre-allocate argument list tuple. */
260 arg
= PyTuple_New(1);
265 it
= PyObject_GetIter(seq
);
269 /* Guess a result list size. */
270 len
= _PyObject_LengthHint(seq
, 8);
272 /* Get a result list. */
273 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
274 /* Eww - can modify the list in-place. */
279 result
= PyList_New(len
);
284 /* Build the result list. */
290 item
= PyIter_Next(it
);
292 if (PyErr_Occurred())
297 if (func
== (PyObject
*)&PyBool_Type
|| func
== Py_None
) {
298 ok
= PyObject_IsTrue(item
);
302 PyTuple_SET_ITEM(arg
, 0, item
);
303 good
= PyObject_Call(func
, arg
, NULL
);
304 PyTuple_SET_ITEM(arg
, 0, NULL
);
309 ok
= PyObject_IsTrue(good
);
314 PyList_SET_ITEM(result
, j
, item
);
316 int status
= PyList_Append(result
, item
);
328 /* Cut back result list if len is too big. */
329 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
345 PyDoc_STRVAR(filter_doc
,
346 "filter(function or None, sequence) -> list, tuple, or string\n"
348 "Return those items of sequence for which function(item) is true. If\n"
349 "function is None, return the items that are true. If sequence is a tuple\n"
350 "or string, return the same type, else return a list.");
353 builtin_format(PyObject
*self
, PyObject
*args
)
356 PyObject
*format_spec
= NULL
;
358 if (!PyArg_ParseTuple(args
, "O|O:format", &value
, &format_spec
))
361 return PyObject_Format(value
, format_spec
);
364 PyDoc_STRVAR(format_doc
,
365 "format(value[, format_spec]) -> string\n\
367 Returns value.__format__(format_spec)\n\
368 format_spec defaults to \"\"");
371 builtin_chr(PyObject
*self
, PyObject
*args
)
376 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
378 if (x
< 0 || x
>= 256) {
379 PyErr_SetString(PyExc_ValueError
,
380 "chr() arg not in range(256)");
384 return PyString_FromStringAndSize(s
, 1);
387 PyDoc_STRVAR(chr_doc
,
388 "chr(i) -> character\n\
390 Return a string of one character with ordinal i; 0 <= i < 256.");
393 #ifdef Py_USING_UNICODE
395 builtin_unichr(PyObject
*self
, PyObject
*args
)
399 if (!PyArg_ParseTuple(args
, "i:unichr", &x
))
402 return PyUnicode_FromOrdinal(x
);
405 PyDoc_STRVAR(unichr_doc
,
406 "unichr(i) -> Unicode character\n\
408 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
413 builtin_cmp(PyObject
*self
, PyObject
*args
)
418 if (!PyArg_UnpackTuple(args
, "cmp", 2, 2, &a
, &b
))
420 if (PyObject_Cmp(a
, b
, &c
) < 0)
422 return PyInt_FromLong((long)c
);
425 PyDoc_STRVAR(cmp_doc
,
426 "cmp(x, y) -> integer\n\
428 Return negative if x<y, zero if x==y, positive if x>y.");
432 builtin_coerce(PyObject
*self
, PyObject
*args
)
437 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
440 if (!PyArg_UnpackTuple(args
, "coerce", 2, 2, &v
, &w
))
442 if (PyNumber_Coerce(&v
, &w
) < 0)
444 res
= PyTuple_Pack(2, v
, w
);
450 PyDoc_STRVAR(coerce_doc
,
451 "coerce(x, y) -> (x1, y1)\n\
453 Return a tuple consisting of the two numeric arguments converted to\n\
454 a common type, using the same rules as used by arithmetic operations.\n\
455 If coercion is not possible, raise TypeError.");
458 builtin_compile(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
464 int dont_inherit
= 0;
465 int supplied_flags
= 0;
467 PyObject
*result
= NULL
, *cmd
, *tmp
= NULL
;
469 static char *kwlist
[] = {"source", "filename", "mode", "flags",
470 "dont_inherit", NULL
};
471 int start
[] = {Py_file_input
, Py_eval_input
, Py_single_input
};
473 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "Oss|ii:compile",
474 kwlist
, &cmd
, &filename
, &startstr
,
475 &supplied_flags
, &dont_inherit
))
478 cf
.cf_flags
= supplied_flags
;
481 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
| PyCF_ONLY_AST
))
483 PyErr_SetString(PyExc_ValueError
,
484 "compile(): unrecognised flags");
487 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
490 PyEval_MergeCompilerFlags(&cf
);
493 if (strcmp(startstr
, "exec") == 0)
495 else if (strcmp(startstr
, "eval") == 0)
497 else if (strcmp(startstr
, "single") == 0)
500 PyErr_SetString(PyExc_ValueError
,
501 "compile() arg 3 must be 'exec', 'eval' or 'single'");
505 if (PyAST_Check(cmd
)) {
506 if (supplied_flags
& PyCF_ONLY_AST
) {
514 arena
= PyArena_New();
515 mod
= PyAST_obj2mod(cmd
, arena
, mode
);
520 result
= (PyObject
*)PyAST_Compile(mod
, filename
,
527 #ifdef Py_USING_UNICODE
528 if (PyUnicode_Check(cmd
)) {
529 tmp
= PyUnicode_AsUTF8String(cmd
);
533 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
537 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &length
))
539 if ((size_t)length
!= strlen(str
)) {
540 PyErr_SetString(PyExc_TypeError
,
541 "compile() expected string without null bytes");
544 result
= Py_CompileStringFlags(str
, filename
, start
[mode
], &cf
);
550 PyDoc_STRVAR(compile_doc
,
551 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
553 Compile the source string (a Python module, statement or expression)\n\
554 into a code object that can be executed by the exec statement or eval().\n\
555 The filename will be used for run-time error messages.\n\
556 The mode must be 'exec' to compile a module, 'single' to compile a\n\
557 single (interactive) statement, or 'eval' to compile an expression.\n\
558 The flags argument, if present, controls which future statements influence\n\
559 the compilation of the code.\n\
560 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
561 the effects of any future statements in effect in the code calling\n\
562 compile; if absent or zero these statements do influence the compilation,\n\
563 in addition to any features explicitly specified.");
566 builtin_dir(PyObject
*self
, PyObject
*args
)
568 PyObject
*arg
= NULL
;
570 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
572 return PyObject_Dir(arg
);
575 PyDoc_STRVAR(dir_doc
,
576 "dir([object]) -> list of strings\n"
578 "If called without an argument, return the names in the current scope.\n"
579 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
580 "of the given object, and of attributes reachable from it.\n"
581 "If the object supplies a method named __dir__, it will be used; otherwise\n"
582 "the default dir() logic is used and returns:\n"
583 " for a module object: the module's attributes.\n"
584 " for a class object: its attributes, and recursively the attributes\n"
586 " for any other object: its attributes, its class's attributes, and\n"
587 " recursively the attributes of its class's base classes.");
590 builtin_divmod(PyObject
*self
, PyObject
*args
)
594 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
596 return PyNumber_Divmod(v
, w
);
599 PyDoc_STRVAR(divmod_doc
,
600 "divmod(x, y) -> (div, mod)\n\
602 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
606 builtin_eval(PyObject
*self
, PyObject
*args
)
608 PyObject
*cmd
, *result
, *tmp
= NULL
;
609 PyObject
*globals
= Py_None
, *locals
= Py_None
;
613 if (!PyArg_UnpackTuple(args
, "eval", 1, 3, &cmd
, &globals
, &locals
))
615 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
616 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
619 if (globals
!= Py_None
&& !PyDict_Check(globals
)) {
620 PyErr_SetString(PyExc_TypeError
, PyMapping_Check(globals
) ?
621 "globals must be a real dict; try eval(expr, {}, mapping)"
622 : "globals must be a dict");
625 if (globals
== Py_None
) {
626 globals
= PyEval_GetGlobals();
627 if (locals
== Py_None
)
628 locals
= PyEval_GetLocals();
630 else if (locals
== Py_None
)
633 if (globals
== NULL
|| locals
== NULL
) {
634 PyErr_SetString(PyExc_TypeError
,
635 "eval must be given globals and locals "
636 "when called without a frame");
640 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
641 if (PyDict_SetItemString(globals
, "__builtins__",
642 PyEval_GetBuiltins()) != 0)
646 if (PyCode_Check(cmd
)) {
647 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
648 PyErr_SetString(PyExc_TypeError
,
649 "code object passed to eval() may not contain free variables");
652 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
655 if (!PyString_Check(cmd
) &&
656 !PyUnicode_Check(cmd
)) {
657 PyErr_SetString(PyExc_TypeError
,
658 "eval() arg 1 must be a string or code object");
663 #ifdef Py_USING_UNICODE
664 if (PyUnicode_Check(cmd
)) {
665 tmp
= PyUnicode_AsUTF8String(cmd
);
669 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
672 if (PyString_AsStringAndSize(cmd
, &str
, NULL
)) {
676 while (*str
== ' ' || *str
== '\t')
679 (void)PyEval_MergeCompilerFlags(&cf
);
680 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
685 PyDoc_STRVAR(eval_doc
,
686 "eval(source[, globals[, locals]]) -> value\n\
688 Evaluate the source in the context of globals and locals.\n\
689 The source may be a string representing a Python expression\n\
690 or a code object as returned by compile().\n\
691 The globals must be a dictionary and locals can be any mapping,\n\
692 defaulting to the current globals and locals.\n\
693 If only globals is given, locals defaults to it.\n");
697 builtin_execfile(PyObject
*self
, PyObject
*args
)
700 PyObject
*globals
= Py_None
, *locals
= Py_None
;
706 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
710 if (!PyArg_ParseTuple(args
, "s|O!O:execfile",
712 &PyDict_Type
, &globals
,
715 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
716 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
719 if (globals
== Py_None
) {
720 globals
= PyEval_GetGlobals();
721 if (locals
== Py_None
)
722 locals
= PyEval_GetLocals();
724 else if (locals
== Py_None
)
726 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
727 if (PyDict_SetItemString(globals
, "__builtins__",
728 PyEval_GetBuiltins()) != 0)
733 /* Test for existence or directory. */
738 if ((d
= dirstat(filename
))!=nil
) {
740 werrstr("is a directory");
746 #elif defined(RISCOS)
747 if (object_exists(filename
)) {
753 #else /* standard Posix */
756 if (stat(filename
, &s
) == 0) {
757 if (S_ISDIR(s
.st_mode
))
758 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
770 Py_BEGIN_ALLOW_THREADS
771 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
780 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
784 if (PyEval_MergeCompilerFlags(&cf
))
785 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
788 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
793 PyDoc_STRVAR(execfile_doc
,
794 "execfile(filename[, globals[, locals]])\n\
796 Read and execute a Python script from a file.\n\
797 The globals and locals are dictionaries, defaulting to the current\n\
798 globals and locals. If only globals is given, locals defaults to it.");
802 builtin_getattr(PyObject
*self
, PyObject
*args
)
804 PyObject
*v
, *result
, *dflt
= NULL
;
807 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
809 #ifdef Py_USING_UNICODE
810 if (PyUnicode_Check(name
)) {
811 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
817 if (!PyString_Check(name
)) {
818 PyErr_SetString(PyExc_TypeError
,
819 "getattr(): attribute name must be string");
822 result
= PyObject_GetAttr(v
, name
);
823 if (result
== NULL
&& dflt
!= NULL
&&
824 PyErr_ExceptionMatches(PyExc_AttributeError
))
833 PyDoc_STRVAR(getattr_doc
,
834 "getattr(object, name[, default]) -> value\n\
836 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
837 When a default argument is given, it is returned when the attribute doesn't\n\
838 exist; without it, an exception is raised in that case.");
842 builtin_globals(PyObject
*self
)
846 d
= PyEval_GetGlobals();
851 PyDoc_STRVAR(globals_doc
,
852 "globals() -> dictionary\n\
854 Return the dictionary containing the current scope's global variables.");
858 builtin_hasattr(PyObject
*self
, PyObject
*args
)
863 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
865 #ifdef Py_USING_UNICODE
866 if (PyUnicode_Check(name
)) {
867 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
873 if (!PyString_Check(name
)) {
874 PyErr_SetString(PyExc_TypeError
,
875 "hasattr(): attribute name must be string");
878 v
= PyObject_GetAttr(v
, name
);
880 if (!PyErr_ExceptionMatches(PyExc_Exception
))
893 PyDoc_STRVAR(hasattr_doc
,
894 "hasattr(object, name) -> bool\n\
896 Return whether the object has an attribute with the given name.\n\
897 (This is done by calling getattr(object, name) and catching exceptions.)");
901 builtin_id(PyObject
*self
, PyObject
*v
)
903 return PyLong_FromVoidPtr(v
);
907 "id(object) -> integer\n\
909 Return the identity of an object. This is guaranteed to be unique among\n\
910 simultaneously existing objects. (Hint: it's the object's memory address.)");
914 builtin_map(PyObject
*self
, PyObject
*args
)
917 PyObject
*it
; /* the iterator object */
918 int saw_StopIteration
; /* bool: did the iterator end? */
921 PyObject
*func
, *result
;
922 sequence
*seqs
= NULL
, *sqp
;
926 n
= PyTuple_Size(args
);
928 PyErr_SetString(PyExc_TypeError
,
929 "map() requires at least two args");
933 func
= PyTuple_GetItem(args
, 0);
936 if (func
== Py_None
) {
937 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
938 "use list(...)", 1) < 0)
941 /* map(None, S) is the same as list(S). */
942 return PySequence_List(PyTuple_GetItem(args
, 1));
946 /* Get space for sequence descriptors. Must NULL out the iterator
947 * pointers so that jumping to Fail_2 later doesn't see trash.
949 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
953 for (i
= 0; i
< n
; ++i
) {
954 seqs
[i
].it
= (PyObject
*)NULL
;
955 seqs
[i
].saw_StopIteration
= 0;
958 /* Do a first pass to obtain iterators for the arguments, and set len
959 * to the largest of their lengths.
962 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
967 curseq
= PyTuple_GetItem(args
, i
+1);
968 sqp
->it
= PyObject_GetIter(curseq
);
969 if (sqp
->it
== NULL
) {
970 static char errmsg
[] =
971 "argument %d to map() must support iteration";
972 char errbuf
[sizeof(errmsg
) + 25];
973 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
974 PyErr_SetString(PyExc_TypeError
, errbuf
);
979 curlen
= _PyObject_LengthHint(curseq
, 8);
984 /* Get space for the result list. */
985 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
988 /* Iterate over the sequences until all have stopped. */
990 PyObject
*alist
, *item
=NULL
, *value
;
993 if (func
== Py_None
&& n
== 1)
995 else if ((alist
= PyTuple_New(n
)) == NULL
)
998 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
999 if (sqp
->saw_StopIteration
) {
1004 item
= PyIter_Next(sqp
->it
);
1008 if (PyErr_Occurred()) {
1014 sqp
->saw_StopIteration
= 1;
1018 PyTuple_SET_ITEM(alist
, j
, item
);
1026 if (numactive
== 0) {
1031 if (func
== Py_None
)
1034 value
= PyEval_CallObject(func
, alist
);
1040 int status
= PyList_Append(result
, value
);
1045 else if (PyList_SetItem(result
, i
, value
) < 0)
1049 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
1060 for (i
= 0; i
< n
; ++i
)
1061 Py_XDECREF(seqs
[i
].it
);
1066 PyDoc_STRVAR(map_doc
,
1067 "map(function, sequence[, sequence, ...]) -> list\n\
1069 Return a list of the results of applying the function to the items of\n\
1070 the argument sequence(s). If more than one sequence is given, the\n\
1071 function is called with an argument list consisting of the corresponding\n\
1072 item of each sequence, substituting None for missing values when not all\n\
1073 sequences have the same length. If the function is None, return a list of\n\
1074 the items of the sequence (or a list of tuples if more than one sequence).");
1078 builtin_next(PyObject
*self
, PyObject
*args
)
1081 PyObject
*def
= NULL
;
1083 if (!PyArg_UnpackTuple(args
, "next", 1, 2, &it
, &def
))
1085 if (!PyIter_Check(it
)) {
1086 PyErr_Format(PyExc_TypeError
,
1087 "%.200s object is not an iterator",
1088 it
->ob_type
->tp_name
);
1092 res
= (*it
->ob_type
->tp_iternext
)(it
);
1095 } else if (def
!= NULL
) {
1096 if (PyErr_Occurred()) {
1097 if (!PyErr_ExceptionMatches(PyExc_StopIteration
))
1103 } else if (PyErr_Occurred()) {
1106 PyErr_SetNone(PyExc_StopIteration
);
1111 PyDoc_STRVAR(next_doc
,
1112 "next(iterator[, default])\n\
1114 Return the next item from the iterator. If default is given and the iterator\n\
1115 is exhausted, it is returned instead of raising StopIteration.");
1119 builtin_setattr(PyObject
*self
, PyObject
*args
)
1125 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
1127 if (PyObject_SetAttr(v
, name
, value
) != 0)
1133 PyDoc_STRVAR(setattr_doc
,
1134 "setattr(object, name, value)\n\
1136 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1141 builtin_delattr(PyObject
*self
, PyObject
*args
)
1146 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
1148 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1154 PyDoc_STRVAR(delattr_doc
,
1155 "delattr(object, name)\n\
1157 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1162 builtin_hash(PyObject
*self
, PyObject
*v
)
1166 x
= PyObject_Hash(v
);
1169 return PyInt_FromLong(x
);
1172 PyDoc_STRVAR(hash_doc
,
1173 "hash(object) -> integer\n\
1175 Return a hash value for the object. Two objects with the same value have\n\
1176 the same hash value. The reverse is not necessarily true, but likely.");
1180 builtin_hex(PyObject
*self
, PyObject
*v
)
1182 PyNumberMethods
*nb
;
1185 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1186 nb
->nb_hex
== NULL
) {
1187 PyErr_SetString(PyExc_TypeError
,
1188 "hex() argument can't be converted to hex");
1191 res
= (*nb
->nb_hex
)(v
);
1192 if (res
&& !PyString_Check(res
)) {
1193 PyErr_Format(PyExc_TypeError
,
1194 "__hex__ returned non-string (type %.200s)",
1195 res
->ob_type
->tp_name
);
1202 PyDoc_STRVAR(hex_doc
,
1203 "hex(number) -> string\n\
1205 Return the hexadecimal representation of an integer or long integer.");
1208 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
1211 builtin_input(PyObject
*self
, PyObject
*args
)
1216 PyObject
*globals
, *locals
;
1219 line
= builtin_raw_input(self
, args
);
1222 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1224 while (*str
== ' ' || *str
== '\t')
1226 globals
= PyEval_GetGlobals();
1227 locals
= PyEval_GetLocals();
1228 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1229 if (PyDict_SetItemString(globals
, "__builtins__",
1230 PyEval_GetBuiltins()) != 0)
1234 PyEval_MergeCompilerFlags(&cf
);
1235 res
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
1240 PyDoc_STRVAR(input_doc
,
1241 "input([prompt]) -> value\n\
1243 Equivalent to eval(raw_input(prompt)).");
1247 builtin_intern(PyObject
*self
, PyObject
*args
)
1250 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1252 if (!PyString_CheckExact(s
)) {
1253 PyErr_SetString(PyExc_TypeError
,
1254 "can't intern subclass of string");
1258 PyString_InternInPlace(&s
);
1262 PyDoc_STRVAR(intern_doc
,
1263 "intern(string) -> string\n\
1265 ``Intern'' the given string. This enters the string in the (global)\n\
1266 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1267 Return the string itself or the previously interned string object with the\n\
1272 builtin_iter(PyObject
*self
, PyObject
*args
)
1274 PyObject
*v
, *w
= NULL
;
1276 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1279 return PyObject_GetIter(v
);
1280 if (!PyCallable_Check(v
)) {
1281 PyErr_SetString(PyExc_TypeError
,
1282 "iter(v, w): v must be callable");
1285 return PyCallIter_New(v
, w
);
1288 PyDoc_STRVAR(iter_doc
,
1289 "iter(collection) -> iterator\n\
1290 iter(callable, sentinel) -> iterator\n\
1292 Get an iterator from an object. In the first form, the argument must\n\
1293 supply its own iterator, or be a sequence.\n\
1294 In the second form, the callable is called until it returns the sentinel.");
1298 builtin_len(PyObject
*self
, PyObject
*v
)
1302 res
= PyObject_Size(v
);
1303 if (res
< 0 && PyErr_Occurred())
1305 return PyInt_FromSsize_t(res
);
1308 PyDoc_STRVAR(len_doc
,
1309 "len(object) -> integer\n\
1311 Return the number of items of a sequence or mapping.");
1315 builtin_locals(PyObject
*self
)
1319 d
= PyEval_GetLocals();
1324 PyDoc_STRVAR(locals_doc
,
1325 "locals() -> dictionary\n\
1327 Update and return a dictionary containing the current scope's local variables.");
1331 min_max(PyObject
*args
, PyObject
*kwds
, int op
)
1333 PyObject
*v
, *it
, *item
, *val
, *maxitem
, *maxval
, *keyfunc
=NULL
;
1334 const char *name
= op
== Py_LT
? "min" : "max";
1336 if (PyTuple_Size(args
) > 1)
1338 else if (!PyArg_UnpackTuple(args
, (char *)name
, 1, 1, &v
))
1341 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
)) {
1342 keyfunc
= PyDict_GetItemString(kwds
, "key");
1343 if (PyDict_Size(kwds
)!=1 || keyfunc
== NULL
) {
1344 PyErr_Format(PyExc_TypeError
,
1345 "%s() got an unexpected keyword argument", name
);
1351 it
= PyObject_GetIter(v
);
1353 Py_XDECREF(keyfunc
);
1357 maxitem
= NULL
; /* the result */
1358 maxval
= NULL
; /* the value associated with the result */
1359 while (( item
= PyIter_Next(it
) )) {
1360 /* get the value from the key function */
1361 if (keyfunc
!= NULL
) {
1362 val
= PyObject_CallFunctionObjArgs(keyfunc
, item
, NULL
);
1366 /* no key function; the value is the item */
1372 /* maximum value and item are unset; set them */
1373 if (maxval
== NULL
) {
1377 /* maximum value and item are set; update them as necessary */
1379 int cmp
= PyObject_RichCompareBool(val
, maxval
, op
);
1381 goto Fail_it_item_and_val
;
1394 if (PyErr_Occurred())
1396 if (maxval
== NULL
) {
1397 PyErr_Format(PyExc_ValueError
,
1398 "%s() arg is an empty sequence", name
);
1399 assert(maxitem
== NULL
);
1404 Py_XDECREF(keyfunc
);
1407 Fail_it_item_and_val
:
1413 Py_XDECREF(maxitem
);
1415 Py_XDECREF(keyfunc
);
1420 builtin_min(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1422 return min_max(args
, kwds
, Py_LT
);
1425 PyDoc_STRVAR(min_doc
,
1426 "min(iterable[, key=func]) -> value\n\
1427 min(a, b, c, ...[, key=func]) -> value\n\
1429 With a single iterable argument, return its smallest item.\n\
1430 With two or more arguments, return the smallest argument.");
1434 builtin_max(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1436 return min_max(args
, kwds
, Py_GT
);
1439 PyDoc_STRVAR(max_doc
,
1440 "max(iterable[, key=func]) -> value\n\
1441 max(a, b, c, ...[, key=func]) -> value\n\
1443 With a single iterable argument, return its largest item.\n\
1444 With two or more arguments, return the largest argument.");
1448 builtin_oct(PyObject
*self
, PyObject
*v
)
1450 PyNumberMethods
*nb
;
1453 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1454 nb
->nb_oct
== NULL
) {
1455 PyErr_SetString(PyExc_TypeError
,
1456 "oct() argument can't be converted to oct");
1459 res
= (*nb
->nb_oct
)(v
);
1460 if (res
&& !PyString_Check(res
)) {
1461 PyErr_Format(PyExc_TypeError
,
1462 "__oct__ returned non-string (type %.200s)",
1463 res
->ob_type
->tp_name
);
1470 PyDoc_STRVAR(oct_doc
,
1471 "oct(number) -> string\n\
1473 Return the octal representation of an integer or long integer.");
1477 builtin_open(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1479 return PyObject_Call((PyObject
*)&PyFile_Type
, args
, kwds
);
1482 PyDoc_STRVAR(open_doc
,
1483 "open(name[, mode[, buffering]]) -> file object\n\
1485 Open a file using the file() type, returns a file object. This is the\n\
1486 preferred way to open a file.");
1490 builtin_ord(PyObject
*self
, PyObject
* obj
)
1495 if (PyString_Check(obj
)) {
1496 size
= PyString_GET_SIZE(obj
);
1498 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1499 return PyInt_FromLong(ord
);
1501 } else if (PyByteArray_Check(obj
)) {
1502 size
= PyByteArray_GET_SIZE(obj
);
1504 ord
= (long)((unsigned char)*PyByteArray_AS_STRING(obj
));
1505 return PyInt_FromLong(ord
);
1508 #ifdef Py_USING_UNICODE
1509 } else if (PyUnicode_Check(obj
)) {
1510 size
= PyUnicode_GET_SIZE(obj
);
1512 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1513 return PyInt_FromLong(ord
);
1517 PyErr_Format(PyExc_TypeError
,
1518 "ord() expected string of length 1, but " \
1519 "%.200s found", obj
->ob_type
->tp_name
);
1523 PyErr_Format(PyExc_TypeError
,
1524 "ord() expected a character, "
1525 "but string of length %zd found",
1530 PyDoc_STRVAR(ord_doc
,
1531 "ord(c) -> integer\n\
1533 Return the integer ordinal of a one-character string.");
1537 builtin_pow(PyObject
*self
, PyObject
*args
)
1539 PyObject
*v
, *w
, *z
= Py_None
;
1541 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1543 return PyNumber_Power(v
, w
, z
);
1546 PyDoc_STRVAR(pow_doc
,
1547 "pow(x, y[, z]) -> number\n\
1549 With two arguments, equivalent to x**y. With three arguments,\n\
1550 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1554 builtin_print(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1556 static char *kwlist
[] = {"sep", "end", "file", 0};
1557 static PyObject
*dummy_args
;
1558 PyObject
*sep
= NULL
, *end
= NULL
, *file
= NULL
;
1561 if (dummy_args
== NULL
) {
1562 if (!(dummy_args
= PyTuple_New(0)))
1565 if (!PyArg_ParseTupleAndKeywords(dummy_args
, kwds
, "|OOO:print",
1566 kwlist
, &sep
, &end
, &file
))
1568 if (file
== NULL
|| file
== Py_None
) {
1569 file
= PySys_GetObject("stdout");
1570 /* sys.stdout may be None when FILE* stdout isn't connected */
1571 if (file
== Py_None
)
1575 if (sep
&& sep
!= Py_None
&& !PyString_Check(sep
) &&
1576 !PyUnicode_Check(sep
)) {
1577 PyErr_Format(PyExc_TypeError
,
1578 "sep must be None, str or unicode, not %.200s",
1579 sep
->ob_type
->tp_name
);
1582 if (end
&& end
!= Py_None
&& !PyString_Check(end
) &&
1583 !PyUnicode_Check(end
)) {
1584 PyErr_Format(PyExc_TypeError
,
1585 "end must be None, str or unicode, not %.200s",
1586 end
->ob_type
->tp_name
);
1590 for (i
= 0; i
< PyTuple_Size(args
); i
++) {
1592 if (sep
== NULL
|| sep
== Py_None
)
1593 err
= PyFile_WriteString(" ", file
);
1595 err
= PyFile_WriteObject(sep
, file
,
1600 err
= PyFile_WriteObject(PyTuple_GetItem(args
, i
), file
,
1606 if (end
== NULL
|| end
== Py_None
)
1607 err
= PyFile_WriteString("\n", file
);
1609 err
= PyFile_WriteObject(end
, file
, Py_PRINT_RAW
);
1616 PyDoc_STRVAR(print_doc
,
1617 "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1619 Prints the values to a stream, or to sys.stdout by default.\n\
1620 Optional keyword arguments:\n\
1621 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1622 sep: string inserted between values, default a space.\n\
1623 end: string appended after the last value, default a newline.");
1626 /* Return number of items in range (lo, hi, step), when arguments are
1627 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1628 * & only if the true value is too large to fit in a signed long.
1629 * Arguments MUST return 1 with either PyInt_Check() or
1630 * PyLong_Check(). Return -1 when there is an error.
1633 get_len_of_range_longs(PyObject
*lo
, PyObject
*hi
, PyObject
*step
)
1635 /* -------------------------------------------------------------
1636 Algorithm is equal to that of get_len_of_range(), but it operates
1637 on PyObjects (which are assumed to be PyLong or PyInt objects).
1638 ---------------------------------------------------------------*/
1640 PyObject
*diff
= NULL
;
1641 PyObject
*one
= NULL
;
1642 PyObject
*tmp1
= NULL
, *tmp2
= NULL
, *tmp3
= NULL
;
1643 /* holds sub-expression evaluations */
1645 /* if (lo >= hi), return length of 0. */
1646 if (PyObject_Compare(lo
, hi
) >= 0)
1649 if ((one
= PyLong_FromLong(1L)) == NULL
)
1652 if ((tmp1
= PyNumber_Subtract(hi
, lo
)) == NULL
)
1655 if ((diff
= PyNumber_Subtract(tmp1
, one
)) == NULL
)
1658 if ((tmp2
= PyNumber_FloorDivide(diff
, step
)) == NULL
)
1661 if ((tmp3
= PyNumber_Add(tmp2
, one
)) == NULL
)
1664 n
= PyLong_AsLong(tmp3
);
1665 if (PyErr_Occurred()) { /* Check for Overflow */
1686 /* An extension of builtin_range() that handles the case when PyLong
1687 * arguments are given. */
1689 handle_range_longs(PyObject
*self
, PyObject
*args
)
1692 PyObject
*ihigh
= NULL
;
1693 PyObject
*istep
= NULL
;
1695 PyObject
*curnum
= NULL
;
1701 PyObject
*zero
= PyLong_FromLong(0);
1706 if (!PyArg_UnpackTuple(args
, "range", 1, 3, &ilow
, &ihigh
, &istep
)) {
1711 /* Figure out which way we were called, supply defaults, and be
1712 * sure to incref everything so that the decrefs at the end
1715 assert(ilow
!= NULL
);
1716 if (ihigh
== NULL
) {
1717 /* only 1 arg -- it's the upper limit */
1721 assert(ihigh
!= NULL
);
1724 /* ihigh correct now; do ilow */
1729 /* ilow and ihigh correct now; do istep */
1730 if (istep
== NULL
) {
1731 istep
= PyLong_FromLong(1L);
1739 if (!PyInt_Check(ilow
) && !PyLong_Check(ilow
)) {
1740 PyErr_Format(PyExc_TypeError
,
1741 "range() integer start argument expected, got %s.",
1742 ilow
->ob_type
->tp_name
);
1746 if (!PyInt_Check(ihigh
) && !PyLong_Check(ihigh
)) {
1747 PyErr_Format(PyExc_TypeError
,
1748 "range() integer end argument expected, got %s.",
1749 ihigh
->ob_type
->tp_name
);
1753 if (!PyInt_Check(istep
) && !PyLong_Check(istep
)) {
1754 PyErr_Format(PyExc_TypeError
,
1755 "range() integer step argument expected, got %s.",
1756 istep
->ob_type
->tp_name
);
1760 if (PyObject_Cmp(istep
, zero
, &cmp_result
) == -1)
1762 if (cmp_result
== 0) {
1763 PyErr_SetString(PyExc_ValueError
,
1764 "range() step argument must not be zero");
1769 bign
= get_len_of_range_longs(ilow
, ihigh
, istep
);
1771 PyObject
*neg_istep
= PyNumber_Negative(istep
);
1772 if (neg_istep
== NULL
)
1774 bign
= get_len_of_range_longs(ihigh
, ilow
, neg_istep
);
1775 Py_DECREF(neg_istep
);
1779 if (bign
< 0 || (long)n
!= bign
) {
1780 PyErr_SetString(PyExc_OverflowError
,
1781 "range() result has too many items");
1792 for (i
= 0; i
< n
; i
++) {
1793 PyObject
*w
= PyNumber_Long(curnum
);
1798 PyList_SET_ITEM(v
, i
, w
);
1800 tmp_num
= PyNumber_Add(curnum
, istep
);
1801 if (tmp_num
== NULL
)
1824 /* Return number of items in range/xrange (lo, hi, step). step > 0
1825 * required. Return a value < 0 if & only if the true value is too
1826 * large to fit in a signed long.
1829 get_len_of_range(long lo
, long hi
, long step
)
1831 /* -------------------------------------------------------------
1832 If lo >= hi, the range is empty.
1833 Else if n values are in the range, the last one is
1834 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1835 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1836 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1837 the RHS is non-negative and so truncation is the same as the
1838 floor. Letting M be the largest positive long, the worst case
1839 for the RHS numerator is hi=M, lo=-M-1, and then
1840 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1841 precision to compute the RHS exactly.
1842 ---------------------------------------------------------------*/
1845 unsigned long uhi
= (unsigned long)hi
;
1846 unsigned long ulo
= (unsigned long)lo
;
1847 unsigned long diff
= uhi
- ulo
- 1;
1848 n
= (long)(diff
/ (unsigned long)step
+ 1);
1854 builtin_range(PyObject
*self
, PyObject
*args
)
1856 long ilow
= 0, ihigh
= 0, istep
= 1;
1862 if (PyTuple_Size(args
) <= 1) {
1863 if (!PyArg_ParseTuple(args
,
1864 "l;range() requires 1-3 int arguments",
1867 return handle_range_longs(self
, args
);
1871 if (!PyArg_ParseTuple(args
,
1872 "ll|l;range() requires 1-3 int arguments",
1873 &ilow
, &ihigh
, &istep
)) {
1875 return handle_range_longs(self
, args
);
1879 PyErr_SetString(PyExc_ValueError
,
1880 "range() step argument must not be zero");
1884 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1886 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1888 if (bign
< 0 || (long)n
!= bign
) {
1889 PyErr_SetString(PyExc_OverflowError
,
1890 "range() result has too many items");
1896 for (i
= 0; i
< n
; i
++) {
1897 PyObject
*w
= PyInt_FromLong(ilow
);
1902 PyList_SET_ITEM(v
, i
, w
);
1908 PyDoc_STRVAR(range_doc
,
1909 "range([start,] stop[, step]) -> list of integers\n\
1911 Return a list containing an arithmetic progression of integers.\n\
1912 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1913 When step is given, it specifies the increment (or decrement).\n\
1914 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1915 These are exactly the valid indices for a list of 4 elements.");
1919 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1922 PyObject
*fin
= PySys_GetObject("stdin");
1923 PyObject
*fout
= PySys_GetObject("stdout");
1925 if (!PyArg_UnpackTuple(args
, "[raw_]input", 0, 1, &v
))
1929 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdin");
1933 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdout");
1936 if (PyFile_SoftSpace(fout
, 0)) {
1937 if (PyFile_WriteString(" ", fout
) != 0)
1940 if (PyFile_AsFile(fin
) && PyFile_AsFile(fout
)
1941 && isatty(fileno(PyFile_AsFile(fin
)))
1942 && isatty(fileno(PyFile_AsFile(fout
)))) {
1948 po
= PyObject_Str(v
);
1951 prompt
= PyString_AsString(po
);
1959 s
= PyOS_Readline(PyFile_AsFile(fin
), PyFile_AsFile(fout
),
1963 if (!PyErr_Occurred())
1964 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1968 PyErr_SetNone(PyExc_EOFError
);
1971 else { /* strip trailing '\n' */
1972 size_t len
= strlen(s
);
1973 if (len
> PY_SSIZE_T_MAX
) {
1974 PyErr_SetString(PyExc_OverflowError
,
1975 "[raw_]input: input too long");
1979 result
= PyString_FromStringAndSize(s
, len
-1);
1986 if (PyFile_WriteObject(v
, fout
, Py_PRINT_RAW
) != 0)
1989 return PyFile_GetLine(fin
, -1);
1992 PyDoc_STRVAR(raw_input_doc
,
1993 "raw_input([prompt]) -> string\n\
1995 Read a string from standard input. The trailing newline is stripped.\n\
1996 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1997 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1998 is printed without a trailing newline before reading.");
2002 builtin_reduce(PyObject
*self
, PyObject
*args
)
2004 PyObject
*seq
, *func
, *result
= NULL
, *it
;
2006 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2007 "use functools.reduce()", 1) < 0)
2010 if (!PyArg_UnpackTuple(args
, "reduce", 2, 3, &func
, &seq
, &result
))
2015 it
= PyObject_GetIter(seq
);
2017 PyErr_SetString(PyExc_TypeError
,
2018 "reduce() arg 2 must support iteration");
2023 if ((args
= PyTuple_New(2)) == NULL
)
2029 if (args
->ob_refcnt
> 1) {
2031 if ((args
= PyTuple_New(2)) == NULL
)
2035 op2
= PyIter_Next(it
);
2037 if (PyErr_Occurred())
2045 PyTuple_SetItem(args
, 0, result
);
2046 PyTuple_SetItem(args
, 1, op2
);
2047 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
2055 PyErr_SetString(PyExc_TypeError
,
2056 "reduce() of empty sequence with no initial value");
2068 PyDoc_STRVAR(reduce_doc
,
2069 "reduce(function, sequence[, initial]) -> value\n\
2071 Apply a function of two arguments cumulatively to the items of a sequence,\n\
2072 from left to right, so as to reduce the sequence to a single value.\n\
2073 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2074 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2075 of the sequence in the calculation, and serves as a default when the\n\
2076 sequence is empty.");
2080 builtin_reload(PyObject
*self
, PyObject
*v
)
2082 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2086 return PyImport_ReloadModule(v
);
2089 PyDoc_STRVAR(reload_doc
,
2090 "reload(module) -> module\n\
2092 Reload the module. The module must have been successfully imported before.");
2096 builtin_repr(PyObject
*self
, PyObject
*v
)
2098 return PyObject_Repr(v
);
2101 PyDoc_STRVAR(repr_doc
,
2102 "repr(object) -> string\n\
2104 Return the canonical string representation of the object.\n\
2105 For most object types, eval(repr(object)) == object.");
2109 builtin_round(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2115 static char *kwlist
[] = {"number", "ndigits", 0};
2117 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "d|i:round",
2118 kwlist
, &number
, &ndigits
))
2129 number
= floor(number
+ 0.5);
2131 number
= ceil(number
- 0.5);
2136 return PyFloat_FromDouble(number
);
2139 PyDoc_STRVAR(round_doc
,
2140 "round(number[, ndigits]) -> floating point number\n\
2142 Round a number to a given precision in decimal digits (default 0 digits).\n\
2143 This always returns a floating point number. Precision may be negative.");
2146 builtin_sorted(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2148 PyObject
*newlist
, *v
, *seq
, *compare
=NULL
, *keyfunc
=NULL
, *newargs
;
2150 static char *kwlist
[] = {"iterable", "cmp", "key", "reverse", 0};
2153 /* args 1-4 should match listsort in Objects/listobject.c */
2154 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|OOi:sorted",
2155 kwlist
, &seq
, &compare
, &keyfunc
, &reverse
))
2158 newlist
= PySequence_List(seq
);
2159 if (newlist
== NULL
)
2162 callable
= PyObject_GetAttrString(newlist
, "sort");
2163 if (callable
== NULL
) {
2168 newargs
= PyTuple_GetSlice(args
, 1, 4);
2169 if (newargs
== NULL
) {
2171 Py_DECREF(callable
);
2175 v
= PyObject_Call(callable
, newargs
, kwds
);
2177 Py_DECREF(callable
);
2186 PyDoc_STRVAR(sorted_doc
,
2187 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2190 builtin_vars(PyObject
*self
, PyObject
*args
)
2195 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
2198 d
= PyEval_GetLocals();
2200 if (!PyErr_Occurred())
2201 PyErr_SetString(PyExc_SystemError
,
2202 "vars(): no locals!?");
2208 d
= PyObject_GetAttrString(v
, "__dict__");
2210 PyErr_SetString(PyExc_TypeError
,
2211 "vars() argument must have __dict__ attribute");
2218 PyDoc_STRVAR(vars_doc
,
2219 "vars([object]) -> dictionary\n\
2221 Without arguments, equivalent to locals().\n\
2222 With an argument, equivalent to object.__dict__.");
2226 builtin_sum(PyObject
*self
, PyObject
*args
)
2229 PyObject
*result
= NULL
;
2230 PyObject
*temp
, *item
, *iter
;
2232 if (!PyArg_UnpackTuple(args
, "sum", 1, 2, &seq
, &result
))
2235 iter
= PyObject_GetIter(seq
);
2239 if (result
== NULL
) {
2240 result
= PyInt_FromLong(0);
2241 if (result
== NULL
) {
2246 /* reject string values for 'start' parameter */
2247 if (PyObject_TypeCheck(result
, &PyBaseString_Type
)) {
2248 PyErr_SetString(PyExc_TypeError
,
2249 "sum() can't sum strings [use ''.join(seq) instead]");
2257 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2258 Assumes all inputs are the same type. If the assumption fails, default
2259 to the more general routine.
2261 if (PyInt_CheckExact(result
)) {
2262 long i_result
= PyInt_AS_LONG(result
);
2265 while(result
== NULL
) {
2266 item
= PyIter_Next(iter
);
2269 if (PyErr_Occurred())
2271 return PyInt_FromLong(i_result
);
2273 if (PyInt_CheckExact(item
)) {
2274 long b
= PyInt_AS_LONG(item
);
2275 long x
= i_result
+ b
;
2276 if ((x
^i_result
) >= 0 || (x
^b
) >= 0) {
2282 /* Either overflowed or is not an int. Restore real objects and process normally */
2283 result
= PyInt_FromLong(i_result
);
2284 temp
= PyNumber_Add(result
, item
);
2288 if (result
== NULL
) {
2295 if (PyFloat_CheckExact(result
)) {
2296 double f_result
= PyFloat_AS_DOUBLE(result
);
2299 while(result
== NULL
) {
2300 item
= PyIter_Next(iter
);
2303 if (PyErr_Occurred())
2305 return PyFloat_FromDouble(f_result
);
2307 if (PyFloat_CheckExact(item
)) {
2308 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
2309 f_result
+= PyFloat_AS_DOUBLE(item
);
2310 PyFPE_END_PROTECT(f_result
)
2314 if (PyInt_CheckExact(item
)) {
2315 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
2316 f_result
+= (double)PyInt_AS_LONG(item
);
2317 PyFPE_END_PROTECT(f_result
)
2321 result
= PyFloat_FromDouble(f_result
);
2322 temp
= PyNumber_Add(result
, item
);
2326 if (result
== NULL
) {
2335 item
= PyIter_Next(iter
);
2337 /* error, or end-of-sequence */
2338 if (PyErr_Occurred()) {
2344 temp
= PyNumber_Add(result
, item
);
2355 PyDoc_STRVAR(sum_doc
,
2356 "sum(sequence[, start]) -> value\n\
2358 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2359 of parameter 'start' (which defaults to 0). When the sequence is\n\
2360 empty, returns start.");
2364 builtin_isinstance(PyObject
*self
, PyObject
*args
)
2370 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
2373 retval
= PyObject_IsInstance(inst
, cls
);
2376 return PyBool_FromLong(retval
);
2379 PyDoc_STRVAR(isinstance_doc
,
2380 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2382 Return whether an object is an instance of a class or of a subclass thereof.\n\
2383 With a type as second argument, return whether that is the object's type.\n\
2384 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2385 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2389 builtin_issubclass(PyObject
*self
, PyObject
*args
)
2395 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
2398 retval
= PyObject_IsSubclass(derived
, cls
);
2401 return PyBool_FromLong(retval
);
2404 PyDoc_STRVAR(issubclass_doc
,
2405 "issubclass(C, B) -> bool\n\
2407 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2408 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2409 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2413 builtin_zip(PyObject
*self
, PyObject
*args
)
2416 const Py_ssize_t itemsize
= PySequence_Length(args
);
2418 PyObject
*itlist
; /* tuple of iterators */
2419 Py_ssize_t len
; /* guess at result length */
2422 return PyList_New(0);
2424 /* args must be a tuple */
2425 assert(PyTuple_Check(args
));
2427 /* Guess at result length: the shortest of the input lengths.
2428 If some argument refuses to say, we refuse to guess too, lest
2429 an argument like xrange(sys.maxint) lead us astray.*/
2430 len
= -1; /* unknown */
2431 for (i
= 0; i
< itemsize
; ++i
) {
2432 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2433 Py_ssize_t thislen
= _PyObject_LengthHint(item
, -1);
2438 else if (len
< 0 || thislen
< len
)
2442 /* allocate result list */
2444 len
= 10; /* arbitrary */
2445 if ((ret
= PyList_New(len
)) == NULL
)
2448 /* obtain iterators */
2449 itlist
= PyTuple_New(itemsize
);
2452 for (i
= 0; i
< itemsize
; ++i
) {
2453 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2454 PyObject
*it
= PyObject_GetIter(item
);
2456 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2457 PyErr_Format(PyExc_TypeError
,
2458 "zip argument #%zd must support iteration",
2460 goto Fail_ret_itlist
;
2462 PyTuple_SET_ITEM(itlist
, i
, it
);
2465 /* build result into ret list */
2466 for (i
= 0; ; ++i
) {
2468 PyObject
*next
= PyTuple_New(itemsize
);
2470 goto Fail_ret_itlist
;
2472 for (j
= 0; j
< itemsize
; j
++) {
2473 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
2474 PyObject
*item
= PyIter_Next(it
);
2476 if (PyErr_Occurred()) {
2484 PyTuple_SET_ITEM(next
, j
, item
);
2488 PyList_SET_ITEM(ret
, i
, next
);
2490 int status
= PyList_Append(ret
, next
);
2494 goto Fail_ret_itlist
;
2499 if (ret
!= NULL
&& i
< len
) {
2500 /* The list is too big. */
2501 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
2514 PyDoc_STRVAR(zip_doc
,
2515 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2517 Return a list of tuples, where each tuple contains the i-th element\n\
2518 from each of the argument sequences. The returned list is truncated\n\
2519 in length to the length of the shortest argument sequence.");
2522 static PyMethodDef builtin_methods
[] = {
2523 {"__import__", (PyCFunction
)builtin___import__
, METH_VARARGS
| METH_KEYWORDS
, import_doc
},
2524 {"abs", builtin_abs
, METH_O
, abs_doc
},
2525 {"all", builtin_all
, METH_O
, all_doc
},
2526 {"any", builtin_any
, METH_O
, any_doc
},
2527 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
2528 {"bin", builtin_bin
, METH_O
, bin_doc
},
2529 {"callable", builtin_callable
, METH_O
, callable_doc
},
2530 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2531 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
2532 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
2533 {"compile", (PyCFunction
)builtin_compile
, METH_VARARGS
| METH_KEYWORDS
, compile_doc
},
2534 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2535 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2536 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2537 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2538 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
2539 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
2540 {"format", builtin_format
, METH_VARARGS
, format_doc
},
2541 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2542 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2543 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2544 {"hash", builtin_hash
, METH_O
, hash_doc
},
2545 {"hex", builtin_hex
, METH_O
, hex_doc
},
2546 {"id", builtin_id
, METH_O
, id_doc
},
2547 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2548 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
2549 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2550 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2551 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2552 {"len", builtin_len
, METH_O
, len_doc
},
2553 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2554 {"map", builtin_map
, METH_VARARGS
, map_doc
},
2555 {"max", (PyCFunction
)builtin_max
, METH_VARARGS
| METH_KEYWORDS
, max_doc
},
2556 {"min", (PyCFunction
)builtin_min
, METH_VARARGS
| METH_KEYWORDS
, min_doc
},
2557 {"next", builtin_next
, METH_VARARGS
, next_doc
},
2558 {"oct", builtin_oct
, METH_O
, oct_doc
},
2559 {"open", (PyCFunction
)builtin_open
, METH_VARARGS
| METH_KEYWORDS
, open_doc
},
2560 {"ord", builtin_ord
, METH_O
, ord_doc
},
2561 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2562 {"print", (PyCFunction
)builtin_print
, METH_VARARGS
| METH_KEYWORDS
, print_doc
},
2563 {"range", builtin_range
, METH_VARARGS
, range_doc
},
2564 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
2565 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
2566 {"reload", builtin_reload
, METH_O
, reload_doc
},
2567 {"repr", builtin_repr
, METH_O
, repr_doc
},
2568 {"round", (PyCFunction
)builtin_round
, METH_VARARGS
| METH_KEYWORDS
, round_doc
},
2569 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2570 {"sorted", (PyCFunction
)builtin_sorted
, METH_VARARGS
| METH_KEYWORDS
, sorted_doc
},
2571 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2572 #ifdef Py_USING_UNICODE
2573 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
2575 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2576 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
2580 PyDoc_STRVAR(builtin_doc
,
2581 "Built-in functions, exceptions, and other objects.\n\
2583 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2586 _PyBuiltin_Init(void)
2588 PyObject
*mod
, *dict
, *debug
;
2589 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2590 builtin_doc
, (PyObject
*)NULL
,
2591 PYTHON_API_VERSION
);
2594 dict
= PyModule_GetDict(mod
);
2596 #ifdef Py_TRACE_REFS
2597 /* __builtin__ exposes a number of statically allocated objects
2598 * that, before this code was added in 2.3, never showed up in
2599 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2600 * result, programs leaking references to None and False (etc)
2601 * couldn't be diagnosed by examining sys.getobjects(0).
2603 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2605 #define ADD_TO_ALL(OBJECT) (void)0
2608 #define SETBUILTIN(NAME, OBJECT) \
2609 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2613 SETBUILTIN("None", Py_None
);
2614 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2615 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2616 SETBUILTIN("False", Py_False
);
2617 SETBUILTIN("True", Py_True
);
2618 SETBUILTIN("basestring", &PyBaseString_Type
);
2619 SETBUILTIN("bool", &PyBool_Type
);
2620 /* SETBUILTIN("memoryview", &PyMemoryView_Type); */
2621 SETBUILTIN("bytearray", &PyByteArray_Type
);
2622 SETBUILTIN("bytes", &PyString_Type
);
2623 SETBUILTIN("buffer", &PyBuffer_Type
);
2624 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2625 #ifndef WITHOUT_COMPLEX
2626 SETBUILTIN("complex", &PyComplex_Type
);
2628 SETBUILTIN("dict", &PyDict_Type
);
2629 SETBUILTIN("enumerate", &PyEnum_Type
);
2630 SETBUILTIN("file", &PyFile_Type
);
2631 SETBUILTIN("float", &PyFloat_Type
);
2632 SETBUILTIN("frozenset", &PyFrozenSet_Type
);
2633 SETBUILTIN("property", &PyProperty_Type
);
2634 SETBUILTIN("int", &PyInt_Type
);
2635 SETBUILTIN("list", &PyList_Type
);
2636 SETBUILTIN("long", &PyLong_Type
);
2637 SETBUILTIN("object", &PyBaseObject_Type
);
2638 SETBUILTIN("reversed", &PyReversed_Type
);
2639 SETBUILTIN("set", &PySet_Type
);
2640 SETBUILTIN("slice", &PySlice_Type
);
2641 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2642 SETBUILTIN("str", &PyString_Type
);
2643 SETBUILTIN("super", &PySuper_Type
);
2644 SETBUILTIN("tuple", &PyTuple_Type
);
2645 SETBUILTIN("type", &PyType_Type
);
2646 SETBUILTIN("xrange", &PyRange_Type
);
2647 #ifdef Py_USING_UNICODE
2648 SETBUILTIN("unicode", &PyUnicode_Type
);
2650 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2651 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2662 /* Helper for filter(): filter a tuple through a function */
2665 filtertuple(PyObject
*func
, PyObject
*tuple
)
2669 Py_ssize_t len
= PyTuple_Size(tuple
);
2672 if (PyTuple_CheckExact(tuple
))
2675 tuple
= PyTuple_New(0);
2679 if ((result
= PyTuple_New(len
)) == NULL
)
2682 for (i
= j
= 0; i
< len
; ++i
) {
2683 PyObject
*item
, *good
;
2686 if (tuple
->ob_type
->tp_as_sequence
&&
2687 tuple
->ob_type
->tp_as_sequence
->sq_item
) {
2688 item
= tuple
->ob_type
->tp_as_sequence
->sq_item(tuple
, i
);
2692 PyErr_SetString(PyExc_TypeError
, "filter(): unsubscriptable tuple");
2695 if (func
== Py_None
) {
2700 PyObject
*arg
= PyTuple_Pack(1, item
);
2705 good
= PyEval_CallObject(func
, arg
);
2712 ok
= PyObject_IsTrue(good
);
2715 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2722 if (_PyTuple_Resize(&result
, j
) < 0)
2733 /* Helper for filter(): filter a string through a function */
2736 filterstring(PyObject
*func
, PyObject
*strobj
)
2740 Py_ssize_t len
= PyString_Size(strobj
);
2741 Py_ssize_t outlen
= len
;
2743 if (func
== Py_None
) {
2744 /* If it's a real string we can return the original,
2745 * as no character is ever false and __getitem__
2746 * does return this character. If it's a subclass
2747 * we must go through the __getitem__ loop */
2748 if (PyString_CheckExact(strobj
)) {
2753 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2756 for (i
= j
= 0; i
< len
; ++i
) {
2760 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2763 if (func
==Py_None
) {
2766 PyObject
*arg
, *good
;
2767 arg
= PyTuple_Pack(1, item
);
2772 good
= PyEval_CallObject(func
, arg
);
2778 ok
= PyObject_IsTrue(good
);
2783 if (!PyString_Check(item
)) {
2784 PyErr_SetString(PyExc_TypeError
, "can't filter str to str:"
2785 " __getitem__ returned different type");
2789 reslen
= PyString_GET_SIZE(item
);
2791 PyString_AS_STRING(result
)[j
++] =
2792 PyString_AS_STRING(item
)[0];
2794 /* do we need more space? */
2795 Py_ssize_t need
= j
;
2797 /* calculate space requirements while checking for overflow */
2798 if (need
> PY_SSIZE_T_MAX
- reslen
) {
2805 if (need
> PY_SSIZE_T_MAX
- len
) {
2817 need
= need
- i
- 1;
2820 assert(outlen
>= 0);
2822 if (need
> outlen
) {
2823 /* overallocate, to avoid reallocations */
2824 if (outlen
> PY_SSIZE_T_MAX
/ 2) {
2829 if (need
<2*outlen
) {
2832 if (_PyString_Resize(&result
, need
)) {
2839 PyString_AS_STRING(result
) + j
,
2840 PyString_AS_STRING(item
),
2850 _PyString_Resize(&result
, j
);
2859 #ifdef Py_USING_UNICODE
2860 /* Helper for filter(): filter a Unicode object through a function */
2863 filterunicode(PyObject
*func
, PyObject
*strobj
)
2866 register Py_ssize_t i
, j
;
2867 Py_ssize_t len
= PyUnicode_GetSize(strobj
);
2868 Py_ssize_t outlen
= len
;
2870 if (func
== Py_None
) {
2871 /* If it's a real string we can return the original,
2872 * as no character is ever false and __getitem__
2873 * does return this character. If it's a subclass
2874 * we must go through the __getitem__ loop */
2875 if (PyUnicode_CheckExact(strobj
)) {
2880 if ((result
= PyUnicode_FromUnicode(NULL
, len
)) == NULL
)
2883 for (i
= j
= 0; i
< len
; ++i
) {
2884 PyObject
*item
, *arg
, *good
;
2887 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2890 if (func
== Py_None
) {
2893 arg
= PyTuple_Pack(1, item
);
2898 good
= PyEval_CallObject(func
, arg
);
2904 ok
= PyObject_IsTrue(good
);
2909 if (!PyUnicode_Check(item
)) {
2910 PyErr_SetString(PyExc_TypeError
,
2911 "can't filter unicode to unicode:"
2912 " __getitem__ returned different type");
2916 reslen
= PyUnicode_GET_SIZE(item
);
2918 PyUnicode_AS_UNICODE(result
)[j
++] =
2919 PyUnicode_AS_UNICODE(item
)[0];
2921 /* do we need more space? */
2922 Py_ssize_t need
= j
+ reslen
+ len
- i
- 1;
2924 /* check that didnt overflow */
2925 if ((j
> PY_SSIZE_T_MAX
- reslen
) ||
2926 ((j
+ reslen
) > PY_SSIZE_T_MAX
- len
) ||
2927 ((j
+ reslen
+ len
) < i
) ||
2928 ((j
+ reslen
+ len
- i
) <= 0)) {
2934 assert(outlen
>= 0);
2936 if (need
> outlen
) {
2938 to avoid reallocations */
2939 if (need
< 2 * outlen
) {
2940 if (outlen
> PY_SSIZE_T_MAX
/ 2) {
2948 if (PyUnicode_Resize(
2949 &result
, need
) < 0) {
2955 memcpy(PyUnicode_AS_UNICODE(result
) + j
,
2956 PyUnicode_AS_UNICODE(item
),
2957 reslen
*sizeof(Py_UNICODE
));
2965 PyUnicode_Resize(&result
, j
);