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);
274 /* Get a result list. */
275 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
276 /* Eww - can modify the list in-place. */
281 result
= PyList_New(len
);
286 /* Build the result list. */
292 item
= PyIter_Next(it
);
294 if (PyErr_Occurred())
299 if (func
== (PyObject
*)&PyBool_Type
|| func
== Py_None
) {
300 ok
= PyObject_IsTrue(item
);
304 PyTuple_SET_ITEM(arg
, 0, item
);
305 good
= PyObject_Call(func
, arg
, NULL
);
306 PyTuple_SET_ITEM(arg
, 0, NULL
);
311 ok
= PyObject_IsTrue(good
);
316 PyList_SET_ITEM(result
, j
, item
);
318 int status
= PyList_Append(result
, item
);
330 /* Cut back result list if len is too big. */
331 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
347 PyDoc_STRVAR(filter_doc
,
348 "filter(function or None, sequence) -> list, tuple, or string\n"
350 "Return those items of sequence for which function(item) is true. If\n"
351 "function is None, return the items that are true. If sequence is a tuple\n"
352 "or string, return the same type, else return a list.");
355 builtin_format(PyObject
*self
, PyObject
*args
)
358 PyObject
*format_spec
= NULL
;
360 if (!PyArg_ParseTuple(args
, "O|O:format", &value
, &format_spec
))
363 return PyObject_Format(value
, format_spec
);
366 PyDoc_STRVAR(format_doc
,
367 "format(value[, format_spec]) -> string\n\
369 Returns value.__format__(format_spec)\n\
370 format_spec defaults to \"\"");
373 builtin_chr(PyObject
*self
, PyObject
*args
)
378 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
380 if (x
< 0 || x
>= 256) {
381 PyErr_SetString(PyExc_ValueError
,
382 "chr() arg not in range(256)");
386 return PyString_FromStringAndSize(s
, 1);
389 PyDoc_STRVAR(chr_doc
,
390 "chr(i) -> character\n\
392 Return a string of one character with ordinal i; 0 <= i < 256.");
395 #ifdef Py_USING_UNICODE
397 builtin_unichr(PyObject
*self
, PyObject
*args
)
401 if (!PyArg_ParseTuple(args
, "i:unichr", &x
))
404 return PyUnicode_FromOrdinal(x
);
407 PyDoc_STRVAR(unichr_doc
,
408 "unichr(i) -> Unicode character\n\
410 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
415 builtin_cmp(PyObject
*self
, PyObject
*args
)
420 if (!PyArg_UnpackTuple(args
, "cmp", 2, 2, &a
, &b
))
422 if (PyObject_Cmp(a
, b
, &c
) < 0)
424 return PyInt_FromLong((long)c
);
427 PyDoc_STRVAR(cmp_doc
,
428 "cmp(x, y) -> integer\n\
430 Return negative if x<y, zero if x==y, positive if x>y.");
434 builtin_coerce(PyObject
*self
, PyObject
*args
)
439 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
442 if (!PyArg_UnpackTuple(args
, "coerce", 2, 2, &v
, &w
))
444 if (PyNumber_Coerce(&v
, &w
) < 0)
446 res
= PyTuple_Pack(2, v
, w
);
452 PyDoc_STRVAR(coerce_doc
,
453 "coerce(x, y) -> (x1, y1)\n\
455 Return a tuple consisting of the two numeric arguments converted to\n\
456 a common type, using the same rules as used by arithmetic operations.\n\
457 If coercion is not possible, raise TypeError.");
460 builtin_compile(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
466 int dont_inherit
= 0;
467 int supplied_flags
= 0;
469 PyObject
*result
= NULL
, *cmd
, *tmp
= NULL
;
471 static char *kwlist
[] = {"source", "filename", "mode", "flags",
472 "dont_inherit", NULL
};
473 int start
[] = {Py_file_input
, Py_eval_input
, Py_single_input
};
475 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "Oss|ii:compile",
476 kwlist
, &cmd
, &filename
, &startstr
,
477 &supplied_flags
, &dont_inherit
))
480 cf
.cf_flags
= supplied_flags
;
483 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
| PyCF_ONLY_AST
))
485 PyErr_SetString(PyExc_ValueError
,
486 "compile(): unrecognised flags");
489 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
492 PyEval_MergeCompilerFlags(&cf
);
495 if (strcmp(startstr
, "exec") == 0)
497 else if (strcmp(startstr
, "eval") == 0)
499 else if (strcmp(startstr
, "single") == 0)
502 PyErr_SetString(PyExc_ValueError
,
503 "compile() arg 3 must be 'exec', 'eval' or 'single'");
507 if (PyAST_Check(cmd
)) {
508 if (supplied_flags
& PyCF_ONLY_AST
) {
516 arena
= PyArena_New();
517 mod
= PyAST_obj2mod(cmd
, arena
, mode
);
522 result
= (PyObject
*)PyAST_Compile(mod
, filename
,
529 #ifdef Py_USING_UNICODE
530 if (PyUnicode_Check(cmd
)) {
531 tmp
= PyUnicode_AsUTF8String(cmd
);
535 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
539 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &length
))
541 if ((size_t)length
!= strlen(str
)) {
542 PyErr_SetString(PyExc_TypeError
,
543 "compile() expected string without null bytes");
546 result
= Py_CompileStringFlags(str
, filename
, start
[mode
], &cf
);
552 PyDoc_STRVAR(compile_doc
,
553 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
555 Compile the source string (a Python module, statement or expression)\n\
556 into a code object that can be executed by the exec statement or eval().\n\
557 The filename will be used for run-time error messages.\n\
558 The mode must be 'exec' to compile a module, 'single' to compile a\n\
559 single (interactive) statement, or 'eval' to compile an expression.\n\
560 The flags argument, if present, controls which future statements influence\n\
561 the compilation of the code.\n\
562 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
563 the effects of any future statements in effect in the code calling\n\
564 compile; if absent or zero these statements do influence the compilation,\n\
565 in addition to any features explicitly specified.");
568 builtin_dir(PyObject
*self
, PyObject
*args
)
570 PyObject
*arg
= NULL
;
572 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
574 return PyObject_Dir(arg
);
577 PyDoc_STRVAR(dir_doc
,
578 "dir([object]) -> list of strings\n"
580 "If called without an argument, return the names in the current scope.\n"
581 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
582 "of the given object, and of attributes reachable from it.\n"
583 "If the object supplies a method named __dir__, it will be used; otherwise\n"
584 "the default dir() logic is used and returns:\n"
585 " for a module object: the module's attributes.\n"
586 " for a class object: its attributes, and recursively the attributes\n"
588 " for any other object: its attributes, its class's attributes, and\n"
589 " recursively the attributes of its class's base classes.");
592 builtin_divmod(PyObject
*self
, PyObject
*args
)
596 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
598 return PyNumber_Divmod(v
, w
);
601 PyDoc_STRVAR(divmod_doc
,
602 "divmod(x, y) -> (div, mod)\n\
604 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
608 builtin_eval(PyObject
*self
, PyObject
*args
)
610 PyObject
*cmd
, *result
, *tmp
= NULL
;
611 PyObject
*globals
= Py_None
, *locals
= Py_None
;
615 if (!PyArg_UnpackTuple(args
, "eval", 1, 3, &cmd
, &globals
, &locals
))
617 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
618 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
621 if (globals
!= Py_None
&& !PyDict_Check(globals
)) {
622 PyErr_SetString(PyExc_TypeError
, PyMapping_Check(globals
) ?
623 "globals must be a real dict; try eval(expr, {}, mapping)"
624 : "globals must be a dict");
627 if (globals
== Py_None
) {
628 globals
= PyEval_GetGlobals();
629 if (locals
== Py_None
)
630 locals
= PyEval_GetLocals();
632 else if (locals
== Py_None
)
635 if (globals
== NULL
|| locals
== NULL
) {
636 PyErr_SetString(PyExc_TypeError
,
637 "eval must be given globals and locals "
638 "when called without a frame");
642 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
643 if (PyDict_SetItemString(globals
, "__builtins__",
644 PyEval_GetBuiltins()) != 0)
648 if (PyCode_Check(cmd
)) {
649 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
650 PyErr_SetString(PyExc_TypeError
,
651 "code object passed to eval() may not contain free variables");
654 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
657 if (!PyString_Check(cmd
) &&
658 !PyUnicode_Check(cmd
)) {
659 PyErr_SetString(PyExc_TypeError
,
660 "eval() arg 1 must be a string or code object");
665 #ifdef Py_USING_UNICODE
666 if (PyUnicode_Check(cmd
)) {
667 tmp
= PyUnicode_AsUTF8String(cmd
);
671 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
674 if (PyString_AsStringAndSize(cmd
, &str
, NULL
)) {
678 while (*str
== ' ' || *str
== '\t')
681 (void)PyEval_MergeCompilerFlags(&cf
);
682 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
687 PyDoc_STRVAR(eval_doc
,
688 "eval(source[, globals[, locals]]) -> value\n\
690 Evaluate the source in the context of globals and locals.\n\
691 The source may be a string representing a Python expression\n\
692 or a code object as returned by compile().\n\
693 The globals must be a dictionary and locals can be any mapping,\n\
694 defaulting to the current globals and locals.\n\
695 If only globals is given, locals defaults to it.\n");
699 builtin_execfile(PyObject
*self
, PyObject
*args
)
702 PyObject
*globals
= Py_None
, *locals
= Py_None
;
708 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
712 if (!PyArg_ParseTuple(args
, "s|O!O:execfile",
714 &PyDict_Type
, &globals
,
717 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
718 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
721 if (globals
== Py_None
) {
722 globals
= PyEval_GetGlobals();
723 if (locals
== Py_None
)
724 locals
= PyEval_GetLocals();
726 else if (locals
== Py_None
)
728 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
729 if (PyDict_SetItemString(globals
, "__builtins__",
730 PyEval_GetBuiltins()) != 0)
735 /* Test for existence or directory. */
740 if ((d
= dirstat(filename
))!=nil
) {
742 werrstr("is a directory");
748 #elif defined(RISCOS)
749 if (object_exists(filename
)) {
755 #else /* standard Posix */
758 if (stat(filename
, &s
) == 0) {
759 if (S_ISDIR(s
.st_mode
))
760 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
772 Py_BEGIN_ALLOW_THREADS
773 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
782 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
786 if (PyEval_MergeCompilerFlags(&cf
))
787 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
790 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
795 PyDoc_STRVAR(execfile_doc
,
796 "execfile(filename[, globals[, locals]])\n\
798 Read and execute a Python script from a file.\n\
799 The globals and locals are dictionaries, defaulting to the current\n\
800 globals and locals. If only globals is given, locals defaults to it.");
804 builtin_getattr(PyObject
*self
, PyObject
*args
)
806 PyObject
*v
, *result
, *dflt
= NULL
;
809 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
811 #ifdef Py_USING_UNICODE
812 if (PyUnicode_Check(name
)) {
813 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
819 if (!PyString_Check(name
)) {
820 PyErr_SetString(PyExc_TypeError
,
821 "getattr(): attribute name must be string");
824 result
= PyObject_GetAttr(v
, name
);
825 if (result
== NULL
&& dflt
!= NULL
&&
826 PyErr_ExceptionMatches(PyExc_AttributeError
))
835 PyDoc_STRVAR(getattr_doc
,
836 "getattr(object, name[, default]) -> value\n\
838 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
839 When a default argument is given, it is returned when the attribute doesn't\n\
840 exist; without it, an exception is raised in that case.");
844 builtin_globals(PyObject
*self
)
848 d
= PyEval_GetGlobals();
853 PyDoc_STRVAR(globals_doc
,
854 "globals() -> dictionary\n\
856 Return the dictionary containing the current scope's global variables.");
860 builtin_hasattr(PyObject
*self
, PyObject
*args
)
865 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
867 #ifdef Py_USING_UNICODE
868 if (PyUnicode_Check(name
)) {
869 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
875 if (!PyString_Check(name
)) {
876 PyErr_SetString(PyExc_TypeError
,
877 "hasattr(): attribute name must be string");
880 v
= PyObject_GetAttr(v
, name
);
882 if (!PyErr_ExceptionMatches(PyExc_Exception
))
895 PyDoc_STRVAR(hasattr_doc
,
896 "hasattr(object, name) -> bool\n\
898 Return whether the object has an attribute with the given name.\n\
899 (This is done by calling getattr(object, name) and catching exceptions.)");
903 builtin_id(PyObject
*self
, PyObject
*v
)
905 return PyLong_FromVoidPtr(v
);
909 "id(object) -> integer\n\
911 Return the identity of an object. This is guaranteed to be unique among\n\
912 simultaneously existing objects. (Hint: it's the object's memory address.)");
916 builtin_map(PyObject
*self
, PyObject
*args
)
919 PyObject
*it
; /* the iterator object */
920 int saw_StopIteration
; /* bool: did the iterator end? */
923 PyObject
*func
, *result
;
924 sequence
*seqs
= NULL
, *sqp
;
928 n
= PyTuple_Size(args
);
930 PyErr_SetString(PyExc_TypeError
,
931 "map() requires at least two args");
935 func
= PyTuple_GetItem(args
, 0);
938 if (func
== Py_None
) {
939 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
940 "use list(...)", 1) < 0)
943 /* map(None, S) is the same as list(S). */
944 return PySequence_List(PyTuple_GetItem(args
, 1));
948 /* Get space for sequence descriptors. Must NULL out the iterator
949 * pointers so that jumping to Fail_2 later doesn't see trash.
951 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
955 for (i
= 0; i
< n
; ++i
) {
956 seqs
[i
].it
= (PyObject
*)NULL
;
957 seqs
[i
].saw_StopIteration
= 0;
960 /* Do a first pass to obtain iterators for the arguments, and set len
961 * to the largest of their lengths.
964 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
969 curseq
= PyTuple_GetItem(args
, i
+1);
970 sqp
->it
= PyObject_GetIter(curseq
);
971 if (sqp
->it
== NULL
) {
972 static char errmsg
[] =
973 "argument %d to map() must support iteration";
974 char errbuf
[sizeof(errmsg
) + 25];
975 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
976 PyErr_SetString(PyExc_TypeError
, errbuf
);
981 curlen
= _PyObject_LengthHint(curseq
, 8);
986 /* Get space for the result list. */
987 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
990 /* Iterate over the sequences until all have stopped. */
992 PyObject
*alist
, *item
=NULL
, *value
;
995 if (func
== Py_None
&& n
== 1)
997 else if ((alist
= PyTuple_New(n
)) == NULL
)
1000 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
1001 if (sqp
->saw_StopIteration
) {
1006 item
= PyIter_Next(sqp
->it
);
1010 if (PyErr_Occurred()) {
1016 sqp
->saw_StopIteration
= 1;
1020 PyTuple_SET_ITEM(alist
, j
, item
);
1028 if (numactive
== 0) {
1033 if (func
== Py_None
)
1036 value
= PyEval_CallObject(func
, alist
);
1042 int status
= PyList_Append(result
, value
);
1047 else if (PyList_SetItem(result
, i
, value
) < 0)
1051 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
1062 for (i
= 0; i
< n
; ++i
)
1063 Py_XDECREF(seqs
[i
].it
);
1068 PyDoc_STRVAR(map_doc
,
1069 "map(function, sequence[, sequence, ...]) -> list\n\
1071 Return a list of the results of applying the function to the items of\n\
1072 the argument sequence(s). If more than one sequence is given, the\n\
1073 function is called with an argument list consisting of the corresponding\n\
1074 item of each sequence, substituting None for missing values when not all\n\
1075 sequences have the same length. If the function is None, return a list of\n\
1076 the items of the sequence (or a list of tuples if more than one sequence).");
1080 builtin_next(PyObject
*self
, PyObject
*args
)
1083 PyObject
*def
= NULL
;
1085 if (!PyArg_UnpackTuple(args
, "next", 1, 2, &it
, &def
))
1087 if (!PyIter_Check(it
)) {
1088 PyErr_Format(PyExc_TypeError
,
1089 "%.200s object is not an iterator",
1090 it
->ob_type
->tp_name
);
1094 res
= (*it
->ob_type
->tp_iternext
)(it
);
1097 } else if (def
!= NULL
) {
1098 if (PyErr_Occurred()) {
1099 if (!PyErr_ExceptionMatches(PyExc_StopIteration
))
1105 } else if (PyErr_Occurred()) {
1108 PyErr_SetNone(PyExc_StopIteration
);
1113 PyDoc_STRVAR(next_doc
,
1114 "next(iterator[, default])\n\
1116 Return the next item from the iterator. If default is given and the iterator\n\
1117 is exhausted, it is returned instead of raising StopIteration.");
1121 builtin_setattr(PyObject
*self
, PyObject
*args
)
1127 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
1129 if (PyObject_SetAttr(v
, name
, value
) != 0)
1135 PyDoc_STRVAR(setattr_doc
,
1136 "setattr(object, name, value)\n\
1138 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1143 builtin_delattr(PyObject
*self
, PyObject
*args
)
1148 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
1150 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1156 PyDoc_STRVAR(delattr_doc
,
1157 "delattr(object, name)\n\
1159 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1164 builtin_hash(PyObject
*self
, PyObject
*v
)
1168 x
= PyObject_Hash(v
);
1171 return PyInt_FromLong(x
);
1174 PyDoc_STRVAR(hash_doc
,
1175 "hash(object) -> integer\n\
1177 Return a hash value for the object. Two objects with the same value have\n\
1178 the same hash value. The reverse is not necessarily true, but likely.");
1182 builtin_hex(PyObject
*self
, PyObject
*v
)
1184 PyNumberMethods
*nb
;
1187 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1188 nb
->nb_hex
== NULL
) {
1189 PyErr_SetString(PyExc_TypeError
,
1190 "hex() argument can't be converted to hex");
1193 res
= (*nb
->nb_hex
)(v
);
1194 if (res
&& !PyString_Check(res
)) {
1195 PyErr_Format(PyExc_TypeError
,
1196 "__hex__ returned non-string (type %.200s)",
1197 res
->ob_type
->tp_name
);
1204 PyDoc_STRVAR(hex_doc
,
1205 "hex(number) -> string\n\
1207 Return the hexadecimal representation of an integer or long integer.");
1210 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
1213 builtin_input(PyObject
*self
, PyObject
*args
)
1218 PyObject
*globals
, *locals
;
1221 line
= builtin_raw_input(self
, args
);
1224 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1226 while (*str
== ' ' || *str
== '\t')
1228 globals
= PyEval_GetGlobals();
1229 locals
= PyEval_GetLocals();
1230 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1231 if (PyDict_SetItemString(globals
, "__builtins__",
1232 PyEval_GetBuiltins()) != 0)
1236 PyEval_MergeCompilerFlags(&cf
);
1237 res
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
1242 PyDoc_STRVAR(input_doc
,
1243 "input([prompt]) -> value\n\
1245 Equivalent to eval(raw_input(prompt)).");
1249 builtin_intern(PyObject
*self
, PyObject
*args
)
1252 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1254 if (!PyString_CheckExact(s
)) {
1255 PyErr_SetString(PyExc_TypeError
,
1256 "can't intern subclass of string");
1260 PyString_InternInPlace(&s
);
1264 PyDoc_STRVAR(intern_doc
,
1265 "intern(string) -> string\n\
1267 ``Intern'' the given string. This enters the string in the (global)\n\
1268 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1269 Return the string itself or the previously interned string object with the\n\
1274 builtin_iter(PyObject
*self
, PyObject
*args
)
1276 PyObject
*v
, *w
= NULL
;
1278 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1281 return PyObject_GetIter(v
);
1282 if (!PyCallable_Check(v
)) {
1283 PyErr_SetString(PyExc_TypeError
,
1284 "iter(v, w): v must be callable");
1287 return PyCallIter_New(v
, w
);
1290 PyDoc_STRVAR(iter_doc
,
1291 "iter(collection) -> iterator\n\
1292 iter(callable, sentinel) -> iterator\n\
1294 Get an iterator from an object. In the first form, the argument must\n\
1295 supply its own iterator, or be a sequence.\n\
1296 In the second form, the callable is called until it returns the sentinel.");
1300 builtin_len(PyObject
*self
, PyObject
*v
)
1304 res
= PyObject_Size(v
);
1305 if (res
< 0 && PyErr_Occurred())
1307 return PyInt_FromSsize_t(res
);
1310 PyDoc_STRVAR(len_doc
,
1311 "len(object) -> integer\n\
1313 Return the number of items of a sequence or mapping.");
1317 builtin_locals(PyObject
*self
)
1321 d
= PyEval_GetLocals();
1326 PyDoc_STRVAR(locals_doc
,
1327 "locals() -> dictionary\n\
1329 Update and return a dictionary containing the current scope's local variables.");
1333 min_max(PyObject
*args
, PyObject
*kwds
, int op
)
1335 PyObject
*v
, *it
, *item
, *val
, *maxitem
, *maxval
, *keyfunc
=NULL
;
1336 const char *name
= op
== Py_LT
? "min" : "max";
1338 if (PyTuple_Size(args
) > 1)
1340 else if (!PyArg_UnpackTuple(args
, (char *)name
, 1, 1, &v
))
1343 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
)) {
1344 keyfunc
= PyDict_GetItemString(kwds
, "key");
1345 if (PyDict_Size(kwds
)!=1 || keyfunc
== NULL
) {
1346 PyErr_Format(PyExc_TypeError
,
1347 "%s() got an unexpected keyword argument", name
);
1353 it
= PyObject_GetIter(v
);
1355 Py_XDECREF(keyfunc
);
1359 maxitem
= NULL
; /* the result */
1360 maxval
= NULL
; /* the value associated with the result */
1361 while (( item
= PyIter_Next(it
) )) {
1362 /* get the value from the key function */
1363 if (keyfunc
!= NULL
) {
1364 val
= PyObject_CallFunctionObjArgs(keyfunc
, item
, NULL
);
1368 /* no key function; the value is the item */
1374 /* maximum value and item are unset; set them */
1375 if (maxval
== NULL
) {
1379 /* maximum value and item are set; update them as necessary */
1381 int cmp
= PyObject_RichCompareBool(val
, maxval
, op
);
1383 goto Fail_it_item_and_val
;
1396 if (PyErr_Occurred())
1398 if (maxval
== NULL
) {
1399 PyErr_Format(PyExc_ValueError
,
1400 "%s() arg is an empty sequence", name
);
1401 assert(maxitem
== NULL
);
1406 Py_XDECREF(keyfunc
);
1409 Fail_it_item_and_val
:
1415 Py_XDECREF(maxitem
);
1417 Py_XDECREF(keyfunc
);
1422 builtin_min(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1424 return min_max(args
, kwds
, Py_LT
);
1427 PyDoc_STRVAR(min_doc
,
1428 "min(iterable[, key=func]) -> value\n\
1429 min(a, b, c, ...[, key=func]) -> value\n\
1431 With a single iterable argument, return its smallest item.\n\
1432 With two or more arguments, return the smallest argument.");
1436 builtin_max(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1438 return min_max(args
, kwds
, Py_GT
);
1441 PyDoc_STRVAR(max_doc
,
1442 "max(iterable[, key=func]) -> value\n\
1443 max(a, b, c, ...[, key=func]) -> value\n\
1445 With a single iterable argument, return its largest item.\n\
1446 With two or more arguments, return the largest argument.");
1450 builtin_oct(PyObject
*self
, PyObject
*v
)
1452 PyNumberMethods
*nb
;
1455 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1456 nb
->nb_oct
== NULL
) {
1457 PyErr_SetString(PyExc_TypeError
,
1458 "oct() argument can't be converted to oct");
1461 res
= (*nb
->nb_oct
)(v
);
1462 if (res
&& !PyString_Check(res
)) {
1463 PyErr_Format(PyExc_TypeError
,
1464 "__oct__ returned non-string (type %.200s)",
1465 res
->ob_type
->tp_name
);
1472 PyDoc_STRVAR(oct_doc
,
1473 "oct(number) -> string\n\
1475 Return the octal representation of an integer or long integer.");
1479 builtin_open(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1481 return PyObject_Call((PyObject
*)&PyFile_Type
, args
, kwds
);
1484 PyDoc_STRVAR(open_doc
,
1485 "open(name[, mode[, buffering]]) -> file object\n\
1487 Open a file using the file() type, returns a file object. This is the\n\
1488 preferred way to open a file. See file.__doc__ for further information.");
1492 builtin_ord(PyObject
*self
, PyObject
* obj
)
1497 if (PyString_Check(obj
)) {
1498 size
= PyString_GET_SIZE(obj
);
1500 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1501 return PyInt_FromLong(ord
);
1503 } else if (PyByteArray_Check(obj
)) {
1504 size
= PyByteArray_GET_SIZE(obj
);
1506 ord
= (long)((unsigned char)*PyByteArray_AS_STRING(obj
));
1507 return PyInt_FromLong(ord
);
1510 #ifdef Py_USING_UNICODE
1511 } else if (PyUnicode_Check(obj
)) {
1512 size
= PyUnicode_GET_SIZE(obj
);
1514 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1515 return PyInt_FromLong(ord
);
1519 PyErr_Format(PyExc_TypeError
,
1520 "ord() expected string of length 1, but " \
1521 "%.200s found", obj
->ob_type
->tp_name
);
1525 PyErr_Format(PyExc_TypeError
,
1526 "ord() expected a character, "
1527 "but string of length %zd found",
1532 PyDoc_STRVAR(ord_doc
,
1533 "ord(c) -> integer\n\
1535 Return the integer ordinal of a one-character string.");
1539 builtin_pow(PyObject
*self
, PyObject
*args
)
1541 PyObject
*v
, *w
, *z
= Py_None
;
1543 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1545 return PyNumber_Power(v
, w
, z
);
1548 PyDoc_STRVAR(pow_doc
,
1549 "pow(x, y[, z]) -> number\n\
1551 With two arguments, equivalent to x**y. With three arguments,\n\
1552 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1556 builtin_print(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1558 static char *kwlist
[] = {"sep", "end", "file", 0};
1559 static PyObject
*dummy_args
= NULL
;
1560 static PyObject
*unicode_newline
= NULL
, *unicode_space
= NULL
;
1561 static PyObject
*str_newline
= NULL
, *str_space
= NULL
;
1562 PyObject
*newline
, *space
;
1563 PyObject
*sep
= NULL
, *end
= NULL
, *file
= NULL
;
1564 int i
, err
, use_unicode
= 0;
1566 if (dummy_args
== NULL
) {
1567 if (!(dummy_args
= PyTuple_New(0)))
1570 if (str_newline
== NULL
) {
1571 str_newline
= PyString_FromString("\n");
1572 if (str_newline
== NULL
)
1574 str_space
= PyString_FromString(" ");
1575 if (str_space
== NULL
) {
1576 Py_CLEAR(str_newline
);
1579 unicode_newline
= PyUnicode_FromString("\n");
1580 if (unicode_newline
== NULL
) {
1581 Py_CLEAR(str_newline
);
1582 Py_CLEAR(str_space
);
1585 unicode_space
= PyUnicode_FromString(" ");
1586 if (unicode_space
== NULL
) {
1587 Py_CLEAR(str_newline
);
1588 Py_CLEAR(str_space
);
1589 Py_CLEAR(unicode_space
);
1593 if (!PyArg_ParseTupleAndKeywords(dummy_args
, kwds
, "|OOO:print",
1594 kwlist
, &sep
, &end
, &file
))
1596 if (file
== NULL
|| file
== Py_None
) {
1597 file
= PySys_GetObject("stdout");
1598 /* sys.stdout may be None when FILE* stdout isn't connected */
1599 if (file
== Py_None
)
1602 if (sep
== Py_None
) {
1606 if (PyUnicode_Check(sep
)) {
1609 else if (!PyString_Check(sep
)) {
1610 PyErr_Format(PyExc_TypeError
,
1611 "sep must be None, str or unicode, not %.200s",
1612 sep
->ob_type
->tp_name
);
1619 if (PyUnicode_Check(end
)) {
1622 else if (!PyString_Check(end
)) {
1623 PyErr_Format(PyExc_TypeError
,
1624 "end must be None, str or unicode, not %.200s",
1625 end
->ob_type
->tp_name
);
1631 for (i
= 0; i
< PyTuple_Size(args
); i
++) {
1632 if (PyUnicode_Check(PyTuple_GET_ITEM(args
, i
))) {
1639 newline
= unicode_newline
;
1640 space
= unicode_space
;
1643 newline
= str_newline
;
1647 for (i
= 0; i
< PyTuple_Size(args
); i
++) {
1650 err
= PyFile_WriteObject(space
, file
,
1653 err
= PyFile_WriteObject(sep
, file
,
1658 err
= PyFile_WriteObject(PyTuple_GetItem(args
, i
), file
,
1665 err
= PyFile_WriteObject(newline
, file
, Py_PRINT_RAW
);
1667 err
= PyFile_WriteObject(end
, file
, Py_PRINT_RAW
);
1674 PyDoc_STRVAR(print_doc
,
1675 "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1677 Prints the values to a stream, or to sys.stdout by default.\n\
1678 Optional keyword arguments:\n\
1679 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1680 sep: string inserted between values, default a space.\n\
1681 end: string appended after the last value, default a newline.");
1684 /* Return number of items in range (lo, hi, step), when arguments are
1685 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1686 * & only if the true value is too large to fit in a signed long.
1687 * Arguments MUST return 1 with either PyInt_Check() or
1688 * PyLong_Check(). Return -1 when there is an error.
1691 get_len_of_range_longs(PyObject
*lo
, PyObject
*hi
, PyObject
*step
)
1693 /* -------------------------------------------------------------
1694 Algorithm is equal to that of get_len_of_range(), but it operates
1695 on PyObjects (which are assumed to be PyLong or PyInt objects).
1696 ---------------------------------------------------------------*/
1698 PyObject
*diff
= NULL
;
1699 PyObject
*one
= NULL
;
1700 PyObject
*tmp1
= NULL
, *tmp2
= NULL
, *tmp3
= NULL
;
1701 /* holds sub-expression evaluations */
1703 /* if (lo >= hi), return length of 0. */
1704 if (PyObject_Compare(lo
, hi
) >= 0)
1707 if ((one
= PyLong_FromLong(1L)) == NULL
)
1710 if ((tmp1
= PyNumber_Subtract(hi
, lo
)) == NULL
)
1713 if ((diff
= PyNumber_Subtract(tmp1
, one
)) == NULL
)
1716 if ((tmp2
= PyNumber_FloorDivide(diff
, step
)) == NULL
)
1719 if ((tmp3
= PyNumber_Add(tmp2
, one
)) == NULL
)
1722 n
= PyLong_AsLong(tmp3
);
1723 if (PyErr_Occurred()) { /* Check for Overflow */
1744 /* An extension of builtin_range() that handles the case when PyLong
1745 * arguments are given. */
1747 handle_range_longs(PyObject
*self
, PyObject
*args
)
1750 PyObject
*ihigh
= NULL
;
1751 PyObject
*istep
= NULL
;
1753 PyObject
*curnum
= NULL
;
1759 PyObject
*zero
= PyLong_FromLong(0);
1764 if (!PyArg_UnpackTuple(args
, "range", 1, 3, &ilow
, &ihigh
, &istep
)) {
1769 /* Figure out which way we were called, supply defaults, and be
1770 * sure to incref everything so that the decrefs at the end
1773 assert(ilow
!= NULL
);
1774 if (ihigh
== NULL
) {
1775 /* only 1 arg -- it's the upper limit */
1779 assert(ihigh
!= NULL
);
1782 /* ihigh correct now; do ilow */
1787 /* ilow and ihigh correct now; do istep */
1788 if (istep
== NULL
) {
1789 istep
= PyLong_FromLong(1L);
1797 if (!PyInt_Check(ilow
) && !PyLong_Check(ilow
)) {
1798 PyErr_Format(PyExc_TypeError
,
1799 "range() integer start argument expected, got %s.",
1800 ilow
->ob_type
->tp_name
);
1804 if (!PyInt_Check(ihigh
) && !PyLong_Check(ihigh
)) {
1805 PyErr_Format(PyExc_TypeError
,
1806 "range() integer end argument expected, got %s.",
1807 ihigh
->ob_type
->tp_name
);
1811 if (!PyInt_Check(istep
) && !PyLong_Check(istep
)) {
1812 PyErr_Format(PyExc_TypeError
,
1813 "range() integer step argument expected, got %s.",
1814 istep
->ob_type
->tp_name
);
1818 if (PyObject_Cmp(istep
, zero
, &cmp_result
) == -1)
1820 if (cmp_result
== 0) {
1821 PyErr_SetString(PyExc_ValueError
,
1822 "range() step argument must not be zero");
1827 bign
= get_len_of_range_longs(ilow
, ihigh
, istep
);
1829 PyObject
*neg_istep
= PyNumber_Negative(istep
);
1830 if (neg_istep
== NULL
)
1832 bign
= get_len_of_range_longs(ihigh
, ilow
, neg_istep
);
1833 Py_DECREF(neg_istep
);
1837 if (bign
< 0 || (long)n
!= bign
) {
1838 PyErr_SetString(PyExc_OverflowError
,
1839 "range() result has too many items");
1850 for (i
= 0; i
< n
; i
++) {
1851 PyObject
*w
= PyNumber_Long(curnum
);
1856 PyList_SET_ITEM(v
, i
, w
);
1858 tmp_num
= PyNumber_Add(curnum
, istep
);
1859 if (tmp_num
== NULL
)
1882 /* Return number of items in range/xrange (lo, hi, step). step > 0
1883 * required. Return a value < 0 if & only if the true value is too
1884 * large to fit in a signed long.
1887 get_len_of_range(long lo
, long hi
, long step
)
1889 /* -------------------------------------------------------------
1890 If lo >= hi, the range is empty.
1891 Else if n values are in the range, the last one is
1892 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1893 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1894 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1895 the RHS is non-negative and so truncation is the same as the
1896 floor. Letting M be the largest positive long, the worst case
1897 for the RHS numerator is hi=M, lo=-M-1, and then
1898 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1899 precision to compute the RHS exactly.
1900 ---------------------------------------------------------------*/
1903 unsigned long uhi
= (unsigned long)hi
;
1904 unsigned long ulo
= (unsigned long)lo
;
1905 unsigned long diff
= uhi
- ulo
- 1;
1906 n
= (long)(diff
/ (unsigned long)step
+ 1);
1912 builtin_range(PyObject
*self
, PyObject
*args
)
1914 long ilow
= 0, ihigh
= 0, istep
= 1;
1920 if (PyTuple_Size(args
) <= 1) {
1921 if (!PyArg_ParseTuple(args
,
1922 "l;range() requires 1-3 int arguments",
1925 return handle_range_longs(self
, args
);
1929 if (!PyArg_ParseTuple(args
,
1930 "ll|l;range() requires 1-3 int arguments",
1931 &ilow
, &ihigh
, &istep
)) {
1933 return handle_range_longs(self
, args
);
1937 PyErr_SetString(PyExc_ValueError
,
1938 "range() step argument must not be zero");
1942 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1944 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1946 if (bign
< 0 || (long)n
!= bign
) {
1947 PyErr_SetString(PyExc_OverflowError
,
1948 "range() result has too many items");
1954 for (i
= 0; i
< n
; i
++) {
1955 PyObject
*w
= PyInt_FromLong(ilow
);
1960 PyList_SET_ITEM(v
, i
, w
);
1966 PyDoc_STRVAR(range_doc
,
1967 "range([start,] stop[, step]) -> list of integers\n\
1969 Return a list containing an arithmetic progression of integers.\n\
1970 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1971 When step is given, it specifies the increment (or decrement).\n\
1972 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1973 These are exactly the valid indices for a list of 4 elements.");
1977 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1980 PyObject
*fin
= PySys_GetObject("stdin");
1981 PyObject
*fout
= PySys_GetObject("stdout");
1983 if (!PyArg_UnpackTuple(args
, "[raw_]input", 0, 1, &v
))
1987 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdin");
1991 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdout");
1994 if (PyFile_SoftSpace(fout
, 0)) {
1995 if (PyFile_WriteString(" ", fout
) != 0)
1998 if (PyFile_AsFile(fin
) && PyFile_AsFile(fout
)
1999 && isatty(fileno(PyFile_AsFile(fin
)))
2000 && isatty(fileno(PyFile_AsFile(fout
)))) {
2006 po
= PyObject_Str(v
);
2009 prompt
= PyString_AsString(po
);
2017 s
= PyOS_Readline(PyFile_AsFile(fin
), PyFile_AsFile(fout
),
2021 if (!PyErr_Occurred())
2022 PyErr_SetNone(PyExc_KeyboardInterrupt
);
2026 PyErr_SetNone(PyExc_EOFError
);
2029 else { /* strip trailing '\n' */
2030 size_t len
= strlen(s
);
2031 if (len
> PY_SSIZE_T_MAX
) {
2032 PyErr_SetString(PyExc_OverflowError
,
2033 "[raw_]input: input too long");
2037 result
= PyString_FromStringAndSize(s
, len
-1);
2044 if (PyFile_WriteObject(v
, fout
, Py_PRINT_RAW
) != 0)
2047 return PyFile_GetLine(fin
, -1);
2050 PyDoc_STRVAR(raw_input_doc
,
2051 "raw_input([prompt]) -> string\n\
2053 Read a string from standard input. The trailing newline is stripped.\n\
2054 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2055 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
2056 is printed without a trailing newline before reading.");
2060 builtin_reduce(PyObject
*self
, PyObject
*args
)
2062 static PyObject
*functools_reduce
= NULL
;
2064 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2065 "use functools.reduce()", 1) < 0)
2068 if (functools_reduce
== NULL
) {
2069 PyObject
*functools
= PyImport_ImportModule("functools");
2070 if (functools
== NULL
)
2072 functools_reduce
= PyObject_GetAttrString(functools
, "reduce");
2073 Py_DECREF(functools
);
2074 if (functools_reduce
== NULL
)
2077 return PyObject_Call(functools_reduce
, args
, NULL
);
2080 PyDoc_STRVAR(reduce_doc
,
2081 "reduce(function, sequence[, initial]) -> value\n\
2083 Apply a function of two arguments cumulatively to the items of a sequence,\n\
2084 from left to right, so as to reduce the sequence to a single value.\n\
2085 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2086 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2087 of the sequence in the calculation, and serves as a default when the\n\
2088 sequence is empty.");
2092 builtin_reload(PyObject
*self
, PyObject
*v
)
2094 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2098 return PyImport_ReloadModule(v
);
2101 PyDoc_STRVAR(reload_doc
,
2102 "reload(module) -> module\n\
2104 Reload the module. The module must have been successfully imported before.");
2108 builtin_repr(PyObject
*self
, PyObject
*v
)
2110 return PyObject_Repr(v
);
2113 PyDoc_STRVAR(repr_doc
,
2114 "repr(object) -> string\n\
2116 Return the canonical string representation of the object.\n\
2117 For most object types, eval(repr(object)) == object.");
2121 builtin_round(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2127 static char *kwlist
[] = {"number", "ndigits", 0};
2129 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "d|i:round",
2130 kwlist
, &number
, &ndigits
))
2140 number
= round(number
);
2145 return PyFloat_FromDouble(number
);
2148 PyDoc_STRVAR(round_doc
,
2149 "round(number[, ndigits]) -> floating point number\n\
2151 Round a number to a given precision in decimal digits (default 0 digits).\n\
2152 This always returns a floating point number. Precision may be negative.");
2155 builtin_sorted(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2157 PyObject
*newlist
, *v
, *seq
, *compare
=NULL
, *keyfunc
=NULL
, *newargs
;
2159 static char *kwlist
[] = {"iterable", "cmp", "key", "reverse", 0};
2162 /* args 1-4 should match listsort in Objects/listobject.c */
2163 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|OOi:sorted",
2164 kwlist
, &seq
, &compare
, &keyfunc
, &reverse
))
2167 newlist
= PySequence_List(seq
);
2168 if (newlist
== NULL
)
2171 callable
= PyObject_GetAttrString(newlist
, "sort");
2172 if (callable
== NULL
) {
2177 newargs
= PyTuple_GetSlice(args
, 1, 4);
2178 if (newargs
== NULL
) {
2180 Py_DECREF(callable
);
2184 v
= PyObject_Call(callable
, newargs
, kwds
);
2186 Py_DECREF(callable
);
2195 PyDoc_STRVAR(sorted_doc
,
2196 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2199 builtin_vars(PyObject
*self
, PyObject
*args
)
2204 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
2207 d
= PyEval_GetLocals();
2209 if (!PyErr_Occurred())
2210 PyErr_SetString(PyExc_SystemError
,
2211 "vars(): no locals!?");
2217 d
= PyObject_GetAttrString(v
, "__dict__");
2219 PyErr_SetString(PyExc_TypeError
,
2220 "vars() argument must have __dict__ attribute");
2227 PyDoc_STRVAR(vars_doc
,
2228 "vars([object]) -> dictionary\n\
2230 Without arguments, equivalent to locals().\n\
2231 With an argument, equivalent to object.__dict__.");
2235 builtin_sum(PyObject
*self
, PyObject
*args
)
2238 PyObject
*result
= NULL
;
2239 PyObject
*temp
, *item
, *iter
;
2241 if (!PyArg_UnpackTuple(args
, "sum", 1, 2, &seq
, &result
))
2244 iter
= PyObject_GetIter(seq
);
2248 if (result
== NULL
) {
2249 result
= PyInt_FromLong(0);
2250 if (result
== NULL
) {
2255 /* reject string values for 'start' parameter */
2256 if (PyObject_TypeCheck(result
, &PyBaseString_Type
)) {
2257 PyErr_SetString(PyExc_TypeError
,
2258 "sum() can't sum strings [use ''.join(seq) instead]");
2266 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2267 Assumes all inputs are the same type. If the assumption fails, default
2268 to the more general routine.
2270 if (PyInt_CheckExact(result
)) {
2271 long i_result
= PyInt_AS_LONG(result
);
2274 while(result
== NULL
) {
2275 item
= PyIter_Next(iter
);
2278 if (PyErr_Occurred())
2280 return PyInt_FromLong(i_result
);
2282 if (PyInt_CheckExact(item
)) {
2283 long b
= PyInt_AS_LONG(item
);
2284 long x
= i_result
+ b
;
2285 if ((x
^i_result
) >= 0 || (x
^b
) >= 0) {
2291 /* Either overflowed or is not an int. Restore real objects and process normally */
2292 result
= PyInt_FromLong(i_result
);
2293 temp
= PyNumber_Add(result
, item
);
2297 if (result
== NULL
) {
2304 if (PyFloat_CheckExact(result
)) {
2305 double f_result
= PyFloat_AS_DOUBLE(result
);
2308 while(result
== NULL
) {
2309 item
= PyIter_Next(iter
);
2312 if (PyErr_Occurred())
2314 return PyFloat_FromDouble(f_result
);
2316 if (PyFloat_CheckExact(item
)) {
2317 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
2318 f_result
+= PyFloat_AS_DOUBLE(item
);
2319 PyFPE_END_PROTECT(f_result
)
2323 if (PyInt_CheckExact(item
)) {
2324 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
2325 f_result
+= (double)PyInt_AS_LONG(item
);
2326 PyFPE_END_PROTECT(f_result
)
2330 result
= PyFloat_FromDouble(f_result
);
2331 temp
= PyNumber_Add(result
, item
);
2335 if (result
== NULL
) {
2344 item
= PyIter_Next(iter
);
2346 /* error, or end-of-sequence */
2347 if (PyErr_Occurred()) {
2353 temp
= PyNumber_Add(result
, item
);
2364 PyDoc_STRVAR(sum_doc
,
2365 "sum(sequence[, start]) -> value\n\
2367 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2368 of parameter 'start' (which defaults to 0). When the sequence is\n\
2369 empty, returns start.");
2373 builtin_isinstance(PyObject
*self
, PyObject
*args
)
2379 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
2382 retval
= PyObject_IsInstance(inst
, cls
);
2385 return PyBool_FromLong(retval
);
2388 PyDoc_STRVAR(isinstance_doc
,
2389 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2391 Return whether an object is an instance of a class or of a subclass thereof.\n\
2392 With a type as second argument, return whether that is the object's type.\n\
2393 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2394 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2398 builtin_issubclass(PyObject
*self
, PyObject
*args
)
2404 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
2407 retval
= PyObject_IsSubclass(derived
, cls
);
2410 return PyBool_FromLong(retval
);
2413 PyDoc_STRVAR(issubclass_doc
,
2414 "issubclass(C, B) -> bool\n\
2416 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2417 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2418 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2422 builtin_zip(PyObject
*self
, PyObject
*args
)
2425 const Py_ssize_t itemsize
= PySequence_Length(args
);
2427 PyObject
*itlist
; /* tuple of iterators */
2428 Py_ssize_t len
; /* guess at result length */
2431 return PyList_New(0);
2433 /* args must be a tuple */
2434 assert(PyTuple_Check(args
));
2436 /* Guess at result length: the shortest of the input lengths.
2437 If some argument refuses to say, we refuse to guess too, lest
2438 an argument like xrange(sys.maxint) lead us astray.*/
2439 len
= -1; /* unknown */
2440 for (i
= 0; i
< itemsize
; ++i
) {
2441 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2442 Py_ssize_t thislen
= _PyObject_LengthHint(item
, -2);
2449 else if (len
< 0 || thislen
< len
)
2453 /* allocate result list */
2455 len
= 10; /* arbitrary */
2456 if ((ret
= PyList_New(len
)) == NULL
)
2459 /* obtain iterators */
2460 itlist
= PyTuple_New(itemsize
);
2463 for (i
= 0; i
< itemsize
; ++i
) {
2464 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2465 PyObject
*it
= PyObject_GetIter(item
);
2467 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2468 PyErr_Format(PyExc_TypeError
,
2469 "zip argument #%zd must support iteration",
2471 goto Fail_ret_itlist
;
2473 PyTuple_SET_ITEM(itlist
, i
, it
);
2476 /* build result into ret list */
2477 for (i
= 0; ; ++i
) {
2479 PyObject
*next
= PyTuple_New(itemsize
);
2481 goto Fail_ret_itlist
;
2483 for (j
= 0; j
< itemsize
; j
++) {
2484 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
2485 PyObject
*item
= PyIter_Next(it
);
2487 if (PyErr_Occurred()) {
2495 PyTuple_SET_ITEM(next
, j
, item
);
2499 PyList_SET_ITEM(ret
, i
, next
);
2501 int status
= PyList_Append(ret
, next
);
2505 goto Fail_ret_itlist
;
2510 if (ret
!= NULL
&& i
< len
) {
2511 /* The list is too big. */
2512 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
2525 PyDoc_STRVAR(zip_doc
,
2526 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2528 Return a list of tuples, where each tuple contains the i-th element\n\
2529 from each of the argument sequences. The returned list is truncated\n\
2530 in length to the length of the shortest argument sequence.");
2533 static PyMethodDef builtin_methods
[] = {
2534 {"__import__", (PyCFunction
)builtin___import__
, METH_VARARGS
| METH_KEYWORDS
, import_doc
},
2535 {"abs", builtin_abs
, METH_O
, abs_doc
},
2536 {"all", builtin_all
, METH_O
, all_doc
},
2537 {"any", builtin_any
, METH_O
, any_doc
},
2538 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
2539 {"bin", builtin_bin
, METH_O
, bin_doc
},
2540 {"callable", builtin_callable
, METH_O
, callable_doc
},
2541 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2542 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
2543 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
2544 {"compile", (PyCFunction
)builtin_compile
, METH_VARARGS
| METH_KEYWORDS
, compile_doc
},
2545 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2546 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2547 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2548 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2549 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
2550 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
2551 {"format", builtin_format
, METH_VARARGS
, format_doc
},
2552 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2553 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2554 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2555 {"hash", builtin_hash
, METH_O
, hash_doc
},
2556 {"hex", builtin_hex
, METH_O
, hex_doc
},
2557 {"id", builtin_id
, METH_O
, id_doc
},
2558 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2559 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
2560 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2561 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2562 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2563 {"len", builtin_len
, METH_O
, len_doc
},
2564 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2565 {"map", builtin_map
, METH_VARARGS
, map_doc
},
2566 {"max", (PyCFunction
)builtin_max
, METH_VARARGS
| METH_KEYWORDS
, max_doc
},
2567 {"min", (PyCFunction
)builtin_min
, METH_VARARGS
| METH_KEYWORDS
, min_doc
},
2568 {"next", builtin_next
, METH_VARARGS
, next_doc
},
2569 {"oct", builtin_oct
, METH_O
, oct_doc
},
2570 {"open", (PyCFunction
)builtin_open
, METH_VARARGS
| METH_KEYWORDS
, open_doc
},
2571 {"ord", builtin_ord
, METH_O
, ord_doc
},
2572 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2573 {"print", (PyCFunction
)builtin_print
, METH_VARARGS
| METH_KEYWORDS
, print_doc
},
2574 {"range", builtin_range
, METH_VARARGS
, range_doc
},
2575 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
2576 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
2577 {"reload", builtin_reload
, METH_O
, reload_doc
},
2578 {"repr", builtin_repr
, METH_O
, repr_doc
},
2579 {"round", (PyCFunction
)builtin_round
, METH_VARARGS
| METH_KEYWORDS
, round_doc
},
2580 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2581 {"sorted", (PyCFunction
)builtin_sorted
, METH_VARARGS
| METH_KEYWORDS
, sorted_doc
},
2582 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2583 #ifdef Py_USING_UNICODE
2584 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
2586 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2587 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
2591 PyDoc_STRVAR(builtin_doc
,
2592 "Built-in functions, exceptions, and other objects.\n\
2594 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2597 _PyBuiltin_Init(void)
2599 PyObject
*mod
, *dict
, *debug
;
2600 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2601 builtin_doc
, (PyObject
*)NULL
,
2602 PYTHON_API_VERSION
);
2605 dict
= PyModule_GetDict(mod
);
2607 #ifdef Py_TRACE_REFS
2608 /* __builtin__ exposes a number of statically allocated objects
2609 * that, before this code was added in 2.3, never showed up in
2610 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2611 * result, programs leaking references to None and False (etc)
2612 * couldn't be diagnosed by examining sys.getobjects(0).
2614 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2616 #define ADD_TO_ALL(OBJECT) (void)0
2619 #define SETBUILTIN(NAME, OBJECT) \
2620 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2624 SETBUILTIN("None", Py_None
);
2625 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2626 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2627 SETBUILTIN("False", Py_False
);
2628 SETBUILTIN("True", Py_True
);
2629 SETBUILTIN("basestring", &PyBaseString_Type
);
2630 SETBUILTIN("bool", &PyBool_Type
);
2631 SETBUILTIN("memoryview", &PyMemoryView_Type
);
2632 SETBUILTIN("bytearray", &PyByteArray_Type
);
2633 SETBUILTIN("bytes", &PyString_Type
);
2634 SETBUILTIN("buffer", &PyBuffer_Type
);
2635 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2636 #ifndef WITHOUT_COMPLEX
2637 SETBUILTIN("complex", &PyComplex_Type
);
2639 SETBUILTIN("dict", &PyDict_Type
);
2640 SETBUILTIN("enumerate", &PyEnum_Type
);
2641 SETBUILTIN("file", &PyFile_Type
);
2642 SETBUILTIN("float", &PyFloat_Type
);
2643 SETBUILTIN("frozenset", &PyFrozenSet_Type
);
2644 SETBUILTIN("property", &PyProperty_Type
);
2645 SETBUILTIN("int", &PyInt_Type
);
2646 SETBUILTIN("list", &PyList_Type
);
2647 SETBUILTIN("long", &PyLong_Type
);
2648 SETBUILTIN("object", &PyBaseObject_Type
);
2649 SETBUILTIN("reversed", &PyReversed_Type
);
2650 SETBUILTIN("set", &PySet_Type
);
2651 SETBUILTIN("slice", &PySlice_Type
);
2652 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2653 SETBUILTIN("str", &PyString_Type
);
2654 SETBUILTIN("super", &PySuper_Type
);
2655 SETBUILTIN("tuple", &PyTuple_Type
);
2656 SETBUILTIN("type", &PyType_Type
);
2657 SETBUILTIN("xrange", &PyRange_Type
);
2658 #ifdef Py_USING_UNICODE
2659 SETBUILTIN("unicode", &PyUnicode_Type
);
2661 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2662 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2673 /* Helper for filter(): filter a tuple through a function */
2676 filtertuple(PyObject
*func
, PyObject
*tuple
)
2680 Py_ssize_t len
= PyTuple_Size(tuple
);
2683 if (PyTuple_CheckExact(tuple
))
2686 tuple
= PyTuple_New(0);
2690 if ((result
= PyTuple_New(len
)) == NULL
)
2693 for (i
= j
= 0; i
< len
; ++i
) {
2694 PyObject
*item
, *good
;
2697 if (tuple
->ob_type
->tp_as_sequence
&&
2698 tuple
->ob_type
->tp_as_sequence
->sq_item
) {
2699 item
= tuple
->ob_type
->tp_as_sequence
->sq_item(tuple
, i
);
2703 PyErr_SetString(PyExc_TypeError
, "filter(): unsubscriptable tuple");
2706 if (func
== Py_None
) {
2711 PyObject
*arg
= PyTuple_Pack(1, item
);
2716 good
= PyEval_CallObject(func
, arg
);
2723 ok
= PyObject_IsTrue(good
);
2726 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2733 if (_PyTuple_Resize(&result
, j
) < 0)
2744 /* Helper for filter(): filter a string through a function */
2747 filterstring(PyObject
*func
, PyObject
*strobj
)
2751 Py_ssize_t len
= PyString_Size(strobj
);
2752 Py_ssize_t outlen
= len
;
2754 if (func
== Py_None
) {
2755 /* If it's a real string we can return the original,
2756 * as no character is ever false and __getitem__
2757 * does return this character. If it's a subclass
2758 * we must go through the __getitem__ loop */
2759 if (PyString_CheckExact(strobj
)) {
2764 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2767 for (i
= j
= 0; i
< len
; ++i
) {
2771 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2774 if (func
==Py_None
) {
2777 PyObject
*arg
, *good
;
2778 arg
= PyTuple_Pack(1, item
);
2783 good
= PyEval_CallObject(func
, arg
);
2789 ok
= PyObject_IsTrue(good
);
2794 if (!PyString_Check(item
)) {
2795 PyErr_SetString(PyExc_TypeError
, "can't filter str to str:"
2796 " __getitem__ returned different type");
2800 reslen
= PyString_GET_SIZE(item
);
2802 PyString_AS_STRING(result
)[j
++] =
2803 PyString_AS_STRING(item
)[0];
2805 /* do we need more space? */
2806 Py_ssize_t need
= j
;
2808 /* calculate space requirements while checking for overflow */
2809 if (need
> PY_SSIZE_T_MAX
- reslen
) {
2816 if (need
> PY_SSIZE_T_MAX
- len
) {
2828 need
= need
- i
- 1;
2831 assert(outlen
>= 0);
2833 if (need
> outlen
) {
2834 /* overallocate, to avoid reallocations */
2835 if (outlen
> PY_SSIZE_T_MAX
/ 2) {
2840 if (need
<2*outlen
) {
2843 if (_PyString_Resize(&result
, need
)) {
2850 PyString_AS_STRING(result
) + j
,
2851 PyString_AS_STRING(item
),
2861 _PyString_Resize(&result
, j
);
2870 #ifdef Py_USING_UNICODE
2871 /* Helper for filter(): filter a Unicode object through a function */
2874 filterunicode(PyObject
*func
, PyObject
*strobj
)
2877 register Py_ssize_t i
, j
;
2878 Py_ssize_t len
= PyUnicode_GetSize(strobj
);
2879 Py_ssize_t outlen
= len
;
2881 if (func
== Py_None
) {
2882 /* If it's a real string we can return the original,
2883 * as no character is ever false and __getitem__
2884 * does return this character. If it's a subclass
2885 * we must go through the __getitem__ loop */
2886 if (PyUnicode_CheckExact(strobj
)) {
2891 if ((result
= PyUnicode_FromUnicode(NULL
, len
)) == NULL
)
2894 for (i
= j
= 0; i
< len
; ++i
) {
2895 PyObject
*item
, *arg
, *good
;
2898 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2901 if (func
== Py_None
) {
2904 arg
= PyTuple_Pack(1, item
);
2909 good
= PyEval_CallObject(func
, arg
);
2915 ok
= PyObject_IsTrue(good
);
2920 if (!PyUnicode_Check(item
)) {
2921 PyErr_SetString(PyExc_TypeError
,
2922 "can't filter unicode to unicode:"
2923 " __getitem__ returned different type");
2927 reslen
= PyUnicode_GET_SIZE(item
);
2929 PyUnicode_AS_UNICODE(result
)[j
++] =
2930 PyUnicode_AS_UNICODE(item
)[0];
2932 /* do we need more space? */
2933 Py_ssize_t need
= j
+ reslen
+ len
- i
- 1;
2935 /* check that didnt overflow */
2936 if ((j
> PY_SSIZE_T_MAX
- reslen
) ||
2937 ((j
+ reslen
) > PY_SSIZE_T_MAX
- len
) ||
2938 ((j
+ reslen
+ len
) < i
) ||
2939 ((j
+ reslen
+ len
- i
) <= 0)) {
2945 assert(outlen
>= 0);
2947 if (need
> outlen
) {
2949 to avoid reallocations */
2950 if (need
< 2 * outlen
) {
2951 if (outlen
> PY_SSIZE_T_MAX
/ 2) {
2959 if (PyUnicode_Resize(
2960 &result
, need
) < 0) {
2966 memcpy(PyUnicode_AS_UNICODE(result
) + j
,
2967 PyUnicode_AS_UNICODE(item
),
2968 reslen
*sizeof(Py_UNICODE
));
2976 PyUnicode_Resize(&result
, j
);